Приложение Laravel:
Код: Выделить всё
AuthController.phpКод: Выделить всё
public function login(Request $request): JsonResponse {
try {
// describe all the variables
$credentials = $request->only('email', 'password');
// call a validator rules
$validatorRules = $this->loginValidatorRules();
// make a validation
$validator = Validator::make($credentials, $validatorRules['rules'], $validatorRules['messages']);
// validate the validation rules
if ($validator->fails()) {
// return to validation exception
throw new ValidationException($validator, 422);
}
// login step
$user = User::where('email', $credentials['email'])->first();
// check if the user is not registered
if (empty($user)) {
throw new Exception('akun belum terdaftar, silahkan daftar terlebih dahulu.', 404);
}
// compare the text password (hashed) with the database password
$isPassword = Hash::check($credentials['password'], $user->password);
// check the password
if (!$isPassword) {
throw new Exception('password yang dimasukkan salah, silahkan coba lagi.', 401);
}
// attempt the token auth
$token = Auth::guard('api')->attempt($credentials);
// check the token
if (!$token) {
throw new Exception('terjadi kesalahan pada saat autentikasi, silahkan hubungi admin (kode error: token).', 401);
}
// create a refresh token
$plainRefreshToken = Str::random(60);
// hash the plain refresh token
$hashedRefreshToken = hash('sha256', $plainRefreshToken);
// store the hashed refresh token to user database
User::where('id_user', $user->id_user)->update(['refresh_token' => $hashedRefreshToken]);
// store the access token to cookie
$accessTokenCookie = cookie('access_token', $token, Auth::factory()->getTTL(), null, null, true, true, false, 'None');
// store the plain refresh token to cookie
$plainRefreshTokenCookie = cookie('refresh_token', $plainRefreshToken, 2880, null, null, true, true, false, 'None');
// create payload data
$payload = [
'data' => [
'session' => $this->respondWithToken($token, $plainRefreshToken),
'user' => [
'id_user' => $user->id_user,
'role' => $user->getRoleNames(),
'name' => $user->name,
'email' => $user->email,
'email_verified_at' => $user->email_verified_at,
],
]
];
// return success response
return ResponseJson::responseJson('success', 'Login berhasil', 200, 'Login telah berhasil', $payload)
->cookie($accessTokenCookie)
->cookie($plainRefreshTokenCookie);
} catch (ValidationException $exception) {
// return error validation message
return ResponseJson::responseJson('error', 'Validasi gagal', $exception->response, $exception->errors());
} catch (Exception $exception) {
dd($exception);
// return error credentials for login message
return ResponseJson::responseJson('error', 'Login gagal', $exception->getCode(), $exception->getMessage());
}
}
Код: Выделить всё
cors.phpКод: Выделить всё
Подробнее здесь: [url]https://stackoverflow.com/questions/79060533/cookie-not-store-to-vue-app-from-laravel-app[/url]