1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Ntb\RestAPI; |
4
|
|
|
|
5
|
|
|
/** |
6
|
|
|
* Factory for different kind of rest authenticators. |
7
|
|
|
* @author Christian Blank <[email protected]> |
8
|
|
|
*/ |
9
|
|
|
class AuthFactory extends \Object { |
10
|
|
|
|
11
|
|
|
/** |
12
|
|
|
* Returns a new instance of an authentication mechanism depending on the configured type. |
13
|
|
|
* @return IAuth an instance of an authentication mechanism |
14
|
|
|
* @throws RestSystemException |
15
|
|
|
*/ |
16
|
|
|
public static function createAuth() { |
17
|
|
|
return \Injector::inst()->get('Authenticator'); |
18
|
|
|
} |
19
|
|
|
|
20
|
|
|
/** |
21
|
|
|
* Generates an encrypted random token. |
22
|
|
|
* @param \Member $user |
23
|
|
|
* @throws \PasswordEncryptor_NotFoundException |
24
|
|
|
* @return string |
25
|
|
|
*/ |
26
|
|
|
public static function generate_token($user) { |
27
|
|
|
$generator = new \RandomGenerator(); |
28
|
|
|
$tokenString = $generator->randomToken(); |
29
|
|
|
$e = \PasswordEncryptor::create_for_algorithm('blowfish'); |
30
|
|
|
$salt = $e->salt($tokenString); |
31
|
|
|
$token = sha1($e->encrypt($tokenString, $salt)) . substr(md5($user->Created.$user->LastEdited.$user->ID), 7); |
32
|
|
|
return $token; |
33
|
|
|
} |
34
|
|
|
|
35
|
|
|
/** |
36
|
|
|
* Returns the token from the request. |
37
|
|
|
* |
38
|
|
|
* Silverstripe doesn't include Authorization header in its requests. We should check it, because we can use the |
39
|
|
|
* mechanism in the tests. |
40
|
|
|
* @param \SS_HTTPRequest $request |
41
|
|
|
* @return String the token |
42
|
|
|
* @throws \Exception |
43
|
|
|
*/ |
44
|
|
|
public static function get_token($request) { |
45
|
|
|
// try to get the token from request object |
46
|
|
|
$tokenStrFromHeader = $request->getHeader('Authorization'); |
47
|
|
|
$tokenStrFromVar = $request->requestVar('access_token'); |
48
|
|
|
if (!empty($tokenStrFromHeader)) { |
49
|
|
|
// string must have format: type token |
50
|
|
|
return explode(' ', $tokenStrFromHeader)[1]; |
51
|
|
|
} else if(!empty($tokenStrFromVar)) { |
52
|
|
|
// try variables |
53
|
|
|
return $tokenStrFromVar; |
54
|
|
|
} else if(function_exists('getallheaders')) { |
55
|
|
|
// get all headers from apache server |
56
|
|
|
$headers = getallheaders(); |
57
|
|
|
if(isset($headers['Authorization'])) { |
58
|
|
|
return explode(' ', $headers['Authorization'])[1]; |
59
|
|
|
} |
60
|
|
|
} |
61
|
|
|
throw new \Exception("Token can't be read or was not specified"); |
62
|
|
|
} |
63
|
|
|
} |
64
|
|
|
|