|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
namespace yrc\actions; |
|
4
|
|
|
|
|
5
|
|
|
use app\forms\Login; |
|
6
|
|
|
use app\models\Token; |
|
7
|
|
|
use yrc\rest\Action as RestAction; |
|
8
|
|
|
|
|
9
|
|
|
use yii\web\UnauthorizedHttpException; |
|
10
|
|
|
use Yii; |
|
11
|
|
|
|
|
12
|
|
|
/** |
|
13
|
|
|
* @class AuthenticationAction |
|
14
|
|
|
* Handles Authentication and Deauthentication of users |
|
15
|
|
|
*/ |
|
16
|
|
|
class AuthenticationAction extends RestAction |
|
17
|
|
|
{ |
|
18
|
|
|
/** |
|
19
|
|
|
* Authenticates a user using their username and password |
|
20
|
|
|
* @return mixed |
|
21
|
|
|
*/ |
|
22
|
|
|
public function post($params) |
|
|
|
|
|
|
23
|
|
|
{ |
|
24
|
|
|
$model = new Login; |
|
25
|
|
|
|
|
26
|
|
|
if ($model->load(['Login' => Yii::$app->request->post()])) { |
|
27
|
|
|
$token = $model->authenticate(); |
|
28
|
|
|
|
|
29
|
|
|
if ($token === false) { |
|
30
|
|
|
throw new UnauthorizedHttpException('The credentials you provided are not valid', $model->exitStatus); |
|
31
|
|
|
} else { |
|
32
|
|
|
return $token->getAuthResponse(); |
|
33
|
|
|
} |
|
34
|
|
|
} |
|
35
|
|
|
|
|
36
|
|
|
return false; |
|
37
|
|
|
} |
|
38
|
|
|
|
|
39
|
|
|
/** |
|
40
|
|
|
* Deauthenticates a user |
|
41
|
|
|
* @return mixed |
|
42
|
|
|
*/ |
|
43
|
|
|
public function delete($params) |
|
|
|
|
|
|
44
|
|
|
{ |
|
45
|
|
|
$token = self::getAccessTokenFromHeader(); |
|
46
|
|
|
return (bool)$token->delete(); |
|
47
|
|
|
} |
|
48
|
|
|
|
|
49
|
|
|
/** |
|
50
|
|
|
* Helper method to grab the User Token object from the header |
|
51
|
|
|
* @return User\Token|bool |
|
52
|
|
|
*/ |
|
53
|
|
|
public static function getAccessTokenFromHeader() |
|
54
|
|
|
{ |
|
55
|
|
|
// Grab the authentication header |
|
56
|
|
|
$authHeader = Yii::$app->request->getHeaders()->get('Authorization'); |
|
57
|
|
|
|
|
58
|
|
|
// Pull the accessToken from the Authorization header string |
|
59
|
|
|
if ($authHeader !== null && preg_match('/^HMAC\s+(.*?)$/', $authHeader, $matches)) { |
|
60
|
|
|
$data = explode(',', trim($matches[1])); |
|
61
|
|
|
$accessToken = $data[0]; |
|
62
|
|
|
|
|
63
|
|
|
// Retrieve the token object |
|
64
|
|
|
$token = Token::find() |
|
65
|
|
|
->where([ |
|
66
|
|
|
'access_token' => $accessToken, |
|
67
|
|
|
'user_id' => Yii::$app->user->id |
|
68
|
|
|
]) |
|
69
|
|
|
->one(); |
|
70
|
|
|
|
|
71
|
|
|
// Malformed header |
|
72
|
|
|
if ($token === null || $token->isExpired()) { |
|
73
|
|
|
throw new UnauthorizedHttpException; |
|
74
|
|
|
} |
|
75
|
|
|
|
|
76
|
|
|
return $token; |
|
77
|
|
|
} |
|
78
|
|
|
|
|
79
|
|
|
// Header isn't present |
|
80
|
|
|
throw new UnauthorizedHttpException; |
|
81
|
|
|
} |
|
82
|
|
|
} |
This check looks from parameters that have been defined for a function or method, but which are not used in the method body.