1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Autumn\JWTAuth\Http\Controllers; |
4
|
|
|
|
5
|
|
|
use Validator; |
6
|
|
|
use Tymon\JWTAuth\JWTAuth; |
7
|
|
|
use Illuminate\Http\Request; |
8
|
|
|
use RainLab\User\Models\User; |
9
|
|
|
use Illuminate\Routing\Controller as BaseController; |
10
|
|
|
use Tymon\JWTAuth\Exceptions\JWTException; |
11
|
|
|
|
12
|
|
|
class AuthController extends BaseController |
13
|
|
|
{ |
14
|
|
|
protected $auth; |
15
|
|
|
|
16
|
|
|
public function __construct(JWTAuth $auth) |
17
|
|
|
{ |
18
|
|
|
$this->auth = $auth; |
19
|
|
|
} |
20
|
|
|
|
21
|
|
|
public function authenticate(Request $request) |
22
|
|
|
{ |
23
|
|
|
try { |
24
|
|
|
if (!$token = $this->auth->attempt($request->only('email', 'password'))) { |
25
|
|
|
return response()->json([ |
26
|
|
|
'error' => 'invalid_credentials' |
27
|
|
|
], 401); |
28
|
|
|
} |
29
|
|
|
} catch (JWTException $e) { |
30
|
|
|
return response()->json([ |
31
|
|
|
'error' => 'could_not_create_token' |
32
|
|
|
], $e->getStatusCode()); |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
return response()->json(compact('token')); |
36
|
|
|
} |
37
|
|
|
|
38
|
|
|
public function register(Request $request) |
39
|
|
|
{ |
40
|
|
|
$data = $request->all(); |
41
|
|
|
|
42
|
|
|
if (!array_key_exists('password_confirmation', $request->all())) { |
43
|
|
|
$data['password_confirmation'] = $request->get('password'); |
44
|
|
|
} |
45
|
|
|
|
46
|
|
|
$validator = $this->validator($data); |
47
|
|
|
|
48
|
|
|
if ($validator->fails()) { |
49
|
|
|
return response()->json([ |
50
|
|
|
'error' => $validator->getMessageBag() |
51
|
|
|
], 400); |
52
|
|
|
} |
53
|
|
|
|
54
|
|
|
$user = User::create($data); |
55
|
|
|
$token = $this->auth->attempt($request->only('email', 'password')); |
56
|
|
|
|
57
|
|
|
return response()->json(compact('user', 'token')); |
58
|
|
|
} |
59
|
|
|
|
60
|
|
|
public function logout() |
61
|
|
|
{ |
62
|
|
|
$this->auth->invalidate($this->auth->getToken()); |
63
|
|
|
|
64
|
|
|
return response(null, 200); |
65
|
|
|
} |
66
|
|
|
|
67
|
|
|
/** |
68
|
|
|
* Get a validator for an incoming registration request. |
69
|
|
|
* |
70
|
|
|
* @param array $data |
71
|
|
|
* |
72
|
|
|
* @return \Illuminate\Contracts\Validation\Validator |
73
|
|
|
*/ |
74
|
|
|
protected function validator(array $data) |
75
|
|
|
{ |
76
|
|
|
return Validator::make($data, [ |
77
|
|
|
'username' => 'required|between:3,64|unique:users', |
78
|
|
|
'email' => 'required|between:3,64|email|unique:users', |
79
|
|
|
'password' => 'required|between:4,64|confirmed', |
80
|
|
|
]); |
81
|
|
|
} |
82
|
|
|
} |
83
|
|
|
|