Completed
Push — master ( fcc0ff...8f456d )
by Mahmoud
03:36
created

ApiAuthenticationTask::login()   A

Complexity

Conditions 3
Paths 3

Size

Total Lines 18
Code Lines 10

Duplication

Lines 0
Ratio 0 %

Importance

Changes 1
Bugs 0 Features 0
Metric Value
c 1
b 0
f 0
dl 0
loc 18
rs 9.4285
cc 3
eloc 10
nc 3
nop 2
1
<?php
2
3
namespace App\Containers\Authentication\Tasks;
4
5
use App\Containers\Authentication\Adapters\JwtAuthAdapter;
6
use App\Containers\Authentication\Exceptions\AuthenticationFailedException;
7
use App\Containers\Authentication\Exceptions\MissingTokenException;
8
use Exception;
9
use Illuminate\Auth\AuthManager as LaravelAuthManager;
10
11
/**
12
 * Class ApiAuthenticationTask.
13
 *
14
 * @author Mahmoud Zalt <[email protected]>
15
 */
16
class ApiAuthenticationTask
17
{
18
19
    /**
20
     * @var \App\Containers\Authentication\Adapters\JwtAuthAdapter
21
     */
22
    private $jwtAuthAdapter;
23
24
    /**
25
     * @var \Illuminate\Auth\AuthManager
26
     */
27
    private $authManager;
28
29
    /**
30
     * AuthenticationTask constructor.
31
     *
32
     * @param \App\Containers\Authentication\Adapters\JwtAuthAdapter $jwtAuthAdapter
33
     * @param \Illuminate\Auth\AuthManager                              $authManager
34
     */
35
    public function __construct(JwtAuthAdapter $jwtAuthAdapter, LaravelAuthManager $authManager)
36
    {
37
        $this->jwtAuthAdapter = $jwtAuthAdapter;
38
        $this->authManager = $authManager;
39
    }
40
41
    /**
42
     * @param $email
43
     * @param $password
44
     *
45
     * @return mixed
46
     */
47
    public function login($email, $password)
48
    {
49
        try {
50
            $token = $this->jwtAuthAdapter->attempt([
51
                'email'    => $email,
52
                'password' => $password,
53
            ]);
54
55
            if (!$token) {
56
                throw new AuthenticationFailedException();
57
            }
58
        } catch (Exception $e) {
59
            // something went wrong whilst attempting to encode the token
60
            throw (new AuthenticationFailedException())->debug($e);
61
        }
62
63
        return $token;
64
    }
65
66
    /**
67
     * login user from it's object. (no username and password needed)
68
     * useful for logging in new created users (during registration).
69
     *
70
     * @param $user
71
     *
72
     * @return mixed
73
     */
74
    public function loginFromObject($user)
75
    {
76
        $token = $this->generateTokenFromObject($user);
77
78
        // manually authenticate the user
79
        $this->jwtAuthAdapter->authenticateViaToken($token);
80
81
        // inject the token on the model
82
        $user = $user->injectToken($token);
83
84
        return $user;
85
    }
86
87
    /**
88
     * get the user object of the current authenticated user
89
     * inject the token on it if a token is provided.
90
     *
91
     * @param null $token
92
     *
93
     * @return mixed
94
     */
95
    public function getAuthenticatedUser($token = null)
96
    {
97
        if (!$user = $this->authManager->user()) {
98
            throw new AuthenticationFailedException('User is not logged in.');
99
        }
100
101
        return $token ? $user->injectToken($token) : $user;
102
    }
103
104
    /**
105
     * @param $authorizationHeader
106
     *
107
     * @throws \App\Containers\Authentication\Tasks\MissingTokenException
108
     *
109
     * @return bool
110
     */
111
    public function logout($authorizationHeader)
112
    {
113
        // remove the `Bearer` string from the header and keep only the token
114
        $token = str_replace('Bearer', '', $authorizationHeader);
115
116
        $ok = $this->jwtAuthAdapter->invalidate($token);
117
118
        if (!$ok) {
119
            throw new MissingTokenException();
120
        }
121
122
        return true;
123
    }
124
125
    /**
126
     * login/authenticate user and return its token.
127
     *
128
     * @param $user
129
     *
130
     * @return mixed
131
     */
132
    public function generateTokenFromObject($user)
133
    {
134
        try {
135
            $token = $this->jwtAuthAdapter->fromUser($user);
136
        } catch (Exception $e) {
137
            throw (new AuthenticationFailedException())->debug($e);
138
        }
139
140
        return $token;
141
    }
142
143
}
144