2 var X_NET_OAUTH2_detection = new Function( 'w', 'try{return w.location.search}catch(e){}' ),
3 X_NET_OAUTH2_authorizationWindow,
4 X_NET_OAUTH2_authorizationTimerID;
9 * <dt>X.Event.NEED_AUTH<dd>window を popup して認可を行う必要あり。ポインターイベント内で oauth2.requestAuth() を呼ぶ。
10 * <dt>X.Event.CANCELED<dd>認可 window が閉じられた。([x]等でウインドウが閉じられた、oauth2.cancelAuth() が呼ばれた)
11 * <dt>X.Event.SUCCESS<dd>認可 window でユーザーが認可し、続いてコードの認可が済んだ。
12 * <dt>X.Event.ERROR<dd>コードの認可のエラー、リフレッシュトークンのエラー、ネットワークエラー
13 * <dt>X.Event.PROGRESS<dd>コードを window から受け取った、リフレッシュトークンの開始、コードの認可を header -> params に切替
17 * oauth2.js , <opendata@oucs.ox.ac.uk>
20 * @class OAuth2 サービスを定義し接続状況をモニタする。適宜にトークンのアップデートなどを行う
22 * @extends {EventDispatcher}
23 * @example // OAuth2 サービスの定義
25 'clientID' : 'xxxxxxxx.apps.googleusercontent.com',
26 'clientSecret' : 'xxxxxxxx',
27 'authorizeEndpoint' : 'https://accounts.google.com/o/oauth2/auth',
28 'tokenEndpoint' : 'https://accounts.google.com/o/oauth2/token',
29 'redirectURI' : X.URL.cleanup( document.location.href ), // 専用の軽量ページを用意してもよいが、現在のアドレスでも可能
30 'scopes' : [ 'https://www.googleapis.com/auth/blogger' ],
31 'authorizeWindowWidth' : 500,
32 'authorizeWindowHeight' : 500
33 }).listen( [ X.Event.NEED_AUTH, X.Event.CANCELED, X.Event.SUCCESS, X.Event.ERROR, X.Event.PROGRESS ], updateOAuth2State );
37 xhr : 'https://www.googleapis.com/blogger/v3/users/self/blogs',
40 test : 'gadget' // http -> https:xProtocol なリクエストのため、google ガジェットを proxy に使用
42 .listen( [ X.Event.SUCCESS, X.Event.ERROR, X.Event.PROGRESS ], updateOAuth2State );
44 X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
48 /** @lends OAuth2.prototype */
50 'Constructor' : function( obj ){
51 obj = X_Object_clone( obj );
53 X_Pair_create( this, obj );
55 if( _getAccessToken( this ) ){
57 this[ 'asyncDispatch' ]( X_EVENT_SUCCESS );
59 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
62 obj.onAuthError = X_NET_OAUTH2_onXHR401Error;
63 obj.updateRequest = X_NET_OAUTH2_updateRequest;
73 * <dt>1 : <dd>認可用 window がポップアップ中
75 * <dt>3 : <dd>トークンのリフレッシュ中
81 return X_Pair_get( this ).oauth2State || 0;
85 * 認可用 window をポップアップする。ポップアップブロックが働かないように必ず pointer event 内で呼ぶこと。
87 'requestAuth' : function(){
89 if( X_NET_OAUTH2_authorizationWindow ) return;
91 pair = X_Pair_get( this );
93 if( pair.net || pair.oauth2State ) return;
95 X_NET_OAUTH2_authorizationWindow = window.open(
96 pair[ 'authorizeEndpoint' ] + '?' + X_URL_objToParam(
98 'response_type' : 'code',
99 'client_id' : pair[ 'clientID' ],
100 'redirect_uri' : pair[ 'redirectURI' ],
101 'scope' : ( pair[ 'scopes' ] || []).join(' ')
104 'width=' + pair[ 'authorizeWindowWidth' ]
105 + ',height=' + pair[ 'authorizeWindowHeight' ]
106 + ',left=' + (screen.width - pair[ 'authorizeWindowWidth' ] ) / 2
107 + ',top=' + (screen.height - pair[ 'authorizeWindowHeight' ] ) / 2
108 + ',menubar=no,toolbar=no');
110 X_NET_OAUTH2_authorizationTimerID = X_Timer_add( 333, 0, this, X_Net_OAuth2_detectAuthPopup );
112 pair.oauth2State = 1;
114 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to auth.' } );
118 * 認可プロセスのキャンセル。ポップアップを閉じて認可用の通信は中断する。
120 'cancelAuth' : function(){
121 var pair = X_Pair_get( this );
124 pair.net[ 'kill' ]();
128 // http://kojikoji75.hatenablog.com/entry/2013/12/15/223839
129 X_NET_OAUTH2_authorizationWindow && X_NET_OAUTH2_authorizationWindow.open( 'about:blank', '_self' ).close();
130 X_NET_OAUTH2_authorizationWindow = null;
132 X_NET_OAUTH2_authorizationTimerID && X_Timer_remove( X_NET_OAUTH2_authorizationTimerID );
133 X_NET_OAUTH2_authorizationTimerID = 0;
135 this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
141 'refreshToken' : function(){
143 * var expires_at = this._getAccessTokenExpiry();
144 if (expires_at && Date.now() + millis > expires_at)
145 this._refreshAccessToken({replay: false});
148 pair = X_Pair_get( this );
150 if( pair.net ) return;
152 pair.oauth2State = 3;
155 'xhr' : pair[ 'tokenEndpoint' ],
156 'postdata' : X_URL_objToParam({
157 'client_id' : pair[ 'clientID' ],
158 'client_secret' : pair[ 'clientSecret' ],
159 'grant_type' : 'refresh_token',
160 'refresh_token' : _getRefreshToken( this )
164 'Accept' : 'application/json',
165 'Content-Type' : 'application/x-www-form-urlencoded'
168 } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], this, X_Net_OAuth2_responceHandler );
170 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to refresh token.' } );
175 function X_Net_OAuth2_detectAuthPopup(){
176 var closed, search, pair = X_Pair_get( this );
178 if( X_NET_OAUTH2_authorizationWindow.closed ){
179 pair.oauth2State = 0;
182 this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
184 if( search = X_NET_OAUTH2_detection( X_NET_OAUTH2_authorizationWindow ) ){
185 pair = X_Pair_get( this );
186 pair.code = X_URL_ParamToObj( search.slice( 1 ) )[ 'code' ];
188 X_NET_OAUTH2_authorizationWindow.open( 'about:blank', '_self' ).close();
191 X_Net_OAuth2_authorizationCode( this, pair );
193 pair.oauth2State = 2;
194 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Get code success, then authorization code.' } );
198 X_NET_OAUTH2_authorizationWindow = null;
199 X_NET_OAUTH2_authorizationTimerID = 0;
201 return X_Callback_UN_LISTEN;
205 function X_Net_OAuth2_authorizationCode( oauth2, pair ){
207 'xhr' : pair[ 'tokenEndpoint' ],
208 'postdata' : X_URL_objToParam({
209 'client_id' : pair[ 'clientID' ],
210 'client_secret' : pair[ 'clientSecret' ],
211 'grant_type' : 'authorization_code',
213 'redirect_uri' : pair[ 'redirectURI' ]
217 'Accept' : 'application/json',
218 'Content-Type' : 'application/x-www-form-urlencoded'
221 } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], oauth2, X_Net_OAuth2_responceHandler );
224 function X_Net_OAuth2_responceHandler( e ){
226 pair = X_Pair_get( this ),
227 isRefresh = pair.oauth2State === 3;
232 case X_EVENT_SUCCESS :
233 if( isRefresh && data.error ){
234 _removeRefreshToken( this );
235 pair.oauth2State = 0;
236 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Refresh access token error.' + data.error, data : data } );
237 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
241 pair.oauth2State = 0;
242 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Get new access token error.' + data.error, data : data } );
243 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
247 _setAccessToken( this, data[ 'access_token' ] || '' );
248 _setRefreshToken( this, data[ 'refresh_token' ] || '' );
250 if( data[ 'expires_in' ] ){
251 _setAccessTokenExpiry( this, X_Timer_now() + data[ 'expires_in' ] * 1000 );
253 if( _getAccessTokenExpiry( this ) ){
254 _removeAccessTokenExpiry( this );
257 pair.oauth2State = 4;
258 this[ 'asyncDispatch' ]( { type : X_EVENT_SUCCESS, message : isRefresh ? 'Refresh access token success.' : 'Get new access token success.' } );
263 // other error, not auth
264 pair.oauth2State = 0;
265 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Refresh access token error.' } );
266 _removeRefreshToken( this );
267 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
269 if( _getAuthMechanism( this ) === 'param' ){
270 pair.oauth2State = 0;
271 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'network-error' } );
273 pair.oauth2State = 0;
274 _setAuthMechanism( this, 'param' );
275 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Refresh access token failed. retry header -> param. ' } );
277 X_Net_OAuth2_authorizationCode( this, pair );
283 function X_NET_OAUTH2_onXHR401Error( oauth2, e ){
285 headers = e[ 'headers' ],
286 xhr, bearerParams, headersExposed = false;
288 if( _getAuthMechanism( oauth2 ) !== 'param' ){
289 xhr = X_NET_currentWrapper[ '_rawObject' ];
290 headersExposed = !X_Net_XHR_createXDR || !!headers; // this is a hack for Firefox and IE
291 bearerParams = headersExposed && ( headers[ 'WWW-Authenticate' ] || headers[ 'www-authenticate' ] );
292 X_Type_isArray( bearerParams ) && ( bearerParams = bearerParams.join( '\n' ) );
295 // http://d.hatena.ne.jp/ritou/20110402/1301679908
296 if ( bearerParams && bearerParams.indexOf( ' error=' ) === -1 ) {
297 pair.oauth2State = 0;
298 oauth2[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
300 if ((( bearerParams && bearerParams.indexOf( 'invalid_token' ) !== -1 ) || !headersExposed) && _getRefreshToken( oauth2 ) ) {
301 _removeAccessToken( oauth2 ); // It doesn't work any more.
302 pair.oauth2State = 3;
303 oauth2[ 'refreshToken' ]();
305 //if (!headersExposed && !_getRefreshToken( oauth2 )) {
306 _removeAccessToken( oauth2 ); // It doesn't work any more.
307 pair.oauth2State = 0;
308 oauth2[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
312 function X_NET_OAUTH2_updateRequest( oauth2, request ){
313 var token = _getAccessToken( oauth2 ),
314 mechanism = _getAuthMechanism( oauth2 ),
315 url = request[ 'url' ],
318 if( token && mechanism === 'param' ){
319 request[ 'url' ] = url + ((url.indexOf('?') !== -1) ? '&' : '?') + 'bearer_token=' + encodeURIComponent( token );
322 if( token && ( !mechanism || mechanism === 'header' ) ){
323 headers = request[ 'headers' ] || ( request[ 'headers' ] = {} );
324 headers[ 'Authorization' ] = 'Bearer ' + token;
328 function _getAccessToken( that ){ return updateLocalStorage( '', that, 'accessToken' ); }
329 function _getRefreshToken( that){ return updateLocalStorage( '', that, 'refreshToken' ); }
330 function _getAccessTokenExpiry( that ){ return updateLocalStorage( '', that, 'tokenExpiry' ); }
331 function _getAuthMechanism( that ){
332 // TODO use gadget | flash ...
333 // IE's XDomainRequest doesn't support sending headers, so don't try.
334 return X_Net_XHR_createXDR ? 'param' : updateLocalStorage( '', that, 'AuthMechanism' );
336 function _setAccessToken( that, value ){ updateLocalStorage( '+', that, 'accessToken' , value); }
337 function _setRefreshToken( that, value ){ updateLocalStorage( '+', that, 'refreshToken', value); }
338 function _setAccessTokenExpiry( that, value ){ updateLocalStorage( '+', that, 'tokenExpiry', value); }
339 function _setAuthMechanism( that, value ){ updateLocalStorage( '+', that, 'AuthMechanism', value); }
341 function _removeAccessToken( that ){ updateLocalStorage( '-', that, 'accessToken' ); }
342 function _removeRefreshToken( that ){ updateLocalStorage( '-', that, 'refreshToken' ); }
343 function _removeAccessTokenExpiry( that ){ updateLocalStorage( '-', that, 'tokenExpiry' ); }
344 function _removeAuthMechanism( that ){ updateLocalStorage( '-', that, 'AuthMechanism' ); }
346 function updateLocalStorage( cmd, that, name, value ){
347 var action = cmd === '+' ? 'setItem' : cmd === '-' ? 'removeItem' : 'getItem',
350 if( window.localStorage ){
351 return window.localStorage[ action ]( X_Pair_get( that )[ 'clientID' ] + name, value );
354 pair = X_Pair_get( that );
357 pair[ name ] = value;
360 if( pair[ name ] !== undefined ) delete pair[ name ];