Untitled

 avatar
unknown
php
2 years ago
1.2 kB
4
Indexable
// Sign in user and issue access & refresh tokens
    public function login(object $request): object
    {
        // Validate user credentials
        if (!Auth::attempt($request->only(['email', 'password']))) {
            return $this->failedRequest('', 'Invalid email address or password', 401);
        }

        // Get the user
        $user = User::where('email', $request->email)->first();

        // If user is suspended throw error
        if ($user->suspended) {
            return $this->failedRequest("", 'Invalid email address or password', 401);
        }

        // Receive tokens
        $tokens = $this->issueAccessAndRefreshTokens($request->email, $request->password);

        // Attach tokens to user
        $user['access_token'] = $tokens['access_token'];
        $user['refresh_token'] = $tokens['refresh_token'];

        // Create cookies
        $accessCookie = cookie('access_token', $tokens['access_token'], 30, null, 'http://localhost:5176');
        $refreshCookie = cookie('refresh_token', $tokens['refresh_token'], 43200, null, 'http://localhost:5176', null, false);

        return $this->successfullRequest($user, 'User successfully logged in')->withCookie($accessCookie)->withCookie($refreshCookie);
    }
Editor is loading...