|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace App\Http\Controllers\API; |
|
4
|
|
|
|
|
5
|
|
|
use App\Http\Requests\API\UserLoginRequest; |
|
6
|
|
|
use Exception; |
|
7
|
|
|
use Illuminate\Http\JsonResponse; |
|
8
|
|
|
use Illuminate\Log\Logger; |
|
9
|
|
|
use Tymon\JWTAuth\JWTAuth; |
|
10
|
|
|
|
|
11
|
|
|
/** |
|
12
|
|
|
* @group 1. Authentication |
|
13
|
|
|
*/ |
|
14
|
|
|
class AuthController extends Controller |
|
15
|
|
|
{ |
|
16
|
|
|
private $auth; |
|
17
|
|
|
private $logger; |
|
18
|
|
|
|
|
19
|
|
|
public function __construct(JWTAuth $auth, Logger $logger) |
|
20
|
|
|
{ |
|
21
|
|
|
$this->auth = $auth; |
|
22
|
|
|
$this->logger = $logger; |
|
23
|
|
|
} |
|
24
|
|
|
|
|
25
|
|
|
/** |
|
26
|
|
|
* Log a user in. |
|
27
|
|
|
* |
|
28
|
|
|
* Koel uses [JSON Web Tokens](https://jwt.io/) (JWT) for authentication. |
|
29
|
|
|
* After the user has been authenticated, a random "token" will be returned. |
|
30
|
|
|
* This token should then be saved in a local storage and used as an `Authorization: Bearer` header |
|
31
|
|
|
* for consecutive calls. |
|
32
|
|
|
* |
|
33
|
|
|
* Notice: The token is valid for a week, after that the user will need to log in again. |
|
34
|
|
|
* |
|
35
|
|
|
* @bodyParam email string required The user's email. Example: [email protected] |
|
36
|
|
|
* @bodyParam password string required The password. Example: SoSecureMuchW0w |
|
37
|
|
|
* |
|
38
|
|
|
* @response { |
|
39
|
|
|
* "token": "<a-random-string>" |
|
40
|
|
|
* } |
|
41
|
|
|
* @reponse 401 { |
|
42
|
|
|
* "message": "Invalid credentials" |
|
43
|
|
|
* } |
|
44
|
|
|
* |
|
45
|
|
|
* @return JsonResponse |
|
46
|
|
|
*/ |
|
47
|
|
|
public function login(UserLoginRequest $request) |
|
48
|
|
|
{ |
|
49
|
|
|
$token = $this->auth->attempt($request->only('email', 'password')); |
|
50
|
|
|
abort_unless($token, 401, 'Invalid credentials'); |
|
|
|
|
|
|
51
|
|
|
|
|
52
|
|
|
return response()->json(compact('token')); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
/** |
|
56
|
|
|
* Log the current user out. |
|
57
|
|
|
* |
|
58
|
|
|
* @return JsonResponse |
|
59
|
|
|
*/ |
|
60
|
|
|
public function logout() |
|
61
|
|
|
{ |
|
62
|
|
|
if ($token = $this->auth->getToken()) { |
|
63
|
|
|
try { |
|
64
|
|
|
$this->auth->invalidate($token); |
|
65
|
|
|
} catch (Exception $e) { |
|
66
|
|
|
$this->logger->error($e); |
|
67
|
|
|
} |
|
68
|
|
|
} |
|
69
|
|
|
|
|
70
|
|
|
return response()->json(); |
|
71
|
|
|
} |
|
72
|
|
|
} |
|
73
|
|
|
|