前情提要:
以下實作 手動認證 user 的方式逐步說明
在官方文件的Authentication章節,有提到 Laravel 內建使用者驗證的服務,但得先確認有沒有安裝 laravel/ui 這套件
composer require laravel/ui
後續若如果使用 php artisan ui vue --auth
時
甚至會提醒提醒npm有無安裝。
public function loginAPI(Request $request)
{
$credentials = $request->only('email', 'password');
//先確認user資訊是否正確
if (Auth::attempt($credentials)) {
do {
//建立隨機亂碼
$loginToken = Str::random(60);
$checkTokenExist = User::where('remember_token', '=', $loginToken)->first();
} while ($checkTokenExist);
//建立token並寫入使用時間
$user = User::where('email', '=', $request->email)->first();
$user->remember_token = $loginToken;
$user->token_expire_time = date('Y/m/d H:i:s', time() + 10 * 60);
$user->save();
$response = array("token" => $user->remember_token, "expire_time" => $user->token_expire_time);
$httpstatus = 200;
} else {
//user not exist or input infomation error
$response = "login error";
$httpstatus = 400;
}
return response()->json(['message' => $response], $httpstatus);
}
public function userInfo(Request $request)
{
$inputToken = $request->remember_token;
if ($inputToken !== null & $inputToken !== "") {
$userA = User::where('remember_token', '=', $inputToken)->first();
if ($userA ){
return $userA ;
}
}
}
AuthServiceProvider
public function boot()
{
$this->registerPolicies();
Auth::viaRequest('token', function ($request) {
$user = User::where('remember_token', $request->remember_token)->first();
return $user;
}
controller部分只需要這樣寫
public function userInfo(Request $request)
{
//寫法1
return $request->user();
//寫法2
return Auth::user();
}
雖然在db欄位中有以下欄位
但透過 Model 中的 hidden 去隱藏以下資訊
protected $hidden = [ 'password','remember_token','email_verified_at','updated_at','deleted_at'
];
Eloquent ORM 只會提供 postman 截圖的response欄位。
參考資料
https://laravel.com/docs/7.x/authentication
https://ithelp.ithome.com.tw/articles/10229123
https://learnku.com/docs/laravel/7.x/authentication/7474
https://dev.to/msamgan/php-artisan-make-auth-in-laravel-6-0-hc
https://kirin.idv.tw/laravel-user-authentication-basic-step/