Laravel 5.8 JWT API仅当用户的状态为活动时才登录



我正在尝试实现,如果你试图用他的凭据登录,那么登录系统会检查帐户状态,如果状态为ACTIVE,则登录,否则会显示错误通知,你的帐户已被阻止。

我的数据库列名及其值

account_status

ACTIVEBLOCKED

我在控制器中尝试过,但它不起作用

<?php
namespace AppHttpControllersApi;
use AppHttpControllersController;
use AppHttpRequestsUserLoginRequest;
use AppHttpResourcesUser as UserResource;
use AppUser;
class LoginController extends Controller
{
public function login(UserLoginRequest $request)
{
if (!$token = auth()->attempt($request->only(['mobile_number', 'password']))) {
return response()->json([
'errors' => [
'mobile_number' => ['Sorry we cant find you with those details.'],
],
], 422);
};
return (new UserResource($request->user()))->additional([
'meta' => [
'token' => $token,
],
]);
}
public function logout()
{
auth()->logout();
}
}

试试这个:

use Auth;
if (Auth::attempt(['email' => $email, 'password' => $password, 'account_status'=>'ACTIVE'])) {
// Authentication passed...
return (new UserResource($request->user()))->additional([
'meta' => [
'token' => $token,
],
]);
}
return response()->json([
'errors' => ["email" => "Something wrong"]
]);

此代码非常干净且资源充足:

use IlluminateSupportFacadesAuth;
use TymonJWTAuthExceptionsUserNotDefinedException;
use TymonJWTAuthExceptionsTokenInvalidException;
public function login(LoginRequest $request)
{
$credentials = $request->validated();
$rememberMe = $request->input('remember_me');
try {
if (auth()->attempt($credentials)) {
$user = Auth::user();
if (!auth()->user()->status) {
throw new UserNotDefinedException('user is inactive');
}
$token = ($rememberMe == true) ? JWTAuth::customClaims(['exp' => now()->addDays(1000)->timestamp,])->fromUser($user) : JWTAuth::fromUser($user);
return $this->respondWithToken($token);
} else {
throw new TokenInvalidException('user credential is invalid');
}
} catch (UserNotDefinedException $e) {
return response()->json(['message' => __('messages.login.user.deactivate')], Response::HTTP_BAD_REQUEST);
} catch (TokenInvalidException $e) {
return response()->json(['message' => __('messages.login.invalid.credentials')], Response::HTTP_UNPROCESSABLE_ENTITY);
};
}

相关内容

  • 没有找到相关文章

最新更新