Skip to content

2. Login

dungda-0794 edited this page Feb 7, 2023 · 18 revisions

Login use service from package.

Make login function the following: Note: Validation & logic login inside service

# 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

Flow login inside service package as follows:

1. Validator

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',
    ]);
}

2. Find item by attribute

$item = $this->repository->findByAttribute($attributes);

3. Compare hash password

if (! $item || ! Hash::check(Arr::get($credentials, $this->passwd()), $item->{$this->passwd()})) {
    throw ValidationException::withMessages([
        'message' => $this->getFailedLoginMessage(),
    ]);
}

4. Generate accessToken & refreshToken from jwt

$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'],
],
  • $itemArr is 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']);
    },
);

Sun_ Auth _ Architecture Design-Login (1)

Clone this wiki locally