Passed
Branch develop (d6f62e)
by Tito
06:29
created
libraries/redcore/api/oauth2/Controller/TokenControllerInterface.php 1 patch
Indentation   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -17,16 +17,16 @@
 block discarded – undo
17 17
  */
18 18
 interface TokenControllerInterface
19 19
 {
20
-    /**
21
-     * handleTokenRequest
22
-     *
23
-     * @param $request
24
-     * OAuth2\RequestInterface - The current http request
25
-     * @param $response
26
-     * OAuth2\ResponseInterface - An instance of OAuth2\ResponseInterface to contain the response data
27
-     *
28
-     */
29
-    public function handleTokenRequest(RequestInterface $request, ResponseInterface $response);
20
+	/**
21
+	 * handleTokenRequest
22
+	 *
23
+	 * @param $request
24
+	 * OAuth2\RequestInterface - The current http request
25
+	 * @param $response
26
+	 * OAuth2\ResponseInterface - An instance of OAuth2\ResponseInterface to contain the response data
27
+	 *
28
+	 */
29
+	public function handleTokenRequest(RequestInterface $request, ResponseInterface $response);
30 30
 
31
-    public function grantAccessToken(RequestInterface $request, ResponseInterface $response);
31
+	public function grantAccessToken(RequestInterface $request, ResponseInterface $response);
32 32
 }
Please login to merge, or discard this patch.
libraries/redcore/api/oauth2/Controller/ResourceControllerInterface.php 1 patch
Indentation   +2 added lines, -2 removed lines patch added patch discarded remove patch
@@ -20,7 +20,7 @@
 block discarded – undo
20 20
  */
21 21
 interface ResourceControllerInterface
22 22
 {
23
-    public function verifyResourceRequest(RequestInterface $request, ResponseInterface $response, $scope = null);
23
+	public function verifyResourceRequest(RequestInterface $request, ResponseInterface $response, $scope = null);
24 24
 
25
-    public function getAccessTokenData(RequestInterface $request, ResponseInterface $response);
25
+	public function getAccessTokenData(RequestInterface $request, ResponseInterface $response);
26 26
 }
Please login to merge, or discard this patch.
extensions/libraries/redcore/api/oauth2/Storage/ClientInterface.php 1 patch
Indentation   +51 added lines, -51 removed lines patch added patch discarded remove patch
@@ -10,57 +10,57 @@
 block discarded – undo
10 10
  */
11 11
 interface ClientInterface
12 12
 {
13
-    /**
14
-     * Get client details corresponding client_id.
15
-     *
16
-     * OAuth says we should store request URIs for each registered client.
17
-     * Implement this function to grab the stored URI for a given client id.
18
-     *
19
-     * @param $client_id
20
-     * Client identifier to be check with.
21
-     *
22
-     * @return array
23
-     *               Client details. The only mandatory key in the array is "redirect_uri".
24
-     *               This function MUST return FALSE if the given client does not exist or is
25
-     *               invalid. "redirect_uri" can be space-delimited to allow for multiple valid uris.
26
-     *               <code>
27
-     *               return array(
28
-     *               "redirect_uri" => REDIRECT_URI,      // REQUIRED redirect_uri registered for the client
29
-     *               "client_id"    => CLIENT_ID,         // OPTIONAL the client id
30
-     *               "grant_types"  => GRANT_TYPES,       // OPTIONAL an array of restricted grant types
31
-     *               "user_id"      => USER_ID,           // OPTIONAL the user identifier associated with this client
32
-     *               "scope"        => SCOPE,             // OPTIONAL the scopes allowed for this client
33
-     *               );
34
-     *               </code>
35
-     *
36
-     * @ingroup oauth2_section_4
37
-     */
38
-    public function getClientDetails($client_id);
13
+	/**
14
+	 * Get client details corresponding client_id.
15
+	 *
16
+	 * OAuth says we should store request URIs for each registered client.
17
+	 * Implement this function to grab the stored URI for a given client id.
18
+	 *
19
+	 * @param $client_id
20
+	 * Client identifier to be check with.
21
+	 *
22
+	 * @return array
23
+	 *               Client details. The only mandatory key in the array is "redirect_uri".
24
+	 *               This function MUST return FALSE if the given client does not exist or is
25
+	 *               invalid. "redirect_uri" can be space-delimited to allow for multiple valid uris.
26
+	 *               <code>
27
+	 *               return array(
28
+	 *               "redirect_uri" => REDIRECT_URI,      // REQUIRED redirect_uri registered for the client
29
+	 *               "client_id"    => CLIENT_ID,         // OPTIONAL the client id
30
+	 *               "grant_types"  => GRANT_TYPES,       // OPTIONAL an array of restricted grant types
31
+	 *               "user_id"      => USER_ID,           // OPTIONAL the user identifier associated with this client
32
+	 *               "scope"        => SCOPE,             // OPTIONAL the scopes allowed for this client
33
+	 *               );
34
+	 *               </code>
35
+	 *
36
+	 * @ingroup oauth2_section_4
37
+	 */
38
+	public function getClientDetails($client_id);
39 39
 
40
-    /**
41
-     * Get the scope associated with this client
42
-     *
43
-     * @return
44
-     * STRING the space-delineated scope list for the specified client_id
45
-     */
46
-    public function getClientScope($client_id);
40
+	/**
41
+	 * Get the scope associated with this client
42
+	 *
43
+	 * @return
44
+	 * STRING the space-delineated scope list for the specified client_id
45
+	 */
46
+	public function getClientScope($client_id);
47 47
 
48
-    /**
49
-     * Check restricted grant types of corresponding client identifier.
50
-     *
51
-     * If you want to restrict clients to certain grant types, override this
52
-     * function.
53
-     *
54
-     * @param $client_id
55
-     * Client identifier to be check with.
56
-     * @param $grant_type
57
-     * Grant type to be check with
58
-     *
59
-     * @return
60
-     * TRUE if the grant type is supported by this client identifier, and
61
-     * FALSE if it isn't.
62
-     *
63
-     * @ingroup oauth2_section_4
64
-     */
65
-    public function checkRestrictedGrantType($client_id, $grant_type);
48
+	/**
49
+	 * Check restricted grant types of corresponding client identifier.
50
+	 *
51
+	 * If you want to restrict clients to certain grant types, override this
52
+	 * function.
53
+	 *
54
+	 * @param $client_id
55
+	 * Client identifier to be check with.
56
+	 * @param $grant_type
57
+	 * Grant type to be check with
58
+	 *
59
+	 * @return
60
+	 * TRUE if the grant type is supported by this client identifier, and
61
+	 * FALSE if it isn't.
62
+	 *
63
+	 * @ingroup oauth2_section_4
64
+	 */
65
+	public function checkRestrictedGrantType($client_id, $grant_type);
66 66
 }
Please login to merge, or discard this patch.
extensions/libraries/redcore/api/oauth2/Storage/JwtBearerInterface.php 1 patch
Indentation   +55 added lines, -55 removed lines patch added patch discarded remove patch
@@ -14,61 +14,61 @@
 block discarded – undo
14 14
  */
15 15
 interface JwtBearerInterface
16 16
 {
17
-    /**
18
-     * Get the public key associated with a client_id
19
-     *
20
-     * @param $client_id
21
-     * Client identifier to be checked with.
22
-     *
23
-     * @return
24
-     * STRING Return the public key for the client_id if it exists, and MUST return FALSE if it doesn't.
25
-     */
26
-    public function getClientKey($client_id, $subject);
17
+	/**
18
+	 * Get the public key associated with a client_id
19
+	 *
20
+	 * @param $client_id
21
+	 * Client identifier to be checked with.
22
+	 *
23
+	 * @return
24
+	 * STRING Return the public key for the client_id if it exists, and MUST return FALSE if it doesn't.
25
+	 */
26
+	public function getClientKey($client_id, $subject);
27 27
 
28
-    /**
29
-     * Get a jti (JSON token identifier) by matching against the client_id, subject, audience and expiration.
30
-     *
31
-     * @param $client_id
32
-     * Client identifier to match.
33
-     *
34
-     * @param $subject
35
-     * The subject to match.
36
-     *
37
-     * @param $audience
38
-     * The audience to match.
39
-     *
40
-     * @param $expiration
41
-     * The expiration of the jti.
42
-     *
43
-     * @param $jti
44
-     * The jti to match.
45
-     *
46
-     * @return
47
-     * An associative array as below, and return NULL if the jti does not exist.
48
-     * - issuer: Stored client identifier.
49
-     * - subject: Stored subject.
50
-     * - audience: Stored audience.
51
-     * - expires: Stored expiration in unix timestamp.
52
-     * - jti: The stored jti.
53
-     */
54
-    public function getJti($client_id, $subject, $audience, $expiration, $jti);
28
+	/**
29
+	 * Get a jti (JSON token identifier) by matching against the client_id, subject, audience and expiration.
30
+	 *
31
+	 * @param $client_id
32
+	 * Client identifier to match.
33
+	 *
34
+	 * @param $subject
35
+	 * The subject to match.
36
+	 *
37
+	 * @param $audience
38
+	 * The audience to match.
39
+	 *
40
+	 * @param $expiration
41
+	 * The expiration of the jti.
42
+	 *
43
+	 * @param $jti
44
+	 * The jti to match.
45
+	 *
46
+	 * @return
47
+	 * An associative array as below, and return NULL if the jti does not exist.
48
+	 * - issuer: Stored client identifier.
49
+	 * - subject: Stored subject.
50
+	 * - audience: Stored audience.
51
+	 * - expires: Stored expiration in unix timestamp.
52
+	 * - jti: The stored jti.
53
+	 */
54
+	public function getJti($client_id, $subject, $audience, $expiration, $jti);
55 55
 
56
-    /**
57
-     * Store a used jti so that we can check against it to prevent replay attacks.
58
-     * @param $client_id
59
-     * Client identifier to insert.
60
-     *
61
-     * @param $subject
62
-     * The subject to insert.
63
-     *
64
-     * @param $audience
65
-     * The audience to insert.
66
-     *
67
-     * @param $expiration
68
-     * The expiration of the jti.
69
-     *
70
-     * @param $jti
71
-     * The jti to insert.
72
-     */
73
-    public function setJti($client_id, $subject, $audience, $expiration, $jti);
56
+	/**
57
+	 * Store a used jti so that we can check against it to prevent replay attacks.
58
+	 * @param $client_id
59
+	 * Client identifier to insert.
60
+	 *
61
+	 * @param $subject
62
+	 * The subject to insert.
63
+	 *
64
+	 * @param $audience
65
+	 * The audience to insert.
66
+	 *
67
+	 * @param $expiration
68
+	 * The expiration of the jti.
69
+	 *
70
+	 * @param $jti
71
+	 * The jti to insert.
72
+	 */
73
+	public function setJti($client_id, $subject, $audience, $expiration, $jti);
74 74
 }
Please login to merge, or discard this patch.
extensions/libraries/redcore/api/oauth2/Storage/RefreshTokenInterface.php 1 patch
Indentation   +66 added lines, -66 removed lines patch added patch discarded remove patch
@@ -11,72 +11,72 @@
 block discarded – undo
11 11
  */
12 12
 interface RefreshTokenInterface
13 13
 {
14
-    /**
15
-     * Grant refresh access tokens.
16
-     *
17
-     * Retrieve the stored data for the given refresh token.
18
-     *
19
-     * Required for OAuth2::GRANT_TYPE_REFRESH_TOKEN.
20
-     *
21
-     * @param $refresh_token
22
-     * Refresh token to be check with.
23
-     *
24
-     * @return
25
-     * An associative array as below, and NULL if the refresh_token is
26
-     * invalid:
27
-     * - refresh_token: Refresh token identifier.
28
-     * - client_id: Client identifier.
29
-     * - user_id: User identifier.
30
-     * - expires: Expiration unix timestamp, or 0 if the token doesn't expire.
31
-     * - scope: (optional) Scope values in space-separated string.
32
-     *
33
-     * @see http://tools.ietf.org/html/rfc6749#section-6
34
-     *
35
-     * @ingroup oauth2_section_6
36
-     */
37
-    public function getRefreshToken($refresh_token);
14
+	/**
15
+	 * Grant refresh access tokens.
16
+	 *
17
+	 * Retrieve the stored data for the given refresh token.
18
+	 *
19
+	 * Required for OAuth2::GRANT_TYPE_REFRESH_TOKEN.
20
+	 *
21
+	 * @param $refresh_token
22
+	 * Refresh token to be check with.
23
+	 *
24
+	 * @return
25
+	 * An associative array as below, and NULL if the refresh_token is
26
+	 * invalid:
27
+	 * - refresh_token: Refresh token identifier.
28
+	 * - client_id: Client identifier.
29
+	 * - user_id: User identifier.
30
+	 * - expires: Expiration unix timestamp, or 0 if the token doesn't expire.
31
+	 * - scope: (optional) Scope values in space-separated string.
32
+	 *
33
+	 * @see http://tools.ietf.org/html/rfc6749#section-6
34
+	 *
35
+	 * @ingroup oauth2_section_6
36
+	 */
37
+	public function getRefreshToken($refresh_token);
38 38
 
39
-    /**
40
-     * Take the provided refresh token values and store them somewhere.
41
-     *
42
-     * This function should be the storage counterpart to getRefreshToken().
43
-     *
44
-     * If storage fails for some reason, we're not currently checking for
45
-     * any sort of success/failure, so you should bail out of the script
46
-     * and provide a descriptive fail message.
47
-     *
48
-     * Required for OAuth2::GRANT_TYPE_REFRESH_TOKEN.
49
-     *
50
-     * @param $refresh_token
51
-     * Refresh token to be stored.
52
-     * @param $client_id
53
-     * Client identifier to be stored.
54
-     * @param $user_id
55
-     * User identifier to be stored.
56
-     * @param $expires
57
-     * Expiration timestamp to be stored. 0 if the token doesn't expire.
58
-     * @param $scope
59
-     * (optional) Scopes to be stored in space-separated string.
60
-     *
61
-     * @ingroup oauth2_section_6
62
-     */
63
-    public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null);
39
+	/**
40
+	 * Take the provided refresh token values and store them somewhere.
41
+	 *
42
+	 * This function should be the storage counterpart to getRefreshToken().
43
+	 *
44
+	 * If storage fails for some reason, we're not currently checking for
45
+	 * any sort of success/failure, so you should bail out of the script
46
+	 * and provide a descriptive fail message.
47
+	 *
48
+	 * Required for OAuth2::GRANT_TYPE_REFRESH_TOKEN.
49
+	 *
50
+	 * @param $refresh_token
51
+	 * Refresh token to be stored.
52
+	 * @param $client_id
53
+	 * Client identifier to be stored.
54
+	 * @param $user_id
55
+	 * User identifier to be stored.
56
+	 * @param $expires
57
+	 * Expiration timestamp to be stored. 0 if the token doesn't expire.
58
+	 * @param $scope
59
+	 * (optional) Scopes to be stored in space-separated string.
60
+	 *
61
+	 * @ingroup oauth2_section_6
62
+	 */
63
+	public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null);
64 64
 
65
-    /**
66
-     * Expire a used refresh token.
67
-     *
68
-     * This is not explicitly required in the spec, but is almost implied.
69
-     * After granting a new refresh token, the old one is no longer useful and
70
-     * so should be forcibly expired in the data store so it can't be used again.
71
-     *
72
-     * If storage fails for some reason, we're not currently checking for
73
-     * any sort of success/failure, so you should bail out of the script
74
-     * and provide a descriptive fail message.
75
-     *
76
-     * @param $refresh_token
77
-     * Refresh token to be expirse.
78
-     *
79
-     * @ingroup oauth2_section_6
80
-     */
81
-    public function unsetRefreshToken($refresh_token);
65
+	/**
66
+	 * Expire a used refresh token.
67
+	 *
68
+	 * This is not explicitly required in the spec, but is almost implied.
69
+	 * After granting a new refresh token, the old one is no longer useful and
70
+	 * so should be forcibly expired in the data store so it can't be used again.
71
+	 *
72
+	 * If storage fails for some reason, we're not currently checking for
73
+	 * any sort of success/failure, so you should bail out of the script
74
+	 * and provide a descriptive fail message.
75
+	 *
76
+	 * @param $refresh_token
77
+	 * Refresh token to be expirse.
78
+	 *
79
+	 * @ingroup oauth2_section_6
80
+	 */
81
+	public function unsetRefreshToken($refresh_token);
82 82
 }
Please login to merge, or discard this patch.
extensions/libraries/redcore/api/oauth2/Storage/Redis.php 2 patches
Indentation   +296 added lines, -296 removed lines patch added patch discarded remove patch
@@ -16,302 +16,302 @@
 block discarded – undo
16 16
  * </code>
17 17
  */
18 18
 class Redis implements AuthorizationCodeInterface,
19
-    AccessTokenInterface,
20
-    ClientCredentialsInterface,
21
-    UserCredentialsInterface,
22
-    RefreshTokenInterface,
23
-    JwtBearerInterface,
24
-    ScopeInterface,
25
-    OpenIDAuthorizationCodeInterface
19
+	AccessTokenInterface,
20
+	ClientCredentialsInterface,
21
+	UserCredentialsInterface,
22
+	RefreshTokenInterface,
23
+	JwtBearerInterface,
24
+	ScopeInterface,
25
+	OpenIDAuthorizationCodeInterface
26 26
 {
27 27
 
28
-    private $cache;
29
-
30
-    /* The redis client */
31
-    protected $redis;
32
-
33
-    /* Configuration array */
34
-    protected $config;
35
-
36
-    /**
37
-     * Redis Storage!
38
-     *
39
-     * @param \Predis\Client $redis
40
-     * @param array          $config
41
-     */
42
-    public function __construct($redis, $config=array())
43
-    {
44
-        $this->redis = $redis;
45
-        $this->config = array_merge(array(
46
-            'client_key' => 'oauth_clients:',
47
-            'access_token_key' => 'oauth_access_tokens:',
48
-            'refresh_token_key' => 'oauth_refresh_tokens:',
49
-            'code_key' => 'oauth_authorization_codes:',
50
-            'user_key' => 'oauth_users:',
51
-            'jwt_key' => 'oauth_jwt:',
52
-            'scope_key' => 'oauth_scopes:',
53
-        ), $config);
54
-    }
55
-
56
-    protected function getValue($key)
57
-    {
58
-        if ( isset($this->cache[$key]) ) {
59
-            return $this->cache[$key];
60
-        }
61
-        $value = $this->redis->get($key);
62
-        if ( isset($value) ) {
63
-            return json_decode($value, true);
64
-        } else {
65
-            return false;
66
-        }
67
-    }
68
-
69
-    protected function setValue($key, $value, $expire=0)
70
-    {
71
-        $this->cache[$key] = $value;
72
-        $str = json_encode($value);
73
-        if ($expire > 0) {
74
-            $seconds = $expire - time();
75
-            $ret = $this->redis->setex($key, $seconds, $str);
76
-        } else {
77
-            $ret = $this->redis->set($key, $str);
78
-        }
79
-
80
-        // check that the key was set properly
81
-        // if this fails, an exception will usually thrown, so this step isn't strictly necessary
82
-        return is_bool($ret) ? $ret : $ret->getPayload() == 'OK';
83
-    }
84
-
85
-    protected function expireValue($key)
86
-    {
87
-        unset($this->cache[$key]);
88
-
89
-        return $this->redis->del($key);
90
-    }
91
-
92
-    /* AuthorizationCodeInterface */
93
-    public function getAuthorizationCode($code)
94
-    {
95
-        return $this->getValue($this->config['code_key'] . $code);
96
-    }
97
-
98
-    public function setAuthorizationCode($authorization_code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null)
99
-    {
100
-        return $this->setValue(
101
-            $this->config['code_key'] . $authorization_code,
102
-            compact('authorization_code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope', 'id_token'),
103
-            $expires
104
-        );
105
-    }
106
-
107
-    public function expireAuthorizationCode($code)
108
-    {
109
-        $key = $this->config['code_key'] . $code;
110
-        unset($this->cache[$key]);
111
-
112
-        return $this->expireValue($key);
113
-    }
114
-
115
-    /* UserCredentialsInterface */
116
-    public function checkUserCredentials($username, $password)
117
-    {
118
-        $user = $this->getUserDetails($username);
119
-
120
-        return $user && $user['password'] === $password;
121
-    }
122
-
123
-    public function getUserDetails($username)
124
-    {
125
-        return $this->getUser($username);
126
-    }
127
-
128
-    public function getUser($username)
129
-    {
130
-        if (!$userInfo = $this->getValue($this->config['user_key'] . $username)) {
131
-            return false;
132
-        }
133
-
134
-        // the default behavior is to use "username" as the user_id
135
-        return array_merge(array(
136
-            'user_id' => $username,
137
-        ), $userInfo);
138
-    }
139
-
140
-    public function setUser($username, $password, $first_name = null, $last_name = null)
141
-    {
142
-        return $this->setValue(
143
-            $this->config['user_key'] . $username,
144
-            compact('username', 'password', 'first_name', 'last_name')
145
-        );
146
-    }
147
-
148
-    /* ClientCredentialsInterface */
149
-    public function checkClientCredentials($client_id, $client_secret = null)
150
-    {
151
-        if (!$client = $this->getClientDetails($client_id)) {
152
-            return false;
153
-        }
154
-
155
-        return isset($client['client_secret'])
156
-            && $client['client_secret'] == $client_secret;
157
-    }
158
-
159
-    public function isPublicClient($client_id)
160
-    {
161
-        if (!$client = $this->getClientDetails($client_id)) {
162
-            return false;
163
-        }
164
-
165
-        return empty($result['client_secret']);
166
-    }
167
-
168
-    /* ClientInterface */
169
-    public function getClientDetails($client_id)
170
-    {
171
-        return $this->getValue($this->config['client_key'] . $client_id);
172
-    }
173
-
174
-    public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null)
175
-    {
176
-        return $this->setValue(
177
-            $this->config['client_key'] . $client_id,
178
-            compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id')
179
-        );
180
-    }
181
-
182
-    public function checkRestrictedGrantType($client_id, $grant_type)
183
-    {
184
-        $details = $this->getClientDetails($client_id);
185
-        if (isset($details['grant_types'])) {
186
-            $grant_types = explode(' ', $details['grant_types']);
187
-
188
-            return in_array($grant_type, (array) $grant_types);
189
-        }
190
-
191
-        // if grant_types are not defined, then none are restricted
192
-        return true;
193
-    }
194
-
195
-    /* RefreshTokenInterface */
196
-    public function getRefreshToken($refresh_token)
197
-    {
198
-        return $this->getValue($this->config['refresh_token_key'] . $refresh_token);
199
-    }
200
-
201
-    public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null)
202
-    {
203
-        return $this->setValue(
204
-            $this->config['refresh_token_key'] . $refresh_token,
205
-            compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope'),
206
-            $expires
207
-        );
208
-    }
209
-
210
-    public function unsetRefreshToken($refresh_token)
211
-    {
212
-        return $this->expireValue($this->config['refresh_token_key'] . $refresh_token);
213
-    }
214
-
215
-    /* AccessTokenInterface */
216
-    public function getAccessToken($access_token)
217
-    {
218
-        return $this->getValue($this->config['access_token_key'].$access_token);
219
-    }
220
-
221
-    public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null)
222
-    {
223
-        return $this->setValue(
224
-            $this->config['access_token_key'].$access_token,
225
-            compact('access_token', 'client_id', 'user_id', 'expires', 'scope'),
226
-            $expires
227
-        );
228
-    }
229
-
230
-    public function unsetAccessToken($access_token)
231
-    {
232
-        return $this->expireValue($this->config['access_token_key'] . $access_token);
233
-    }
234
-
235
-    /* ScopeInterface */
236
-    public function scopeExists($scope)
237
-    {
238
-        $scope = explode(' ', $scope);
239
-
240
-        $result = $this->getValue($this->config['scope_key'].'supported:global');
241
-
242
-        $supportedScope = explode(' ', (string) $result);
243
-
244
-        return (count(array_diff($scope, $supportedScope)) == 0);
245
-    }
246
-
247
-    public function getDefaultScope($client_id = null)
248
-    {
249
-        if (is_null($client_id) || !$result = $this->getValue($this->config['scope_key'].'default:'.$client_id)) {
250
-            $result = $this->getValue($this->config['scope_key'].'default:global');
251
-        }
252
-
253
-        return $result;
254
-    }
255
-
256
-    public function setScope($scope, $client_id = null, $type = 'supported')
257
-    {
258
-        if (!in_array($type, array('default', 'supported'))) {
259
-            throw new \InvalidArgumentException('"$type" must be one of "default", "supported"');
260
-        }
261
-
262
-        if (is_null($client_id)) {
263
-            $key = $this->config['scope_key'].$type.':global';
264
-        } else {
265
-            $key = $this->config['scope_key'].$type.':'.$client_id;
266
-        }
267
-
268
-        return $this->setValue($key, $scope);
269
-    }
270
-
271
-    /*JWTBearerInterface */
272
-    public function getClientKey($client_id, $subject)
273
-    {
274
-        if (!$jwt = $this->getValue($this->config['jwt_key'] . $client_id)) {
275
-            return false;
276
-        }
277
-
278
-        if (isset($jwt['subject']) && $jwt['subject'] == $subject) {
279
-            return $jwt['key'];
280
-        }
281
-
282
-        return null;
283
-    }
284
-
285
-    public function setClientKey($client_id, $key, $subject = null)
286
-    {
287
-        return $this->setValue($this->config['jwt_key'] . $client_id, array(
288
-            'key' => $key,
289
-            'subject' => $subject
290
-        ));
291
-    }
292
-
293
-    public function getClientScope($client_id)
294
-    {
295
-        if (!$clientDetails = $this->getClientDetails($client_id)) {
296
-            return false;
297
-        }
298
-
299
-        if (isset($clientDetails['scope'])) {
300
-            return $clientDetails['scope'];
301
-        }
302
-
303
-        return null;
304
-    }
305
-
306
-    public function getJti($client_id, $subject, $audience, $expiration, $jti)
307
-    {
308
-        //TODO: Needs redis implementation.
309
-        throw new \Exception('getJti() for the Redis driver is currently unimplemented.');
310
-    }
311
-
312
-    public function setJti($client_id, $subject, $audience, $expiration, $jti)
313
-    {
314
-        //TODO: Needs redis implementation.
315
-        throw new \Exception('setJti() for the Redis driver is currently unimplemented.');
316
-    }
28
+	private $cache;
29
+
30
+	/* The redis client */
31
+	protected $redis;
32
+
33
+	/* Configuration array */
34
+	protected $config;
35
+
36
+	/**
37
+	 * Redis Storage!
38
+	 *
39
+	 * @param \Predis\Client $redis
40
+	 * @param array          $config
41
+	 */
42
+	public function __construct($redis, $config=array())
43
+	{
44
+		$this->redis = $redis;
45
+		$this->config = array_merge(array(
46
+			'client_key' => 'oauth_clients:',
47
+			'access_token_key' => 'oauth_access_tokens:',
48
+			'refresh_token_key' => 'oauth_refresh_tokens:',
49
+			'code_key' => 'oauth_authorization_codes:',
50
+			'user_key' => 'oauth_users:',
51
+			'jwt_key' => 'oauth_jwt:',
52
+			'scope_key' => 'oauth_scopes:',
53
+		), $config);
54
+	}
55
+
56
+	protected function getValue($key)
57
+	{
58
+		if ( isset($this->cache[$key]) ) {
59
+			return $this->cache[$key];
60
+		}
61
+		$value = $this->redis->get($key);
62
+		if ( isset($value) ) {
63
+			return json_decode($value, true);
64
+		} else {
65
+			return false;
66
+		}
67
+	}
68
+
69
+	protected function setValue($key, $value, $expire=0)
70
+	{
71
+		$this->cache[$key] = $value;
72
+		$str = json_encode($value);
73
+		if ($expire > 0) {
74
+			$seconds = $expire - time();
75
+			$ret = $this->redis->setex($key, $seconds, $str);
76
+		} else {
77
+			$ret = $this->redis->set($key, $str);
78
+		}
79
+
80
+		// check that the key was set properly
81
+		// if this fails, an exception will usually thrown, so this step isn't strictly necessary
82
+		return is_bool($ret) ? $ret : $ret->getPayload() == 'OK';
83
+	}
84
+
85
+	protected function expireValue($key)
86
+	{
87
+		unset($this->cache[$key]);
88
+
89
+		return $this->redis->del($key);
90
+	}
91
+
92
+	/* AuthorizationCodeInterface */
93
+	public function getAuthorizationCode($code)
94
+	{
95
+		return $this->getValue($this->config['code_key'] . $code);
96
+	}
97
+
98
+	public function setAuthorizationCode($authorization_code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null)
99
+	{
100
+		return $this->setValue(
101
+			$this->config['code_key'] . $authorization_code,
102
+			compact('authorization_code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'scope', 'id_token'),
103
+			$expires
104
+		);
105
+	}
106
+
107
+	public function expireAuthorizationCode($code)
108
+	{
109
+		$key = $this->config['code_key'] . $code;
110
+		unset($this->cache[$key]);
111
+
112
+		return $this->expireValue($key);
113
+	}
114
+
115
+	/* UserCredentialsInterface */
116
+	public function checkUserCredentials($username, $password)
117
+	{
118
+		$user = $this->getUserDetails($username);
119
+
120
+		return $user && $user['password'] === $password;
121
+	}
122
+
123
+	public function getUserDetails($username)
124
+	{
125
+		return $this->getUser($username);
126
+	}
127
+
128
+	public function getUser($username)
129
+	{
130
+		if (!$userInfo = $this->getValue($this->config['user_key'] . $username)) {
131
+			return false;
132
+		}
133
+
134
+		// the default behavior is to use "username" as the user_id
135
+		return array_merge(array(
136
+			'user_id' => $username,
137
+		), $userInfo);
138
+	}
139
+
140
+	public function setUser($username, $password, $first_name = null, $last_name = null)
141
+	{
142
+		return $this->setValue(
143
+			$this->config['user_key'] . $username,
144
+			compact('username', 'password', 'first_name', 'last_name')
145
+		);
146
+	}
147
+
148
+	/* ClientCredentialsInterface */
149
+	public function checkClientCredentials($client_id, $client_secret = null)
150
+	{
151
+		if (!$client = $this->getClientDetails($client_id)) {
152
+			return false;
153
+		}
154
+
155
+		return isset($client['client_secret'])
156
+			&& $client['client_secret'] == $client_secret;
157
+	}
158
+
159
+	public function isPublicClient($client_id)
160
+	{
161
+		if (!$client = $this->getClientDetails($client_id)) {
162
+			return false;
163
+		}
164
+
165
+		return empty($result['client_secret']);
166
+	}
167
+
168
+	/* ClientInterface */
169
+	public function getClientDetails($client_id)
170
+	{
171
+		return $this->getValue($this->config['client_key'] . $client_id);
172
+	}
173
+
174
+	public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null)
175
+	{
176
+		return $this->setValue(
177
+			$this->config['client_key'] . $client_id,
178
+			compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id')
179
+		);
180
+	}
181
+
182
+	public function checkRestrictedGrantType($client_id, $grant_type)
183
+	{
184
+		$details = $this->getClientDetails($client_id);
185
+		if (isset($details['grant_types'])) {
186
+			$grant_types = explode(' ', $details['grant_types']);
187
+
188
+			return in_array($grant_type, (array) $grant_types);
189
+		}
190
+
191
+		// if grant_types are not defined, then none are restricted
192
+		return true;
193
+	}
194
+
195
+	/* RefreshTokenInterface */
196
+	public function getRefreshToken($refresh_token)
197
+	{
198
+		return $this->getValue($this->config['refresh_token_key'] . $refresh_token);
199
+	}
200
+
201
+	public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null)
202
+	{
203
+		return $this->setValue(
204
+			$this->config['refresh_token_key'] . $refresh_token,
205
+			compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope'),
206
+			$expires
207
+		);
208
+	}
209
+
210
+	public function unsetRefreshToken($refresh_token)
211
+	{
212
+		return $this->expireValue($this->config['refresh_token_key'] . $refresh_token);
213
+	}
214
+
215
+	/* AccessTokenInterface */
216
+	public function getAccessToken($access_token)
217
+	{
218
+		return $this->getValue($this->config['access_token_key'].$access_token);
219
+	}
220
+
221
+	public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null)
222
+	{
223
+		return $this->setValue(
224
+			$this->config['access_token_key'].$access_token,
225
+			compact('access_token', 'client_id', 'user_id', 'expires', 'scope'),
226
+			$expires
227
+		);
228
+	}
229
+
230
+	public function unsetAccessToken($access_token)
231
+	{
232
+		return $this->expireValue($this->config['access_token_key'] . $access_token);
233
+	}
234
+
235
+	/* ScopeInterface */
236
+	public function scopeExists($scope)
237
+	{
238
+		$scope = explode(' ', $scope);
239
+
240
+		$result = $this->getValue($this->config['scope_key'].'supported:global');
241
+
242
+		$supportedScope = explode(' ', (string) $result);
243
+
244
+		return (count(array_diff($scope, $supportedScope)) == 0);
245
+	}
246
+
247
+	public function getDefaultScope($client_id = null)
248
+	{
249
+		if (is_null($client_id) || !$result = $this->getValue($this->config['scope_key'].'default:'.$client_id)) {
250
+			$result = $this->getValue($this->config['scope_key'].'default:global');
251
+		}
252
+
253
+		return $result;
254
+	}
255
+
256
+	public function setScope($scope, $client_id = null, $type = 'supported')
257
+	{
258
+		if (!in_array($type, array('default', 'supported'))) {
259
+			throw new \InvalidArgumentException('"$type" must be one of "default", "supported"');
260
+		}
261
+
262
+		if (is_null($client_id)) {
263
+			$key = $this->config['scope_key'].$type.':global';
264
+		} else {
265
+			$key = $this->config['scope_key'].$type.':'.$client_id;
266
+		}
267
+
268
+		return $this->setValue($key, $scope);
269
+	}
270
+
271
+	/*JWTBearerInterface */
272
+	public function getClientKey($client_id, $subject)
273
+	{
274
+		if (!$jwt = $this->getValue($this->config['jwt_key'] . $client_id)) {
275
+			return false;
276
+		}
277
+
278
+		if (isset($jwt['subject']) && $jwt['subject'] == $subject) {
279
+			return $jwt['key'];
280
+		}
281
+
282
+		return null;
283
+	}
284
+
285
+	public function setClientKey($client_id, $key, $subject = null)
286
+	{
287
+		return $this->setValue($this->config['jwt_key'] . $client_id, array(
288
+			'key' => $key,
289
+			'subject' => $subject
290
+		));
291
+	}
292
+
293
+	public function getClientScope($client_id)
294
+	{
295
+		if (!$clientDetails = $this->getClientDetails($client_id)) {
296
+			return false;
297
+		}
298
+
299
+		if (isset($clientDetails['scope'])) {
300
+			return $clientDetails['scope'];
301
+		}
302
+
303
+		return null;
304
+	}
305
+
306
+	public function getJti($client_id, $subject, $audience, $expiration, $jti)
307
+	{
308
+		//TODO: Needs redis implementation.
309
+		throw new \Exception('getJti() for the Redis driver is currently unimplemented.');
310
+	}
311
+
312
+	public function setJti($client_id, $subject, $audience, $expiration, $jti)
313
+	{
314
+		//TODO: Needs redis implementation.
315
+		throw new \Exception('setJti() for the Redis driver is currently unimplemented.');
316
+	}
317 317
 }
Please login to merge, or discard this patch.
Spacing   +11 added lines, -11 removed lines patch added patch discarded remove patch
@@ -39,7 +39,7 @@  discard block
 block discarded – undo
39 39
      * @param \Predis\Client $redis
40 40
      * @param array          $config
41 41
      */
42
-    public function __construct($redis, $config=array())
42
+    public function __construct($redis, $config = array())
43 43
     {
44 44
         $this->redis = $redis;
45 45
         $this->config = array_merge(array(
@@ -55,18 +55,18 @@  discard block
 block discarded – undo
55 55
 
56 56
     protected function getValue($key)
57 57
     {
58
-        if ( isset($this->cache[$key]) ) {
58
+        if (isset($this->cache[$key])) {
59 59
             return $this->cache[$key];
60 60
         }
61 61
         $value = $this->redis->get($key);
62
-        if ( isset($value) ) {
62
+        if (isset($value)) {
63 63
             return json_decode($value, true);
64 64
         } else {
65 65
             return false;
66 66
         }
67 67
     }
68 68
 
69
-    protected function setValue($key, $value, $expire=0)
69
+    protected function setValue($key, $value, $expire = 0)
70 70
     {
71 71
         $this->cache[$key] = $value;
72 72
         $str = json_encode($value);
@@ -215,13 +215,13 @@  discard block
 block discarded – undo
215 215
     /* AccessTokenInterface */
216 216
     public function getAccessToken($access_token)
217 217
     {
218
-        return $this->getValue($this->config['access_token_key'].$access_token);
218
+        return $this->getValue($this->config['access_token_key'] . $access_token);
219 219
     }
220 220
 
221 221
     public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null)
222 222
     {
223 223
         return $this->setValue(
224
-            $this->config['access_token_key'].$access_token,
224
+            $this->config['access_token_key'] . $access_token,
225 225
             compact('access_token', 'client_id', 'user_id', 'expires', 'scope'),
226 226
             $expires
227 227
         );
@@ -237,7 +237,7 @@  discard block
 block discarded – undo
237 237
     {
238 238
         $scope = explode(' ', $scope);
239 239
 
240
-        $result = $this->getValue($this->config['scope_key'].'supported:global');
240
+        $result = $this->getValue($this->config['scope_key'] . 'supported:global');
241 241
 
242 242
         $supportedScope = explode(' ', (string) $result);
243 243
 
@@ -246,8 +246,8 @@  discard block
 block discarded – undo
246 246
 
247 247
     public function getDefaultScope($client_id = null)
248 248
     {
249
-        if (is_null($client_id) || !$result = $this->getValue($this->config['scope_key'].'default:'.$client_id)) {
250
-            $result = $this->getValue($this->config['scope_key'].'default:global');
249
+        if (is_null($client_id) || !$result = $this->getValue($this->config['scope_key'] . 'default:' . $client_id)) {
250
+            $result = $this->getValue($this->config['scope_key'] . 'default:global');
251 251
         }
252 252
 
253 253
         return $result;
@@ -260,9 +260,9 @@  discard block
 block discarded – undo
260 260
         }
261 261
 
262 262
         if (is_null($client_id)) {
263
-            $key = $this->config['scope_key'].$type.':global';
263
+            $key = $this->config['scope_key'] . $type . ':global';
264 264
         } else {
265
-            $key = $this->config['scope_key'].$type.':'.$client_id;
265
+            $key = $this->config['scope_key'] . $type . ':' . $client_id;
266 266
         }
267 267
 
268 268
         return $this->setValue($key, $scope);
Please login to merge, or discard this patch.
extensions/libraries/redcore/api/oauth2/Storage/Pdoredcore.php 1 patch
Spacing   +1 added lines, -1 removed lines patch added patch discarded remove patch
@@ -68,7 +68,7 @@
 block discarded – undo
68 68
 		$clientId = $request->request('client_id');
69 69
 		$scopes = $this->getClientScope($clientId);
70 70
 
71
-		return array (
71
+		return array(
72 72
 			"user_id"   => $user->get('id'),
73 73
 			"username"  => $user->get('username'),
74 74
 			"name"      => $user->get('name'),
Please login to merge, or discard this patch.
extensions/libraries/redcore/api/oauth2/Storage/DynamoDB.php 2 patches
Indentation   +491 added lines, -491 removed lines patch added patch discarded remove patch
@@ -32,496 +32,496 @@
 block discarded – undo
32 32
  * @author Frederic AUGUSTE <frederic.auguste at gmail dot com>
33 33
  */
34 34
 class DynamoDB implements
35
-    AuthorizationCodeInterface,
36
-    AccessTokenInterface,
37
-    ClientCredentialsInterface,
38
-    UserCredentialsInterface,
39
-    RefreshTokenInterface,
40
-    JwtBearerInterface,
41
-    ScopeInterface,
42
-    PublicKeyInterface,
43
-    UserClaimsInterface,
44
-    OpenIDAuthorizationCodeInterface
35
+	AuthorizationCodeInterface,
36
+	AccessTokenInterface,
37
+	ClientCredentialsInterface,
38
+	UserCredentialsInterface,
39
+	RefreshTokenInterface,
40
+	JwtBearerInterface,
41
+	ScopeInterface,
42
+	PublicKeyInterface,
43
+	UserClaimsInterface,
44
+	OpenIDAuthorizationCodeInterface
45 45
 {
46
-    protected $client;
47
-    protected $config;
48
-
49
-    public function __construct($connection, $config = array())
50
-    {
51
-        if (!($connection instanceof DynamoDbClient)) {
52
-            if (!is_array($connection)) {
53
-                throw new \InvalidArgumentException('First argument to OAuth2\Storage\Dynamodb must be an instance a configuration array containt key, secret, region');
54
-            }
55
-            if (!array_key_exists("key",$connection) || !array_key_exists("secret",$connection) || !array_key_exists("region",$connection) ) {
56
-                throw new \InvalidArgumentException('First argument to OAuth2\Storage\Dynamodb must be an instance a configuration array containt key, secret, region');
57
-            }
58
-            $this->client = DynamoDbClient::factory(array(
59
-                'key' => $connection["key"],
60
-                'secret' => $connection["secret"],
61
-                'region' =>$connection["region"]
62
-            ));
63
-        } else {
64
-            $this->client = $connection;
65
-        }
66
-
67
-        $this->config = array_merge(array(
68
-            'client_table' => 'oauth_clients',
69
-            'access_token_table' => 'oauth_access_tokens',
70
-            'refresh_token_table' => 'oauth_refresh_tokens',
71
-            'code_table' => 'oauth_authorization_codes',
72
-            'user_table' => 'oauth_users',
73
-            'jwt_table'  => 'oauth_jwt',
74
-            'scope_table'  => 'oauth_scopes',
75
-            'public_key_table'  => 'oauth_public_keys',
76
-        ), $config);
77
-    }
78
-
79
-    /* OAuth2\Storage\ClientCredentialsInterface */
80
-    public function checkClientCredentials($client_id, $client_secret = null)
81
-    {
82
-        $result = $this->client->getItem(array(
83
-            "TableName"=> $this->config['client_table'],
84
-            "Key" => array('client_id'   => array('S' => $client_id))
85
-        ));
86
-
87
-        return  $result->count()==1 && $result["Item"]["client_secret"]["S"] == $client_secret;
88
-    }
89
-
90
-    public function isPublicClient($client_id)
91
-    {
92
-        $result = $this->client->getItem(array(
93
-            "TableName"=> $this->config['client_table'],
94
-            "Key" => array('client_id'   => array('S' => $client_id))
95
-        ));
96
-
97
-        if ($result->count()==0) {
98
-            return false ;
99
-        }
100
-
101
-        return empty($result["Item"]["client_secret"]);
102
-    }
103
-
104
-    /* OAuth2\Storage\ClientInterface */
105
-    public function getClientDetails($client_id)
106
-    {
107
-        $result = $this->client->getItem(array(
108
-            "TableName"=> $this->config['client_table'],
109
-            "Key" => array('client_id'   => array('S' => $client_id))
110
-        ));
111
-        if ($result->count()==0) {
112
-            return false ;
113
-        }
114
-        $result = $this->dynamo2array($result);
115
-        foreach (array('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id') as $key => $val) {
116
-            if (!array_key_exists ($val, $result)) {
117
-                $result[$val] = null;
118
-            }
119
-        }
120
-
121
-        return $result;
122
-    }
123
-
124
-    public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null)
125
-    {
126
-        $clientData = compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id');
127
-        $clientData = array_filter($clientData, function ($value) { return !is_null($value); });
128
-
129
-        $this->client->putItem(array(
130
-            'TableName' =>  $this->config['client_table'],
131
-            'Item' => $this->client->formatAttributes($clientData)
132
-        ));
133
-
134
-        return true;
135
-    }
136
-
137
-    public function checkRestrictedGrantType($client_id, $grant_type)
138
-    {
139
-        $details = $this->getClientDetails($client_id);
140
-        if (isset($details['grant_types'])) {
141
-            $grant_types = explode(' ', $details['grant_types']);
142
-
143
-            return in_array($grant_type, (array) $grant_types);
144
-        }
145
-
146
-        // if grant_types are not defined, then none are restricted
147
-        return true;
148
-    }
149
-
150
-    /* OAuth2\Storage\AccessTokenInterface */
151
-    public function getAccessToken($access_token)
152
-    {
153
-        $result = $this->client->getItem(array(
154
-            "TableName"=> $this->config['access_token_table'],
155
-            "Key" => array('access_token'   => array('S' => $access_token))
156
-        ));
157
-        if ($result->count()==0) {
158
-            return false ;
159
-        }
160
-        $token = $this->dynamo2array($result);
161
-        if (array_key_exists ('expires', $token)) {
162
-            $token['expires'] = strtotime($token['expires']);
163
-        }
164
-
165
-        return $token;
166
-    }
167
-
168
-    public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null)
169
-    {
170
-        // convert expires to datestring
171
-        $expires = date('Y-m-d H:i:s', $expires);
172
-
173
-        $clientData = compact('access_token', 'client_id', 'user_id', 'expires', 'scope');
174
-        $clientData = array_filter($clientData, function ($value) { return !empty($value); });
175
-
176
-        $this->client->putItem(array(
177
-            'TableName' =>  $this->config['access_token_table'],
178
-            'Item' => $this->client->formatAttributes($clientData)
179
-        ));
180
-
181
-        return true;
182
-
183
-    }
184
-
185
-    public function unsetAccessToken($access_token)
186
-    {
187
-        $this->client->deleteItem(array(
188
-            'TableName' =>  $this->config['access_token_table'],
189
-            'Key' => $this->client->formatAttributes(array("access_token" => $access_token))
190
-        ));
191
-
192
-        return true;
193
-    }
194
-
195
-    /* OAuth2\Storage\AuthorizationCodeInterface */
196
-    public function getAuthorizationCode($code)
197
-    {
198
-        $result = $this->client->getItem(array(
199
-            "TableName"=> $this->config['code_table'],
200
-            "Key" => array('authorization_code'   => array('S' => $code))
201
-        ));
202
-        if ($result->count()==0) {
203
-            return false ;
204
-        }
205
-        $token = $this->dynamo2array($result);
206
-        if (!array_key_exists("id_token", $token )) {
207
-            $token['id_token'] = null;
208
-        }
209
-        $token['expires'] = strtotime($token['expires']);
210
-
211
-        return $token;
212
-
213
-    }
214
-
215
-    public function setAuthorizationCode($authorization_code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null)
216
-    {
217
-        // convert expires to datestring
218
-        $expires = date('Y-m-d H:i:s', $expires);
219
-
220
-        $clientData = compact('authorization_code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'id_token', 'scope');
221
-        $clientData = array_filter($clientData, function ($value) { return !empty($value); });
222
-
223
-        $this->client->putItem(array(
224
-            'TableName' =>  $this->config['code_table'],
225
-            'Item' => $this->client->formatAttributes($clientData)
226
-        ));
227
-
228
-        return true;
229
-    }
230
-
231
-    public function expireAuthorizationCode($code)
232
-    {
233
-
234
-        $this->client->deleteItem(array(
235
-            'TableName' =>  $this->config['code_table'],
236
-            'Key' => $this->client->formatAttributes(array("authorization_code" => $code))
237
-        ));
238
-
239
-        return true;
240
-    }
241
-
242
-    /* OAuth2\Storage\UserCredentialsInterface */
243
-    public function checkUserCredentials($username, $password)
244
-    {
245
-        if ($user = $this->getUser($username)) {
246
-            return $this->checkPassword($user, $password);
247
-        }
248
-
249
-        return false;
250
-    }
251
-
252
-    public function getUserDetails($username)
253
-    {
254
-        return $this->getUser($username);
255
-    }
256
-
257
-    /* UserClaimsInterface */
258
-    public function getUserClaims($user_id, $claims)
259
-    {
260
-        if (!$userDetails = $this->getUserDetails($user_id)) {
261
-            return false;
262
-        }
263
-
264
-        $claims = explode(' ', trim($claims));
265
-        $userClaims = array();
266
-
267
-        // for each requested claim, if the user has the claim, set it in the response
268
-        $validClaims = explode(' ', self::VALID_CLAIMS);
269
-        foreach ($validClaims as $validClaim) {
270
-            if (in_array($validClaim, $claims)) {
271
-                if ($validClaim == 'address') {
272
-                    // address is an object with subfields
273
-                    $userClaims['address'] = $this->getUserClaim($validClaim, $userDetails['address'] ?: $userDetails);
274
-                } else {
275
-                    $userClaims = array_merge($userClaims, $this->getUserClaim($validClaim, $userDetails));
276
-                }
277
-            }
278
-        }
279
-
280
-        return $userClaims;
281
-    }
282
-
283
-    protected function getUserClaim($claim, $userDetails)
284
-    {
285
-        $userClaims = array();
286
-        $claimValuesString = constant(sprintf('self::%s_CLAIM_VALUES', strtoupper($claim)));
287
-        $claimValues = explode(' ', $claimValuesString);
288
-
289
-        foreach ($claimValues as $value) {
290
-            if ($value == 'email_verified') {
291
-                $userClaims[$value] = $userDetails[$value]=='true' ? true : false;
292
-            } else {
293
-                $userClaims[$value] = isset($userDetails[$value]) ? $userDetails[$value] : null;
294
-            }
295
-        }
296
-
297
-        return $userClaims;
298
-    }
299
-
300
-    /* OAuth2\Storage\RefreshTokenInterface */
301
-    public function getRefreshToken($refresh_token)
302
-    {
303
-        $result = $this->client->getItem(array(
304
-            "TableName"=> $this->config['refresh_token_table'],
305
-            "Key" => array('refresh_token'   => array('S' => $refresh_token))
306
-        ));
307
-        if ($result->count()==0) {
308
-            return false ;
309
-        }
310
-        $token = $this->dynamo2array($result);
311
-        $token['expires'] = strtotime($token['expires']);
312
-
313
-        return $token;
314
-    }
315
-
316
-    public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null)
317
-    {
318
-        // convert expires to datestring
319
-        $expires = date('Y-m-d H:i:s', $expires);
320
-
321
-        $clientData = compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope');
322
-        $clientData = array_filter($clientData, function ($value) { return !empty($value); });
323
-
324
-        $this->client->putItem(array(
325
-            'TableName' =>  $this->config['refresh_token_table'],
326
-            'Item' => $this->client->formatAttributes($clientData)
327
-        ));
328
-
329
-        return true;
330
-    }
331
-
332
-    public function unsetRefreshToken($refresh_token)
333
-    {
334
-       $this->client->deleteItem(array(
335
-            'TableName' =>  $this->config['refresh_token_table'],
336
-            'Key' => $this->client->formatAttributes(array("refresh_token" => $refresh_token))
337
-        ));
338
-
339
-        return true;
340
-    }
341
-
342
-    // plaintext passwords are bad!  Override this for your application
343
-    protected function checkPassword($user, $password)
344
-    {
345
-        return $user['password'] == sha1($password);
346
-    }
347
-
348
-    public function getUser($username)
349
-    {
350
-        $result = $this->client->getItem(array(
351
-            "TableName"=> $this->config['user_table'],
352
-            "Key" => array('username'   => array('S' => $username))
353
-        ));
354
-        if ($result->count()==0) {
355
-            return false ;
356
-        }
357
-        $token = $this->dynamo2array($result);
358
-        $token['user_id'] = $username;
359
-
360
-        return $token;
361
-    }
362
-
363
-    public function setUser($username, $password, $first_name = null, $last_name = null)
364
-    {
365
-        // do not store in plaintext
366
-        $password = sha1($password);
367
-
368
-        $clientData = compact('username', 'password', 'first_name', 'last_name');
369
-        $clientData = array_filter($clientData, function ($value) { return !is_null($value); });
370
-
371
-        $this->client->putItem(array(
372
-            'TableName' =>  $this->config['user_table'],
373
-            'Item' => $this->client->formatAttributes($clientData)
374
-        ));
375
-
376
-        return true;
377
-
378
-    }
379
-
380
-    /* ScopeInterface */
381
-    public function scopeExists($scope)
382
-    {
383
-        $scope = explode(' ', $scope);
384
-        $count = 0;
385
-        foreach ($scope as $key => $val) {
386
-            $result = $this->client->query(array(
387
-                'TableName'     => $this->config['scope_table'],
388
-                'Select'        => 'COUNT',
389
-                'KeyConditions' => array(
390
-                    'scope' => array(
391
-                        'AttributeValueList' => array(array('S' => $val)),
392
-                        'ComparisonOperator' => 'EQ'
393
-                    )
394
-                )
395
-            ));
396
-            $count += $result['Count'];
397
-        }
398
-
399
-        return $count == count($scope);
400
-    }
401
-
402
-    public function getDefaultScope($client_id = null)
403
-    {
404
-
405
-        $result = $this->client->query(array(
406
-            'TableName' => $this->config['scope_table'],
407
-            'IndexName' => 'is_default-index',
408
-            'Select' => 'ALL_ATTRIBUTES',
409
-            'KeyConditions' => array(
410
-                'is_default' => array(
411
-                    'AttributeValueList' => array(array('S' => 'true')),
412
-                    'ComparisonOperator' => 'EQ',
413
-                ),
414
-            )
415
-        ));
416
-        $defaultScope = array();
417
-        if ($result->count() > 0) {
418
-            $array = $result->toArray();
419
-            foreach ($array["Items"] as $item) {
420
-                $defaultScope[]  = $item['scope']['S'];
421
-            }
422
-
423
-            return empty($defaultScope) ? null : implode(' ', $defaultScope);
424
-        }
425
-
426
-        return null;
427
-    }
428
-
429
-    /* JWTBearerInterface */
430
-    public function getClientKey($client_id, $subject)
431
-    {
432
-        $result = $this->client->getItem(array(
433
-            "TableName"=> $this->config['jwt_table'],
434
-            "Key" => array('client_id'   => array('S' => $client_id), 'subject' => array('S' => $subject))
435
-        ));
436
-        if ($result->count()==0) {
437
-            return false ;
438
-        }
439
-        $token = $this->dynamo2array($result);
440
-
441
-        return $token['public_key'];
442
-    }
443
-
444
-    public function getClientScope($client_id)
445
-    {
446
-        if (!$clientDetails = $this->getClientDetails($client_id)) {
447
-            return false;
448
-        }
449
-
450
-        if (isset($clientDetails['scope'])) {
451
-            return $clientDetails['scope'];
452
-        }
453
-
454
-        return null;
455
-    }
456
-
457
-    public function getJti($client_id, $subject, $audience, $expires, $jti)
458
-    {
459
-        //TODO not use.
460
-    }
461
-
462
-    public function setJti($client_id, $subject, $audience, $expires, $jti)
463
-    {
464
-        //TODO not use.
465
-    }
466
-
467
-    /* PublicKeyInterface */
468
-    public function getPublicKey($client_id = '0')
469
-    {
470
-
471
-        $result = $this->client->getItem(array(
472
-            "TableName"=> $this->config['public_key_table'],
473
-            "Key" => array('client_id'   => array('S' => $client_id))
474
-        ));
475
-        if ($result->count()==0) {
476
-            return false ;
477
-        }
478
-        $token = $this->dynamo2array($result);
479
-
480
-        return $token['public_key'];
481
-
482
-    }
483
-
484
-    public function getPrivateKey($client_id = '0')
485
-    {
486
-        $result = $this->client->getItem(array(
487
-            "TableName"=> $this->config['public_key_table'],
488
-            "Key" => array('client_id'   => array('S' => $client_id))
489
-        ));
490
-        if ($result->count()==0) {
491
-            return false ;
492
-        }
493
-        $token = $this->dynamo2array($result);
494
-
495
-        return $token['private_key'];
496
-    }
497
-
498
-    public function getEncryptionAlgorithm($client_id = null)
499
-    {
500
-        $result = $this->client->getItem(array(
501
-            "TableName"=> $this->config['public_key_table'],
502
-            "Key" => array('client_id'   => array('S' => $client_id))
503
-        ));
504
-        if ($result->count()==0) {
505
-            return 'RS256' ;
506
-        }
507
-        $token = $this->dynamo2array($result);
508
-
509
-        return $token['encryption_algorithm'];
510
-    }
511
-
512
-    /**
513
-     * Transform dynamodb resultset to an array.
514
-     * @param $dynamodbResult
515
-     * @return $array
516
-     */
517
-    private function dynamo2array($dynamodbResult)
518
-    {
519
-        $result = array();
520
-        foreach ($dynamodbResult["Item"] as $key => $val) {
521
-            $result[$key] = $val["S"];
522
-            $result[] = $val["S"];
523
-        }
524
-
525
-        return $result;
526
-    }
46
+	protected $client;
47
+	protected $config;
48
+
49
+	public function __construct($connection, $config = array())
50
+	{
51
+		if (!($connection instanceof DynamoDbClient)) {
52
+			if (!is_array($connection)) {
53
+				throw new \InvalidArgumentException('First argument to OAuth2\Storage\Dynamodb must be an instance a configuration array containt key, secret, region');
54
+			}
55
+			if (!array_key_exists("key",$connection) || !array_key_exists("secret",$connection) || !array_key_exists("region",$connection) ) {
56
+				throw new \InvalidArgumentException('First argument to OAuth2\Storage\Dynamodb must be an instance a configuration array containt key, secret, region');
57
+			}
58
+			$this->client = DynamoDbClient::factory(array(
59
+				'key' => $connection["key"],
60
+				'secret' => $connection["secret"],
61
+				'region' =>$connection["region"]
62
+			));
63
+		} else {
64
+			$this->client = $connection;
65
+		}
66
+
67
+		$this->config = array_merge(array(
68
+			'client_table' => 'oauth_clients',
69
+			'access_token_table' => 'oauth_access_tokens',
70
+			'refresh_token_table' => 'oauth_refresh_tokens',
71
+			'code_table' => 'oauth_authorization_codes',
72
+			'user_table' => 'oauth_users',
73
+			'jwt_table'  => 'oauth_jwt',
74
+			'scope_table'  => 'oauth_scopes',
75
+			'public_key_table'  => 'oauth_public_keys',
76
+		), $config);
77
+	}
78
+
79
+	/* OAuth2\Storage\ClientCredentialsInterface */
80
+	public function checkClientCredentials($client_id, $client_secret = null)
81
+	{
82
+		$result = $this->client->getItem(array(
83
+			"TableName"=> $this->config['client_table'],
84
+			"Key" => array('client_id'   => array('S' => $client_id))
85
+		));
86
+
87
+		return  $result->count()==1 && $result["Item"]["client_secret"]["S"] == $client_secret;
88
+	}
89
+
90
+	public function isPublicClient($client_id)
91
+	{
92
+		$result = $this->client->getItem(array(
93
+			"TableName"=> $this->config['client_table'],
94
+			"Key" => array('client_id'   => array('S' => $client_id))
95
+		));
96
+
97
+		if ($result->count()==0) {
98
+			return false ;
99
+		}
100
+
101
+		return empty($result["Item"]["client_secret"]);
102
+	}
103
+
104
+	/* OAuth2\Storage\ClientInterface */
105
+	public function getClientDetails($client_id)
106
+	{
107
+		$result = $this->client->getItem(array(
108
+			"TableName"=> $this->config['client_table'],
109
+			"Key" => array('client_id'   => array('S' => $client_id))
110
+		));
111
+		if ($result->count()==0) {
112
+			return false ;
113
+		}
114
+		$result = $this->dynamo2array($result);
115
+		foreach (array('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id') as $key => $val) {
116
+			if (!array_key_exists ($val, $result)) {
117
+				$result[$val] = null;
118
+			}
119
+		}
120
+
121
+		return $result;
122
+	}
123
+
124
+	public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null)
125
+	{
126
+		$clientData = compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id');
127
+		$clientData = array_filter($clientData, function ($value) { return !is_null($value); });
128
+
129
+		$this->client->putItem(array(
130
+			'TableName' =>  $this->config['client_table'],
131
+			'Item' => $this->client->formatAttributes($clientData)
132
+		));
133
+
134
+		return true;
135
+	}
136
+
137
+	public function checkRestrictedGrantType($client_id, $grant_type)
138
+	{
139
+		$details = $this->getClientDetails($client_id);
140
+		if (isset($details['grant_types'])) {
141
+			$grant_types = explode(' ', $details['grant_types']);
142
+
143
+			return in_array($grant_type, (array) $grant_types);
144
+		}
145
+
146
+		// if grant_types are not defined, then none are restricted
147
+		return true;
148
+	}
149
+
150
+	/* OAuth2\Storage\AccessTokenInterface */
151
+	public function getAccessToken($access_token)
152
+	{
153
+		$result = $this->client->getItem(array(
154
+			"TableName"=> $this->config['access_token_table'],
155
+			"Key" => array('access_token'   => array('S' => $access_token))
156
+		));
157
+		if ($result->count()==0) {
158
+			return false ;
159
+		}
160
+		$token = $this->dynamo2array($result);
161
+		if (array_key_exists ('expires', $token)) {
162
+			$token['expires'] = strtotime($token['expires']);
163
+		}
164
+
165
+		return $token;
166
+	}
167
+
168
+	public function setAccessToken($access_token, $client_id, $user_id, $expires, $scope = null)
169
+	{
170
+		// convert expires to datestring
171
+		$expires = date('Y-m-d H:i:s', $expires);
172
+
173
+		$clientData = compact('access_token', 'client_id', 'user_id', 'expires', 'scope');
174
+		$clientData = array_filter($clientData, function ($value) { return !empty($value); });
175
+
176
+		$this->client->putItem(array(
177
+			'TableName' =>  $this->config['access_token_table'],
178
+			'Item' => $this->client->formatAttributes($clientData)
179
+		));
180
+
181
+		return true;
182
+
183
+	}
184
+
185
+	public function unsetAccessToken($access_token)
186
+	{
187
+		$this->client->deleteItem(array(
188
+			'TableName' =>  $this->config['access_token_table'],
189
+			'Key' => $this->client->formatAttributes(array("access_token" => $access_token))
190
+		));
191
+
192
+		return true;
193
+	}
194
+
195
+	/* OAuth2\Storage\AuthorizationCodeInterface */
196
+	public function getAuthorizationCode($code)
197
+	{
198
+		$result = $this->client->getItem(array(
199
+			"TableName"=> $this->config['code_table'],
200
+			"Key" => array('authorization_code'   => array('S' => $code))
201
+		));
202
+		if ($result->count()==0) {
203
+			return false ;
204
+		}
205
+		$token = $this->dynamo2array($result);
206
+		if (!array_key_exists("id_token", $token )) {
207
+			$token['id_token'] = null;
208
+		}
209
+		$token['expires'] = strtotime($token['expires']);
210
+
211
+		return $token;
212
+
213
+	}
214
+
215
+	public function setAuthorizationCode($authorization_code, $client_id, $user_id, $redirect_uri, $expires, $scope = null, $id_token = null)
216
+	{
217
+		// convert expires to datestring
218
+		$expires = date('Y-m-d H:i:s', $expires);
219
+
220
+		$clientData = compact('authorization_code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'id_token', 'scope');
221
+		$clientData = array_filter($clientData, function ($value) { return !empty($value); });
222
+
223
+		$this->client->putItem(array(
224
+			'TableName' =>  $this->config['code_table'],
225
+			'Item' => $this->client->formatAttributes($clientData)
226
+		));
227
+
228
+		return true;
229
+	}
230
+
231
+	public function expireAuthorizationCode($code)
232
+	{
233
+
234
+		$this->client->deleteItem(array(
235
+			'TableName' =>  $this->config['code_table'],
236
+			'Key' => $this->client->formatAttributes(array("authorization_code" => $code))
237
+		));
238
+
239
+		return true;
240
+	}
241
+
242
+	/* OAuth2\Storage\UserCredentialsInterface */
243
+	public function checkUserCredentials($username, $password)
244
+	{
245
+		if ($user = $this->getUser($username)) {
246
+			return $this->checkPassword($user, $password);
247
+		}
248
+
249
+		return false;
250
+	}
251
+
252
+	public function getUserDetails($username)
253
+	{
254
+		return $this->getUser($username);
255
+	}
256
+
257
+	/* UserClaimsInterface */
258
+	public function getUserClaims($user_id, $claims)
259
+	{
260
+		if (!$userDetails = $this->getUserDetails($user_id)) {
261
+			return false;
262
+		}
263
+
264
+		$claims = explode(' ', trim($claims));
265
+		$userClaims = array();
266
+
267
+		// for each requested claim, if the user has the claim, set it in the response
268
+		$validClaims = explode(' ', self::VALID_CLAIMS);
269
+		foreach ($validClaims as $validClaim) {
270
+			if (in_array($validClaim, $claims)) {
271
+				if ($validClaim == 'address') {
272
+					// address is an object with subfields
273
+					$userClaims['address'] = $this->getUserClaim($validClaim, $userDetails['address'] ?: $userDetails);
274
+				} else {
275
+					$userClaims = array_merge($userClaims, $this->getUserClaim($validClaim, $userDetails));
276
+				}
277
+			}
278
+		}
279
+
280
+		return $userClaims;
281
+	}
282
+
283
+	protected function getUserClaim($claim, $userDetails)
284
+	{
285
+		$userClaims = array();
286
+		$claimValuesString = constant(sprintf('self::%s_CLAIM_VALUES', strtoupper($claim)));
287
+		$claimValues = explode(' ', $claimValuesString);
288
+
289
+		foreach ($claimValues as $value) {
290
+			if ($value == 'email_verified') {
291
+				$userClaims[$value] = $userDetails[$value]=='true' ? true : false;
292
+			} else {
293
+				$userClaims[$value] = isset($userDetails[$value]) ? $userDetails[$value] : null;
294
+			}
295
+		}
296
+
297
+		return $userClaims;
298
+	}
299
+
300
+	/* OAuth2\Storage\RefreshTokenInterface */
301
+	public function getRefreshToken($refresh_token)
302
+	{
303
+		$result = $this->client->getItem(array(
304
+			"TableName"=> $this->config['refresh_token_table'],
305
+			"Key" => array('refresh_token'   => array('S' => $refresh_token))
306
+		));
307
+		if ($result->count()==0) {
308
+			return false ;
309
+		}
310
+		$token = $this->dynamo2array($result);
311
+		$token['expires'] = strtotime($token['expires']);
312
+
313
+		return $token;
314
+	}
315
+
316
+	public function setRefreshToken($refresh_token, $client_id, $user_id, $expires, $scope = null)
317
+	{
318
+		// convert expires to datestring
319
+		$expires = date('Y-m-d H:i:s', $expires);
320
+
321
+		$clientData = compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope');
322
+		$clientData = array_filter($clientData, function ($value) { return !empty($value); });
323
+
324
+		$this->client->putItem(array(
325
+			'TableName' =>  $this->config['refresh_token_table'],
326
+			'Item' => $this->client->formatAttributes($clientData)
327
+		));
328
+
329
+		return true;
330
+	}
331
+
332
+	public function unsetRefreshToken($refresh_token)
333
+	{
334
+	   $this->client->deleteItem(array(
335
+			'TableName' =>  $this->config['refresh_token_table'],
336
+			'Key' => $this->client->formatAttributes(array("refresh_token" => $refresh_token))
337
+		));
338
+
339
+		return true;
340
+	}
341
+
342
+	// plaintext passwords are bad!  Override this for your application
343
+	protected function checkPassword($user, $password)
344
+	{
345
+		return $user['password'] == sha1($password);
346
+	}
347
+
348
+	public function getUser($username)
349
+	{
350
+		$result = $this->client->getItem(array(
351
+			"TableName"=> $this->config['user_table'],
352
+			"Key" => array('username'   => array('S' => $username))
353
+		));
354
+		if ($result->count()==0) {
355
+			return false ;
356
+		}
357
+		$token = $this->dynamo2array($result);
358
+		$token['user_id'] = $username;
359
+
360
+		return $token;
361
+	}
362
+
363
+	public function setUser($username, $password, $first_name = null, $last_name = null)
364
+	{
365
+		// do not store in plaintext
366
+		$password = sha1($password);
367
+
368
+		$clientData = compact('username', 'password', 'first_name', 'last_name');
369
+		$clientData = array_filter($clientData, function ($value) { return !is_null($value); });
370
+
371
+		$this->client->putItem(array(
372
+			'TableName' =>  $this->config['user_table'],
373
+			'Item' => $this->client->formatAttributes($clientData)
374
+		));
375
+
376
+		return true;
377
+
378
+	}
379
+
380
+	/* ScopeInterface */
381
+	public function scopeExists($scope)
382
+	{
383
+		$scope = explode(' ', $scope);
384
+		$count = 0;
385
+		foreach ($scope as $key => $val) {
386
+			$result = $this->client->query(array(
387
+				'TableName'     => $this->config['scope_table'],
388
+				'Select'        => 'COUNT',
389
+				'KeyConditions' => array(
390
+					'scope' => array(
391
+						'AttributeValueList' => array(array('S' => $val)),
392
+						'ComparisonOperator' => 'EQ'
393
+					)
394
+				)
395
+			));
396
+			$count += $result['Count'];
397
+		}
398
+
399
+		return $count == count($scope);
400
+	}
401
+
402
+	public function getDefaultScope($client_id = null)
403
+	{
404
+
405
+		$result = $this->client->query(array(
406
+			'TableName' => $this->config['scope_table'],
407
+			'IndexName' => 'is_default-index',
408
+			'Select' => 'ALL_ATTRIBUTES',
409
+			'KeyConditions' => array(
410
+				'is_default' => array(
411
+					'AttributeValueList' => array(array('S' => 'true')),
412
+					'ComparisonOperator' => 'EQ',
413
+				),
414
+			)
415
+		));
416
+		$defaultScope = array();
417
+		if ($result->count() > 0) {
418
+			$array = $result->toArray();
419
+			foreach ($array["Items"] as $item) {
420
+				$defaultScope[]  = $item['scope']['S'];
421
+			}
422
+
423
+			return empty($defaultScope) ? null : implode(' ', $defaultScope);
424
+		}
425
+
426
+		return null;
427
+	}
428
+
429
+	/* JWTBearerInterface */
430
+	public function getClientKey($client_id, $subject)
431
+	{
432
+		$result = $this->client->getItem(array(
433
+			"TableName"=> $this->config['jwt_table'],
434
+			"Key" => array('client_id'   => array('S' => $client_id), 'subject' => array('S' => $subject))
435
+		));
436
+		if ($result->count()==0) {
437
+			return false ;
438
+		}
439
+		$token = $this->dynamo2array($result);
440
+
441
+		return $token['public_key'];
442
+	}
443
+
444
+	public function getClientScope($client_id)
445
+	{
446
+		if (!$clientDetails = $this->getClientDetails($client_id)) {
447
+			return false;
448
+		}
449
+
450
+		if (isset($clientDetails['scope'])) {
451
+			return $clientDetails['scope'];
452
+		}
453
+
454
+		return null;
455
+	}
456
+
457
+	public function getJti($client_id, $subject, $audience, $expires, $jti)
458
+	{
459
+		//TODO not use.
460
+	}
461
+
462
+	public function setJti($client_id, $subject, $audience, $expires, $jti)
463
+	{
464
+		//TODO not use.
465
+	}
466
+
467
+	/* PublicKeyInterface */
468
+	public function getPublicKey($client_id = '0')
469
+	{
470
+
471
+		$result = $this->client->getItem(array(
472
+			"TableName"=> $this->config['public_key_table'],
473
+			"Key" => array('client_id'   => array('S' => $client_id))
474
+		));
475
+		if ($result->count()==0) {
476
+			return false ;
477
+		}
478
+		$token = $this->dynamo2array($result);
479
+
480
+		return $token['public_key'];
481
+
482
+	}
483
+
484
+	public function getPrivateKey($client_id = '0')
485
+	{
486
+		$result = $this->client->getItem(array(
487
+			"TableName"=> $this->config['public_key_table'],
488
+			"Key" => array('client_id'   => array('S' => $client_id))
489
+		));
490
+		if ($result->count()==0) {
491
+			return false ;
492
+		}
493
+		$token = $this->dynamo2array($result);
494
+
495
+		return $token['private_key'];
496
+	}
497
+
498
+	public function getEncryptionAlgorithm($client_id = null)
499
+	{
500
+		$result = $this->client->getItem(array(
501
+			"TableName"=> $this->config['public_key_table'],
502
+			"Key" => array('client_id'   => array('S' => $client_id))
503
+		));
504
+		if ($result->count()==0) {
505
+			return 'RS256' ;
506
+		}
507
+		$token = $this->dynamo2array($result);
508
+
509
+		return $token['encryption_algorithm'];
510
+	}
511
+
512
+	/**
513
+	 * Transform dynamodb resultset to an array.
514
+	 * @param $dynamodbResult
515
+	 * @return $array
516
+	 */
517
+	private function dynamo2array($dynamodbResult)
518
+	{
519
+		$result = array();
520
+		foreach ($dynamodbResult["Item"] as $key => $val) {
521
+			$result[$key] = $val["S"];
522
+			$result[] = $val["S"];
523
+		}
524
+
525
+		return $result;
526
+	}
527 527
 }
Please login to merge, or discard this patch.
Spacing   +32 added lines, -32 removed lines patch added patch discarded remove patch
@@ -52,7 +52,7 @@  discard block
 block discarded – undo
52 52
             if (!is_array($connection)) {
53 53
                 throw new \InvalidArgumentException('First argument to OAuth2\Storage\Dynamodb must be an instance a configuration array containt key, secret, region');
54 54
             }
55
-            if (!array_key_exists("key",$connection) || !array_key_exists("secret",$connection) || !array_key_exists("region",$connection) ) {
55
+            if (!array_key_exists("key", $connection) || !array_key_exists("secret", $connection) || !array_key_exists("region", $connection)) {
56 56
                 throw new \InvalidArgumentException('First argument to OAuth2\Storage\Dynamodb must be an instance a configuration array containt key, secret, region');
57 57
             }
58 58
             $this->client = DynamoDbClient::factory(array(
@@ -84,7 +84,7 @@  discard block
 block discarded – undo
84 84
             "Key" => array('client_id'   => array('S' => $client_id))
85 85
         ));
86 86
 
87
-        return  $result->count()==1 && $result["Item"]["client_secret"]["S"] == $client_secret;
87
+        return  $result->count() == 1 && $result["Item"]["client_secret"]["S"] == $client_secret;
88 88
     }
89 89
 
90 90
     public function isPublicClient($client_id)
@@ -94,8 +94,8 @@  discard block
 block discarded – undo
94 94
             "Key" => array('client_id'   => array('S' => $client_id))
95 95
         ));
96 96
 
97
-        if ($result->count()==0) {
98
-            return false ;
97
+        if ($result->count() == 0) {
98
+            return false;
99 99
         }
100 100
 
101 101
         return empty($result["Item"]["client_secret"]);
@@ -108,12 +108,12 @@  discard block
 block discarded – undo
108 108
             "TableName"=> $this->config['client_table'],
109 109
             "Key" => array('client_id'   => array('S' => $client_id))
110 110
         ));
111
-        if ($result->count()==0) {
112
-            return false ;
111
+        if ($result->count() == 0) {
112
+            return false;
113 113
         }
114 114
         $result = $this->dynamo2array($result);
115 115
         foreach (array('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id') as $key => $val) {
116
-            if (!array_key_exists ($val, $result)) {
116
+            if (!array_key_exists($val, $result)) {
117 117
                 $result[$val] = null;
118 118
             }
119 119
         }
@@ -124,7 +124,7 @@  discard block
 block discarded – undo
124 124
     public function setClientDetails($client_id, $client_secret = null, $redirect_uri = null, $grant_types = null, $scope = null, $user_id = null)
125 125
     {
126 126
         $clientData = compact('client_id', 'client_secret', 'redirect_uri', 'grant_types', 'scope', 'user_id');
127
-        $clientData = array_filter($clientData, function ($value) { return !is_null($value); });
127
+        $clientData = array_filter($clientData, function($value) { return !is_null($value); });
128 128
 
129 129
         $this->client->putItem(array(
130 130
             'TableName' =>  $this->config['client_table'],
@@ -154,11 +154,11 @@  discard block
 block discarded – undo
154 154
             "TableName"=> $this->config['access_token_table'],
155 155
             "Key" => array('access_token'   => array('S' => $access_token))
156 156
         ));
157
-        if ($result->count()==0) {
158
-            return false ;
157
+        if ($result->count() == 0) {
158
+            return false;
159 159
         }
160 160
         $token = $this->dynamo2array($result);
161
-        if (array_key_exists ('expires', $token)) {
161
+        if (array_key_exists('expires', $token)) {
162 162
             $token['expires'] = strtotime($token['expires']);
163 163
         }
164 164
 
@@ -171,7 +171,7 @@  discard block
 block discarded – undo
171 171
         $expires = date('Y-m-d H:i:s', $expires);
172 172
 
173 173
         $clientData = compact('access_token', 'client_id', 'user_id', 'expires', 'scope');
174
-        $clientData = array_filter($clientData, function ($value) { return !empty($value); });
174
+        $clientData = array_filter($clientData, function($value) { return !empty($value); });
175 175
 
176 176
         $this->client->putItem(array(
177 177
             'TableName' =>  $this->config['access_token_table'],
@@ -199,11 +199,11 @@  discard block
 block discarded – undo
199 199
             "TableName"=> $this->config['code_table'],
200 200
             "Key" => array('authorization_code'   => array('S' => $code))
201 201
         ));
202
-        if ($result->count()==0) {
203
-            return false ;
202
+        if ($result->count() == 0) {
203
+            return false;
204 204
         }
205 205
         $token = $this->dynamo2array($result);
206
-        if (!array_key_exists("id_token", $token )) {
206
+        if (!array_key_exists("id_token", $token)) {
207 207
             $token['id_token'] = null;
208 208
         }
209 209
         $token['expires'] = strtotime($token['expires']);
@@ -218,7 +218,7 @@  discard block
 block discarded – undo
218 218
         $expires = date('Y-m-d H:i:s', $expires);
219 219
 
220 220
         $clientData = compact('authorization_code', 'client_id', 'user_id', 'redirect_uri', 'expires', 'id_token', 'scope');
221
-        $clientData = array_filter($clientData, function ($value) { return !empty($value); });
221
+        $clientData = array_filter($clientData, function($value) { return !empty($value); });
222 222
 
223 223
         $this->client->putItem(array(
224 224
             'TableName' =>  $this->config['code_table'],
@@ -288,7 +288,7 @@  discard block
 block discarded – undo
288 288
 
289 289
         foreach ($claimValues as $value) {
290 290
             if ($value == 'email_verified') {
291
-                $userClaims[$value] = $userDetails[$value]=='true' ? true : false;
291
+                $userClaims[$value] = $userDetails[$value] == 'true' ? true : false;
292 292
             } else {
293 293
                 $userClaims[$value] = isset($userDetails[$value]) ? $userDetails[$value] : null;
294 294
             }
@@ -304,8 +304,8 @@  discard block
 block discarded – undo
304 304
             "TableName"=> $this->config['refresh_token_table'],
305 305
             "Key" => array('refresh_token'   => array('S' => $refresh_token))
306 306
         ));
307
-        if ($result->count()==0) {
308
-            return false ;
307
+        if ($result->count() == 0) {
308
+            return false;
309 309
         }
310 310
         $token = $this->dynamo2array($result);
311 311
         $token['expires'] = strtotime($token['expires']);
@@ -319,7 +319,7 @@  discard block
 block discarded – undo
319 319
         $expires = date('Y-m-d H:i:s', $expires);
320 320
 
321 321
         $clientData = compact('refresh_token', 'client_id', 'user_id', 'expires', 'scope');
322
-        $clientData = array_filter($clientData, function ($value) { return !empty($value); });
322
+        $clientData = array_filter($clientData, function($value) { return !empty($value); });
323 323
 
324 324
         $this->client->putItem(array(
325 325
             'TableName' =>  $this->config['refresh_token_table'],
@@ -351,8 +351,8 @@  discard block
 block discarded – undo
351 351
             "TableName"=> $this->config['user_table'],
352 352
             "Key" => array('username'   => array('S' => $username))
353 353
         ));
354
-        if ($result->count()==0) {
355
-            return false ;
354
+        if ($result->count() == 0) {
355
+            return false;
356 356
         }
357 357
         $token = $this->dynamo2array($result);
358 358
         $token['user_id'] = $username;
@@ -366,7 +366,7 @@  discard block
 block discarded – undo
366 366
         $password = sha1($password);
367 367
 
368 368
         $clientData = compact('username', 'password', 'first_name', 'last_name');
369
-        $clientData = array_filter($clientData, function ($value) { return !is_null($value); });
369
+        $clientData = array_filter($clientData, function($value) { return !is_null($value); });
370 370
 
371 371
         $this->client->putItem(array(
372 372
             'TableName' =>  $this->config['user_table'],
@@ -417,7 +417,7 @@  discard block
 block discarded – undo
417 417
         if ($result->count() > 0) {
418 418
             $array = $result->toArray();
419 419
             foreach ($array["Items"] as $item) {
420
-                $defaultScope[]  = $item['scope']['S'];
420
+                $defaultScope[] = $item['scope']['S'];
421 421
             }
422 422
 
423 423
             return empty($defaultScope) ? null : implode(' ', $defaultScope);
@@ -433,8 +433,8 @@  discard block
 block discarded – undo
433 433
             "TableName"=> $this->config['jwt_table'],
434 434
             "Key" => array('client_id'   => array('S' => $client_id), 'subject' => array('S' => $subject))
435 435
         ));
436
-        if ($result->count()==0) {
437
-            return false ;
436
+        if ($result->count() == 0) {
437
+            return false;
438 438
         }
439 439
         $token = $this->dynamo2array($result);
440 440
 
@@ -472,8 +472,8 @@  discard block
 block discarded – undo
472 472
             "TableName"=> $this->config['public_key_table'],
473 473
             "Key" => array('client_id'   => array('S' => $client_id))
474 474
         ));
475
-        if ($result->count()==0) {
476
-            return false ;
475
+        if ($result->count() == 0) {
476
+            return false;
477 477
         }
478 478
         $token = $this->dynamo2array($result);
479 479
 
@@ -487,8 +487,8 @@  discard block
 block discarded – undo
487 487
             "TableName"=> $this->config['public_key_table'],
488 488
             "Key" => array('client_id'   => array('S' => $client_id))
489 489
         ));
490
-        if ($result->count()==0) {
491
-            return false ;
490
+        if ($result->count() == 0) {
491
+            return false;
492 492
         }
493 493
         $token = $this->dynamo2array($result);
494 494
 
@@ -501,8 +501,8 @@  discard block
 block discarded – undo
501 501
             "TableName"=> $this->config['public_key_table'],
502 502
             "Key" => array('client_id'   => array('S' => $client_id))
503 503
         ));
504
-        if ($result->count()==0) {
505
-            return 'RS256' ;
504
+        if ($result->count() == 0) {
505
+            return 'RS256';
506 506
         }
507 507
         $token = $this->dynamo2array($result);
508 508
 
Please login to merge, or discard this patch.
extensions/libraries/redcore/api/oauth2/Storage/AccessTokenInterface.php 1 patch
Indentation   +48 added lines, -48 removed lines patch added patch discarded remove patch
@@ -10,54 +10,54 @@
 block discarded – undo
10 10
  */
11 11
 interface AccessTokenInterface
12 12
 {
13
-    /**
14
-     * Look up the supplied oauth_token from storage.
15
-     *
16
-     * We need to retrieve access token data as we create and verify tokens.
17
-     *
18
-     * @param $oauth_token
19
-     * oauth_token to be check with.
20
-     *
21
-     * @return
22
-     * An associative array as below, and return NULL if the supplied oauth_token
23
-     * is invalid:
24
-     * - expires: Stored expiration in unix timestamp.
25
-     * - client_id: (optional) Stored client identifier.
26
-     * - user_id: (optional) Stored user identifier.
27
-     * - scope: (optional) Stored scope values in space-separated string.
28
-     * - id_token: (optional) Stored id_token (if "use_openid_connect" is true).
29
-     *
30
-     * @ingroup oauth2_section_7
31
-     */
32
-    public function getAccessToken($oauth_token);
13
+	/**
14
+	 * Look up the supplied oauth_token from storage.
15
+	 *
16
+	 * We need to retrieve access token data as we create and verify tokens.
17
+	 *
18
+	 * @param $oauth_token
19
+	 * oauth_token to be check with.
20
+	 *
21
+	 * @return
22
+	 * An associative array as below, and return NULL if the supplied oauth_token
23
+	 * is invalid:
24
+	 * - expires: Stored expiration in unix timestamp.
25
+	 * - client_id: (optional) Stored client identifier.
26
+	 * - user_id: (optional) Stored user identifier.
27
+	 * - scope: (optional) Stored scope values in space-separated string.
28
+	 * - id_token: (optional) Stored id_token (if "use_openid_connect" is true).
29
+	 *
30
+	 * @ingroup oauth2_section_7
31
+	 */
32
+	public function getAccessToken($oauth_token);
33 33
 
34
-    /**
35
-     * Store the supplied access token values to storage.
36
-     *
37
-     * We need to store access token data as we create and verify tokens.
38
-     *
39
-     * @param $oauth_token    oauth_token to be stored.
40
-     * @param $client_id      client identifier to be stored.
41
-     * @param $user_id        user identifier to be stored.
42
-     * @param int    $expires expiration to be stored as a Unix timestamp.
43
-     * @param string $scope   OPTIONAL Scopes to be stored in space-separated string.
44
-     *
45
-     * @ingroup oauth2_section_4
46
-     */
47
-    public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = null);
34
+	/**
35
+	 * Store the supplied access token values to storage.
36
+	 *
37
+	 * We need to store access token data as we create and verify tokens.
38
+	 *
39
+	 * @param $oauth_token    oauth_token to be stored.
40
+	 * @param $client_id      client identifier to be stored.
41
+	 * @param $user_id        user identifier to be stored.
42
+	 * @param int    $expires expiration to be stored as a Unix timestamp.
43
+	 * @param string $scope   OPTIONAL Scopes to be stored in space-separated string.
44
+	 *
45
+	 * @ingroup oauth2_section_4
46
+	 */
47
+	public function setAccessToken($oauth_token, $client_id, $user_id, $expires, $scope = null);
48 48
 
49
-    /**
50
-     * Expire an access token.
51
-     *
52
-     * This is not explicitly required in the spec, but if defined in a draft RFC for token
53
-     * revoking (RFC 7009) https://tools.ietf.org/html/rfc7009
54
-     *
55
-     * @param $access_token
56
-     * Access token to be expired.
57
-     *
58
-     * @ingroup oauth2_section_6
59
-     *
60
-     * @todo v2.0 include this method in interface. Omitted to maintain BC in v1.x
61
-     */
62
-    //public function unsetAccessToken($access_token);
49
+	/**
50
+	 * Expire an access token.
51
+	 *
52
+	 * This is not explicitly required in the spec, but if defined in a draft RFC for token
53
+	 * revoking (RFC 7009) https://tools.ietf.org/html/rfc7009
54
+	 *
55
+	 * @param $access_token
56
+	 * Access token to be expired.
57
+	 *
58
+	 * @ingroup oauth2_section_6
59
+	 *
60
+	 * @todo v2.0 include this method in interface. Omitted to maintain BC in v1.x
61
+	 */
62
+	//public function unsetAccessToken($access_token);
63 63
 }
Please login to merge, or discard this patch.