-
Notifications
You must be signed in to change notification settings - Fork 3
2. Login
dungda-0794 edited this page Feb 7, 2023
·
18 revisions
Note: Validation & logic login inside service
Make login function the following:
# App\Http\Controllers\AuthController
public function login(Request $request)
{
$params = $request->only(['username', 'password']);
$rs = $this->service->login($params, [], function ($entity) {
return $entity->only(['id', 'email', 'username']);
});
return response()->json($rs['auth']);
}We only get the exact parameters from the client
public function login(array $credentials = [], ?array $attributes = [], ?callable $callback = null): array
{
$this->loginValidator($credentials)->validate();
...
}
...
protected function loginValidator(array $data)
{
return Validator::make($data, [
$this->username() => 'required',
$this->passwd() => 'required',
]);
}$item = $this->repository->findByAttribute($attributes);if (! $item || ! Hash::check(Arr::get($credentials, $this->passwd()), $item->{$this->passwd()})) {
throw ValidationException::withMessages([
'message' => $this->getFailedLoginMessage(),
]);
}$payload = $this->jwt->make($itemArr)->toArray();
$payloadRefresh = $this->jwt->make($itemArr, true)->toArray();
$jwt = $this->jwt->encode($payload);
$refresh = $this->jwt->encode($payloadRefresh, true);Method login will return an array
'item' => $itemArr,
'auth' => [
'refresh_token' => $refresh,
'access_token' => $jwt,
'token_type' => 'bearer',
'expires_at' => $payload['exp'],
],-
$itemArris array of object user model. We can custom by callback function as follows
$rs = $this->service->login($params, [], function ($entity) {
// Custom $itemArr
return $entity->only(['id', 'email', 'username']);
});BTW: Also we can change the sql query for the login flow as follows
$rs = $this->service->login(
$params,
[
'username' => $params['username'],
'is_active' => true, // custom query attributes
],
function ($entity) {
return $entity->only(['id', 'email', 'username']);
},
);