1 | <?php |
||
14 | class ApiAuthService extends BaseApplicationComponent |
||
15 | { |
||
16 | /** |
||
17 | * @param string $key |
||
18 | * @return bool |
||
19 | */ |
||
20 | 3 | public function authenticateKey($key) |
|
21 | { |
||
22 | 3 | $userKeyModel = $this->getUserKeyModelByKey($key); |
|
23 | 3 | if($userKeyModel && $userKeyModel->expires > new DateTime()) { |
|
24 | 1 | return craft()->userSession->loginByUserId($userKeyModel->userId); |
|
25 | } |
||
26 | 2 | return false; |
|
27 | } |
||
28 | |||
29 | /** |
||
30 | * @return string |
||
31 | */ |
||
32 | 1 | public function generateKey() |
|
36 | |||
37 | /** |
||
38 | * @param UserModel $user |
||
39 | * @param $key |
||
40 | * @return bool |
||
41 | */ |
||
42 | 2 | public function saveKey(UserModel $user, $key) |
|
43 | { |
||
44 | 2 | $model = $this->getNewUserKeyModel(); |
|
45 | 2 | $model->userId = $user->getAttribute('id'); |
|
46 | 2 | $model->key = $key; |
|
47 | 2 | $model->expires = new DateTime('+ 1 week'); |
|
48 | 2 | return $model->save(); |
|
49 | } |
||
50 | |||
51 | /** |
||
52 | * Is it an options request? |
||
53 | * |
||
54 | * @return bool |
||
55 | */ |
||
56 | 2 | public function isOptionsRequest() |
|
|
|||
57 | { |
||
58 | 2 | return isset($_SERVER['REQUEST_METHOD']) && $_SERVER['REQUEST_METHOD'] == 'OPTIONS'; |
|
59 | } |
||
60 | |||
61 | /** |
||
62 | * Send an options response |
||
63 | */ |
||
64 | 1 | public function setCorsHeaders() |
|
65 | { |
||
66 | 1 | $this->setHeader('Access-Control-Allow-Headers', 'Authorization'); |
|
67 | 1 | $this->setHeader('Access-Control-Allow-Origin', '*'); |
|
68 | 1 | } |
|
69 | |||
70 | /** |
||
71 | * @codeCoverageIgnore |
||
72 | * |
||
73 | * @return ApiAuth_UserKeyModel |
||
74 | */ |
||
75 | protected function getNewUserKeyModel() |
||
79 | |||
80 | /** |
||
81 | * @codeCoverageIgnore |
||
82 | * |
||
83 | * @param string $key |
||
84 | * @return ApiAuth_UserKeyModel |
||
85 | */ |
||
86 | protected function getUserKeyModelByKey($key) |
||
90 | |||
91 | /** |
||
92 | * @codeCoverageIgnore |
||
93 | * |
||
94 | * @param string $key |
||
95 | * @param string $value |
||
96 | */ |
||
97 | protected function setHeader($key, $value) |
||
101 | } |
||
102 |
Instead of super-globals, we recommend to explicitly inject the dependencies of your class. This makes your code less dependent on global state and it becomes generally more testable: