AuthController.php 1.48 KB
Newer Older
Jacob Priddy's avatar
Jacob Priddy committed
1
2
3
4
5
6
7
8
9
10
11
12
13
<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use Illuminate\Http\JsonResponse;
use Illuminate\Auth\AuthenticationException;
use Source\Exceptions\AuthorizationException;
use Illuminate\Validation\ValidationException;
use Source\Exceptions\EntityNotFoundException;
use Source\UseCases\Users\Authenticate\APIPresenter;
use Source\UseCases\Users\Authenticate\AuthenticateUseCase;

Jacob Priddy's avatar
Jacob Priddy committed
14
class AuthController extends ApiController {
Jacob Priddy's avatar
Jacob Priddy committed
15
16
17
18
19
20
21
22
23
24
25
26
27
28
    protected Request $request;

    public function __construct(Request $request) {
        $this->request = $request;
    }

    /**
     * @param AuthenticateUseCase $authenticateUseCase
     * @return JsonResponse
     * @throws ValidationException
     * @throws AuthenticationException
     * @throws EntityNotFoundException
     */
    public function login(AuthenticateUseCase $authenticateUseCase): JsonResponse {
Jacob Priddy's avatar
Jacob Priddy committed
29
30
31
32
33
34
35
        $this->validate(
            $this->request,
            [
                'email' => 'required',
                'password' => 'required',
            ]
        );
Jacob Priddy's avatar
Jacob Priddy committed
36
37
38
39
40
41
42
43
44

        $presenter = new APIPresenter();

        try {
            $authenticateUseCase->attempt($presenter, $this->request->all());
        } catch (AuthorizationException $e) {
            throw new AuthenticationException();
        }

Jacob Priddy's avatar
Jacob Priddy committed
45
46
47
48
49
        return $this->respondWithData($presenter->getViewModel())->cookie(
            'api_token',
            $presenter->getViewModel()['token']['value'],
            $presenter->getViewModel()['token']['minutes']
        );
Jacob Priddy's avatar
Jacob Priddy committed
50
51
    }
}