Authenticate.php 1.33 KB
Newer Older
Jacob Priddy's avatar
Jacob Priddy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
<?php

namespace Source\UseCases\Users\Authenticate;

use Carbon\Carbon;
use Source\Entities\Token;
use Illuminate\Support\Str;
use Source\Gateways\Users\UsersRepository;
use Source\Gateways\Tokens\TokensRepository;
use Source\Exceptions\AuthorizationException;

class Authenticate implements AuthenticateUseCase {
    protected UsersRepository $users;

    protected TokensRepository $tokens;

    public function __construct(UsersRepository $users, TokensRepository $tokens) {
        $this->users = $users;
        $this->tokens = $tokens;
    }

    /**
     * @inheritDoc
     */
    public function attempt(Presenter $presenter, array $credentials): void {
        $email = $credentials['email'] ?? null;
        $password = $credentials['password'] ?? null;

        if (!$email || !$password) {
            throw new AuthorizationException();
        }

        $user = $this->users->findByCredentials(strtolower($email), $password);

        if (!$user) {
            throw new AuthorizationException();
        }

        $token = $this->tokens->create(
            new Token(
                0,
                $user->getId(),
                Str::random(60),
                null,
                Carbon::now()->days(2)
            )
        );

        $response = new ResponseModel($user, $token);

        $presenter->present($response);
    }
}