1: <?php
2:
3: /**
4: * Oauth2 manager
5: * @package framework
6: * @subpackage oauth2
7: */
8:
9: /**
10: * Class for dealing with Oauth2
11: */
12: class Hm_Oauth2 {
13:
14: private $client_id;
15: private $client_secret;
16: private $redirect_uri;
17: private $api;
18:
19: /**
20: * Load default settings
21: * @param string $id Oath2 client id
22: * @param string $secret Oath2 client secret
23: * @param string $uri URI to redirect to from the remote site
24: */
25: public function __construct($id, $secret, $uri) {
26: $this->client_id = $id;
27: $this->client_secret = $secret;
28: $this->redirect_uri = $uri;
29: $this->api = new Hm_API_Curl();
30: }
31:
32: /**
33: * Build a URL to request an authorization
34: * @param string $url host to request authorization from
35: * @param string $scope oauth2 scope
36: * @param string $state current state of the oauth2 flow
37: * @param string $login_hint optional username
38: * @return string
39: */
40: public function request_authorization_url($url, $scope, $state, $login_hint = false) {
41: $res = sprintf('%s?response_type=code&amp;scope=%s&amp;state=%s&amp;'.
42: 'approval_prompt=force&amp;access_type=offline&amp;client_id=%s&amp;redirect_uri=%s',
43: $url, $scope, $state, $this->client_id, $this->redirect_uri);
44: if ($login_hint !== false) {
45: $res .= '&amp;login_hint='.$login_hint;
46: }
47: return $res;
48: }
49:
50: /**
51: * Use curl to exchange an authorization code for a token
52: * @param string $url url to post to
53: * @param string $authorization_code oauth2 auth code
54: * @param array $headers HTTP headers to add to the request
55: * @return array
56: */
57: public function request_token($url, $authorization_code, $headers = []) {
58: return $this->api->command($url, $headers, array('code' => $authorization_code, 'client_id' => $this->client_id,
59: 'client_secret' => $this->client_secret, 'redirect_uri' => $this->redirect_uri, 'grant_type' => 'authorization_code'));
60: }
61:
62: /**
63: * Use curl to refresh an access token
64: * @param string $url url to to post to
65: * @param string $refresh_token oauth2 refresh token
66: * @return array
67: */
68: public function refresh_token($url, $refresh_token) {
69: return $this->api->command($url, [], array('client_id' => $this->client_id, 'client_secret' => $this->client_secret,
70: 'refresh_token' => $refresh_token, 'grant_type' => 'refresh_token'));
71: }
72: }
73: