php 切换到mongoDB auth::后,尝试不起作用laravel 9

afdcj2ne  于 2023-01-24  发布在  PHP
关注(0)|答案(1)|浏览(110)

下面是我的代码,它在MySQL中运行良好,但当我将MySQL切换到MongoDB时,注册工作正常,但登录尝试返回false。
我正在为我的项目创建一个用于登录和注册的API。
我还在laravel 9中实现了JWT令牌包。

namespace App\Http\Controllers\Api;
use App\Http\Controllers\Controller;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Auth;
use Illuminate\Support\Facades\Hash;
use App\Models\User;
use Carbon\Carbon;

class AuthController extends Controller
{
 public function __construct()
{
    $this->middleware('auth:api', ['except' => ['login','register']]);
}

public function login(Request $request)
{
$request->validate([
'strEmail' => 'required|string|email',
'strPassword' => 'required|string',
]);
$credentials = $request->only('strEmail', 'strPassword');
    
$token = Auth::attempt($credentials);
if (!$token) {
return response()->json([
'status' => 'error',
'message' => 'Unauthorized',
], 401);
}

$user = Auth::user();

return response()->json([
'status' => 'success',
'user' => $user,
'authorisation' => [
'token' => $token,
'type' => 'bearer',
]
]);

}

public function register(Request $request){
$request->validate([
'strFirstName' => 'required|string|max:255',
'strLastName' => 'required|string|max:255',
'strEmail' => 'required|string|email|max:255|unique:users',
'strPassword' => 'required|string|min:6',   
]);

$user = User::create([
'strFirstName' => $request->strFirstName,
'strLastName' => $request->strLastName,
'strEmail' => $request->strEmail,
'strPassword' => Hash::make($request->strPassword),
'isLogin' => 1,
'LastLoginDate'=> Carbon::now(),
'EnterDatetime' => new \DateTime(),
'IP' => \Request::ip(),
]);

$token = Auth::login($user);
return response()->json([
'status' => 'success',
'message' => 'User created successfully',
'user' => $user,
'authorisation' => [
'token' => $token,
'type' => 'bearer',
]
]);
}
}

下面是用户模型

use Illuminate\Contracts\Auth\MustVerifyEmail;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Jenssegers\Mongodb\Auth\User as Authenticatable;
use Illuminate\Notifications\Notifiable;
use PHPOpenSourceSaver\JWTAuth\Contracts\JWTSubject;
use Jenssegers\Mongodb\Eloquent\Model;

class User extends Authenticatable implements JWTSubject
{
use HasFactory, Notifiable;

/**
 * The attributes that are mass assignable.
 *
 * @var array<int, string>
 */

请帮帮我。
我已经尝试了这个代码与MySQL和注册和登录工作与MySQL。

bt1cpqcv

bt1cpqcv1#

终于解决了,Auth只接受密码字段为“密码”。

相关问题