summaryrefslogtreecommitdiff
path: root/Postman/Postman-Auth/PostmanAbstractAuthenticationManager.php
blob: 75d734b0f12fb16eda31da4e030a518d797fd676 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
<?php
if (! class_exists ( "PostmanAbstractAuthenticationManager" )) {
	
	require_once 'PostmanAuthenticationManager.php';
	
	/**
	 */
	abstract class PostmanAbstractAuthenticationManager implements PostmanAuthenticationManager {
		
		// constants
		const APPROVAL_PROMPT = 'force';
		const ACCESS_TYPE = 'offline';
		const ACCESS_TOKEN = 'access_token';
		const REFRESH_TOKEN = 'refresh_token';
		const EXPIRES = 'expires_in';
		
		// the oauth authorization options
		private $clientId;
		private $clientSecret;
		private $authorizationToken;
		private $callbackUri;
		private $logger;
		
		/**
		 * Constructor
		 */
		public function __construct(PostmanLogger $logger, $clientId, $clientSecret, PostmanOAuthToken $authorizationToken, $callbackUri) {
			assert ( ! empty ( $clientId ) );
			assert ( ! empty ( $clientSecret ) );
			assert ( ! empty ( $authorizationToken ) );
			assert ( ! empty ( $callbackUri ) );
			$this->logger = $logger;
			$this->clientId = $clientId;
			$this->clientSecret = $clientSecret;
			$this->authorizationToken = $authorizationToken;
			$this->callbackUri = $callbackUri;
		}
		protected function getLogger() {
			return $this->logger;
		}
		protected function getClientId() {
			return $this->clientId;
		}
		protected function getClientSecret() {
			return $this->clientSecret;
		}
		protected function getAuthorizationToken() {
			return $this->authorizationToken;
		}
		
		/**
		 * Create a state token to prevent request forgery.
		 * Store it in the session for later validation.
		 */
		public function generateRequestTransactionId() {
			return $state = md5 ( rand () );
		}
		
		/**
		 */
		public function isAccessTokenExpired() {
			$expireTime = ($this->authorizationToken->getExpiryTime () - self::FORCE_REFRESH_X_SECONDS_BEFORE_EXPIRE);
			$tokenHasExpired = time () > $expireTime;
			$this->logger->debug ( 'Access Token Expiry Time is ' . $expireTime . ', expires_in=' . ($expireTime - time ()) . ', expired=' . ($tokenHasExpired ? 'yes' : 'no') );
			return $tokenHasExpired;
		}
		
		/**
		 * Decoded the received token
		 * This code is identical for Google and Hotmail
		 *
		 * @param mixed $response        	
		 * @throws Exception
		 */
		protected function processResponse($response) {
			$authToken = json_decode ( stripslashes ( $response ) );
			if ($authToken === NULL) {
				$this->getLogger ()->error ( $response );
				throw new Exception ( $response );
			} else if (isset ( $authToken->{'error'} )) {
				if (isset ( $authToken->{'error_description'} )) {
					$this->getLogger ()->error ( $authToken->{'error'} . ' processing response: ' . $authToken->{'error_description'} );
					throw new Exception ( $authToken->{'error_description'} . '(' . $authToken->{'error'} . ')' );
				} else {
					// Yahoo doesn't give descriptions
					$this->getLogger ()->error ( $authToken->{'error'} . ' processing response' );
					throw new Exception ( $authToken->{'error'} );
				}
			} else {
				$this->getLogger ()->trace ( 'Processing response:' );
				$this->getLogger ()->trace ( $response );
				$this->decodeReceivedAuthorizationToken ( $authToken );
			}
		}
		
		/**
		 * Parses the authorization token and extracts the expiry time, accessToken,
		 * and if this is a first-time authorization, a refresh token.
		 *
		 * This code is identical for Google and Hotmail
		 *
		 * @param mixed $client        	
		 */
		protected function decodeReceivedAuthorizationToken($newtoken) {
			assert ( ! empty ( $newtoken ) );
			assert ( ! empty ( $newtoken->{self::EXPIRES} ) );
			assert ( ! empty ( $newtoken->{self::ACCESS_TOKEN} ) );
			
			// update expiry time
			if (empty ( $newtoken->{self::EXPIRES} )) {
				throw new Exception ( '[expires_in] value is missing from the authentication token' );
			}
			$newExpiryTime = time () + $newtoken->{self::EXPIRES};
			$this->getAuthorizationToken ()->setExpiryTime ( $newExpiryTime );
			$this->getLogger ()->debug ( 'Updating Access Token Expiry Time ' );
			
			// update acccess token
			if (empty ( $newtoken->{self::ACCESS_TOKEN} )) {
				throw new Exception ( '[access_token] value is missing from the authentication token' );
			}
			$newAccessToken = $newtoken->{self::ACCESS_TOKEN};
			$this->getAuthorizationToken ()->setAccessToken ( $newAccessToken );
			$this->getLogger ()->debug ( 'Updating Access Token' );
			
			// update refresh token, if there is one
			if (isset ( $newtoken->{self::REFRESH_TOKEN} )) {
				$newRefreshToken = $newtoken->{self::REFRESH_TOKEN};
				$this->getAuthorizationToken ()->setRefreshToken ( $newRefreshToken );
				$this->getLogger ()->debug ( 'Updating Refresh Token ' );
			}
		}
		
		/**
		 * Given an OAuth provider-specific URL and redirectUri,
		 * issue an HttpRequest to refresh the access token
		 *
		 * This code is identical for Google and Hotmail
		 */
		public function refreshToken() {
			$this->getLogger ()->debug ( 'Refreshing Token' );
			$refreshUrl = $this->getTokenUrl ();
			$callbackUrl = $this->getCallbackUri ();
			assert ( ! empty ( $refreshUrl ) );
			assert ( ! empty ( $callbackUrl ) );
			// the format of the URL is
			// client_id=CLIENT_ID&client_secret=CLIENT_SECRET&redirect_uri=REDIRECT_URI&grant_type=refresh_token&refresh_token=REFRESH_TOKEN
			$postvals = array (
					'client_id' => $this->getClientId (),
					'client_secret' => $this->getClientSecret (),
					'redirect_uri' => $callbackUrl,
					'grant_type' => 'refresh_token',
					'refresh_token' => $this->getAuthorizationToken ()->getRefreshToken () 
			);
			// example request string
			// client_id=0000000603DB0F&redirect_uri=http%3A%2F%2Fwww.contoso.com%2Fcallback.php&client_secret=LWILlT555GicSrIATma5qgyBXebRI&refresh_token=*LA9...//refresh token string shortened for example//...xRoX&grant_type=refresh_token
			$response = PostmanUtils::remotePostGetBodyOnly ( $refreshUrl, $postvals );
			$this->processResponse ( $response );
		}
		/**
		 * (non-PHPdoc)
		 *
		 * @see PostmanAuthenticationManager::getCallbackUri()
		 */
		public function getCallbackUri() {
			return $this->callbackUri;
		}
	}
}