2 //{+oauth2"OAuth2 サービスの定義"(OAuth2外部サービスを定義し、認可プロセス・xhrの署名を自動化します)[+xhr]
3 var X_NET_OAUTH2_detection = new Function( 'w', 'try{return w.location.search}catch(e){}' ),
4 X_NET_OAUTH2_authorizationWindow,
5 X_NET_OAUTH2_authorizationTimerID;
10 * <dt>X.Event.NEED_AUTH<dd>window を popup して認可を行う必要あり。ポインターイベント内で oauth2.requestAuth() を呼ぶ。
11 * <dt>X.Event.CANCELED<dd>認可 window が閉じられた。([x]等でウインドウが閉じられた、oauth2.cancelAuth() が呼ばれた)
12 * <dt>X.Event.SUCCESS<dd>認可 window でユーザーが認可し、続いてコードの認可が済んだ。
13 * <dt>X.Event.ERROR<dd>コードの認可のエラー、リフレッシュトークンのエラー、ネットワークエラー
14 * <dt>X.Event.PROGRESS<dd>コードを window から受け取った、リフレッシュトークンの開始、コードの認可を header -> params に切替
18 * oauth2.js , <opendata@oucs.ox.ac.uk>
21 * @class OAuth2 サービスを定義し接続状況をモニタする。適宜にトークンのアップデートなどを行う
23 * @extends {EventDispatcher}
24 * @example // OAuth2 サービスの定義
26 'clientID' : 'xxxxxxxx.apps.googleusercontent.com',
27 'clientSecret' : 'xxxxxxxx',
28 'authorizeEndpoint' : 'https://accounts.google.com/o/oauth2/auth',
29 'tokenEndpoint' : 'https://accounts.google.com/o/oauth2/token',
30 'redirectURI' : X.URL.cleanup( document.location.href ), // 専用の軽量ページを用意してもよいが、現在のアドレスでも可能
31 'scopes' : [ 'https://www.googleapis.com/auth/blogger' ],
32 'refreshMargin' : 300000,
33 'authorizeWindowWidth' : 500,
34 'authorizeWindowHeight' : 500
35 }).listen( [ X.Event.NEED_AUTH, X.Event.CANCELED, X.Event.SUCCESS, X.Event.ERROR, X.Event.PROGRESS ], updateOAuth2State );
39 xhr : 'https://www.googleapis.com/blogger/v3/users/self/blogs',
42 test : 'gadget' // http -> https:xProtocol なリクエストのため、google ガジェットを proxy に使用
44 .listen( [ X.Event.SUCCESS, X.Event.ERROR, X.Event.PROGRESS ], updateOAuth2State );
46 X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
50 /** @lends OAuth2.prototype */
52 'Constructor' : function( obj ){
55 obj = X_Object_clone( obj );
57 X_Pair_create( this, obj );
59 obj.onAuthError = X_NET_OAUTH2_onXHR401Error;
60 obj.updateRequest = X_NET_OAUTH2_updateRequest;
62 if( X_OAuth2_getAccessToken( this ) && ( expires_at = X_OAuth2_getAccessTokenExpiry( this ) ) ){
63 if( expires_at < X_Timer_now() + ( obj[ 'refreshMargin' ] || 300000 ) ){ // 寿命が5分を切った
64 this[ 'refreshToken' ]();
67 this[ 'asyncDispatch' ]( X_EVENT_SUCCESS );
70 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
73 // TODO canUse gadgetProxy
74 this[ 'listen' ]( [ X_EVENT_KILL_INSTANCE, X_EVENT_SUCCESS, X_EVENT_ERROR, X_EVENT_NEED_AUTH ], X_NET_OAUTH2_handleEvent );
81 * <dt>1 : <dd>認可用 window がポップアップ中
83 * <dt>3 : <dd>トークンのリフレッシュ中
89 return X_Pair_get( this ).oauth2State || 0;
93 * 認可用 window をポップアップする。ポップアップブロックが働かないように必ず pointer event 内で呼ぶこと。
95 'requestAuth' : function(){
97 // TODO pointer event 内か?チェック
99 if( X_NET_OAUTH2_authorizationWindow ) return;
101 pair = X_Pair_get( this );
103 if( pair.net || pair.oauth2State ) return;
105 url = pair[ 'authorizeEndpoint' ];
106 w = pair[ 'authorizeWindowWidth' ] || 500;
107 h = pair[ 'authorizeWindowHeight' ] || 500;
109 X_NET_OAUTH2_authorizationWindow = window.open(
112 'response_type' : 'code',
113 'client_id' : pair[ 'clientID' ],
114 'redirect_uri' : pair[ 'redirectURI' ],
115 'scope' : ( pair[ 'scopes' ] || []).join(' ')
121 + ',left=' + ( screen.width - w ) / 2
122 + ',top=' + ( screen.height - h ) / 2
123 + ',menubar=no,toolbar=no');
125 X_NET_OAUTH2_authorizationTimerID = X_Timer_add( 333, 0, this, X_Net_OAuth2_detectAuthPopup );
127 pair.oauth2State = 1;
129 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to auth.' } );
133 * 認可プロセスのキャンセル。ポップアップを閉じて認可用の通信は中断する。
135 'cancelAuth' : function(){
136 var pair = X_Pair_get( this );
139 pair.net[ 'kill' ]();
143 if( pair.oauth2State !== 1 ){
147 // http://kojikoji75.hatenablog.com/entry/2013/12/15/223839
148 X_NET_OAUTH2_authorizationWindow && X_NET_OAUTH2_authorizationWindow.open( 'about:blank', '_self' ).close();
149 X_NET_OAUTH2_authorizationWindow = null;
151 X_NET_OAUTH2_authorizationTimerID && X_Timer_remove( X_NET_OAUTH2_authorizationTimerID );
152 X_NET_OAUTH2_authorizationTimerID = 0;
154 this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
160 'refreshToken' : function(){
161 var pair = X_Pair_get( this );
163 if( pair.net ) return;
165 if( pair.refreshTimerID ){
166 X_Timer_remove( pair.refreshTimerID );
167 delete pair.refreshTimerID;
170 pair.oauth2State = 3;
173 'xhr' : pair[ 'tokenEndpoint' ],
174 'postdata' : X_URL_objToParam({
175 'client_id' : pair[ 'clientID' ],
176 'client_secret' : pair[ 'clientSecret' ],
177 'grant_type' : 'refresh_token',
178 'refresh_token' : X_OAuth2_getRefreshToken( this )
182 'Accept' : 'application/json',
183 'Content-Type' : 'application/x-www-form-urlencoded'
186 } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], this, X_Net_OAuth2_responceHandler );
188 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to refresh token.' } );
193 function X_NET_OAUTH2_handleEvent( e ){
194 var pair = X_Pair_get( this );
197 case X_EVENT_KILL_INSTANCE :
198 this[ 'cancelAuth' ]();
201 case X_EVENT_NEED_AUTH :
202 pair.refreshTimerID && X_Timer_remove( pair.refreshTimerID );
205 case X_EVENT_SUCCESS :
206 pair.refreshTimerID && X_Timer_remove( pair.refreshTimerID );
207 if( X_OAuth2_getRefreshToken( this ) ){
209 pair.refreshTimerID = X_Timer_once( X_OAuth2_getAccessTokenExpiry( this ) - X_Timer_now() - pair[ 'refreshMargin' ], this, this[ 'refreshToken' ] );
214 function X_Net_OAuth2_detectAuthPopup(){
215 var closed, search, pair = X_Pair_get( this );
217 if( X_NET_OAUTH2_authorizationWindow.closed ){
218 pair.oauth2State = 0;
221 this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
223 if( search = X_NET_OAUTH2_detection( X_NET_OAUTH2_authorizationWindow ) ){
224 pair = X_Pair_get( this );
225 pair.code = X_URL_ParamToObj( search.slice( 1 ) )[ 'code' ];
227 X_NET_OAUTH2_authorizationWindow.open( 'about:blank', '_self' ).close();
230 X_Net_OAuth2_authorizationCode( this, pair );
232 pair.oauth2State = 2;
233 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Get code success, then authorization code.' } );
237 X_NET_OAUTH2_authorizationWindow = null;
238 X_NET_OAUTH2_authorizationTimerID = 0;
240 return X_Callback_UN_LISTEN;
244 function X_Net_OAuth2_authorizationCode( oauth2, pair ){
246 'xhr' : pair[ 'tokenEndpoint' ],
247 'postdata' : X_URL_objToParam({
248 'client_id' : pair[ 'clientID' ],
249 'client_secret' : pair[ 'clientSecret' ],
250 'grant_type' : 'authorization_code',
252 'redirect_uri' : pair[ 'redirectURI' ]
256 'Accept' : 'application/json',
257 'Content-Type' : 'application/x-www-form-urlencoded'
260 } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], oauth2, X_Net_OAuth2_responceHandler );
263 function X_Net_OAuth2_responceHandler( e ){
264 var data = e.response,
265 pair = X_Pair_get( this ),
266 isRefresh = pair.oauth2State === 3;
271 case X_EVENT_SUCCESS :
272 if( isRefresh && data.error ){
273 X_OAuth2_removeRefreshToken( this );
274 pair.oauth2State = 0;
275 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Refresh access token error.' } );
276 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
280 pair.oauth2State = 0;
281 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Get new access token error.' } );
282 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
286 X_OAuth2_setAccessToken( this, data[ 'access_token' ] || '' );
287 X_OAuth2_setRefreshToken( this, data[ 'refresh_token' ] || '' );
289 if( data[ 'expires_in' ] ){
290 X_OAuth2_setAccessTokenExpiry( this, X_Timer_now() + data[ 'expires_in' ] * 1000 );
292 if( X_OAuth2_getAccessTokenExpiry( this ) ){
293 X_OAuth2_removeAccessTokenExpiry( this );
296 pair.oauth2State = 4;
297 this[ 'asyncDispatch' ]( { type : X_EVENT_SUCCESS, message : isRefresh ? 'Refresh access token success.' : 'Get new access token success.' } );
302 // other error, not auth
303 pair.oauth2State = 0;
304 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Refresh access token error.' } );
305 X_OAuth2_removeRefreshToken( this );
306 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
308 if( X_OAuth2_getAuthMechanism( this ) === 'param' ){
309 pair.oauth2State = 0;
310 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'network-error' } );
312 pair.oauth2State = 0;
313 X_OAuth2_setAuthMechanism( this, 'param' );
314 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Refresh access token failed. retry header -> param. ' } );
316 X_Net_OAuth2_authorizationCode( this, pair );
322 function X_NET_OAUTH2_onXHR401Error( oauth2, e ){
324 headers = e[ 'headers' ],
325 xhr, bearerParams, headersExposed = false;
327 if( X_OAuth2_getAuthMechanism( oauth2 ) !== 'param' ){
328 xhr = X_NET_currentWrapper[ '_rawObject' ];
329 headersExposed = !X_Net_XHR_createXDR || !!headers; // this is a hack for Firefox and IE
330 bearerParams = headersExposed && ( headers[ 'WWW-Authenticate' ] || headers[ 'www-authenticate' ] );
331 X_Type_isArray( bearerParams ) && ( bearerParams = bearerParams.join( '\n' ) );
334 // http://d.hatena.ne.jp/ritou/20110402/1301679908
335 if ( bearerParams && bearerParams.indexOf( ' error=' ) === -1 ) {
336 pair.oauth2State = 0;
337 oauth2[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
339 if ((( bearerParams && bearerParams.indexOf( 'invalid_token' ) !== -1 ) || !headersExposed) && X_OAuth2_getRefreshToken( oauth2 ) ) {
340 X_OAuth2_removeAccessToken( oauth2 ); // It doesn't work any more.
341 pair.oauth2State = 3;
342 oauth2[ 'refreshToken' ]();
344 //if (!headersExposed && !X_OAuth2_getRefreshToken( oauth2 )) {
345 X_OAuth2_removeAccessToken( oauth2 ); // It doesn't work any more.
346 pair.oauth2State = 0;
347 oauth2[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
351 function X_NET_OAUTH2_updateRequest( oauth2, request ){
352 var token = X_OAuth2_getAccessToken( oauth2 ),
353 mechanism = X_OAuth2_getAuthMechanism( oauth2 ),
354 url = request[ 'url' ],
357 if( token && mechanism === 'param' ){
358 request[ 'url' ] = X_URL_create( url, { 'bearer_token' : encodeURIComponent( token ) } );
361 if( token && ( !mechanism || mechanism === 'header' ) ){
362 headers = request[ 'headers' ] || ( request[ 'headers' ] = {} );
363 headers[ 'Authorization' ] = 'Bearer ' + token;
367 function X_OAuth2_getAccessToken( that ){ return X_OAuth2_updateLocalStorage( '', that, 'accessToken' ); }
368 function X_OAuth2_getRefreshToken( that){ return X_OAuth2_updateLocalStorage( '', that, 'refreshToken' ); }
369 function X_OAuth2_getAccessTokenExpiry( that ){ return parseInt( X_OAuth2_updateLocalStorage( '', that, 'tokenExpiry' ) ) || 0; }
370 function X_OAuth2_getAuthMechanism( that ){
371 // TODO use gadget | flash ...
372 // IE's XDomainRequest doesn't support sending headers, so don't try.
373 return X_Net_XHR_createXDR ? 'param' : X_OAuth2_updateLocalStorage( '', that, 'AuthMechanism' );
375 function X_OAuth2_setAccessToken( that, value ){ X_OAuth2_updateLocalStorage( '+', that, 'accessToken' , value); }
376 function X_OAuth2_setRefreshToken( that, value ){ X_OAuth2_updateLocalStorage( '+', that, 'refreshToken', value); }
377 function X_OAuth2_setAccessTokenExpiry( that, value ){ X_OAuth2_updateLocalStorage( '+', that, 'tokenExpiry', value); }
378 function X_OAuth2_setAuthMechanism( that, value ){ X_OAuth2_updateLocalStorage( '+', that, 'AuthMechanism', value); }
380 function X_OAuth2_removeAccessToken( that ){ X_OAuth2_updateLocalStorage( '-', that, 'accessToken' ); }
381 function X_OAuth2_removeRefreshToken( that ){ X_OAuth2_updateLocalStorage( '-', that, 'refreshToken' ); }
382 function X_OAuth2_removeAccessTokenExpiry( that ){ X_OAuth2_updateLocalStorage( '-', that, 'tokenExpiry' ); }
383 function X_OAuth2_removeAuthMechanism( that ){ X_OAuth2_updateLocalStorage( '-', that, 'AuthMechanism' ); }
385 function X_OAuth2_updateLocalStorage( cmd, that, name, value ){
386 var action = cmd === '+' ? 'setItem' : cmd === '-' ? 'removeItem' : 'getItem',
389 if( window.localStorage ){
390 return window.localStorage[ action ]( X_Pair_get( that )[ 'clientID' ] + name, value );
393 pair = X_Pair_get( that );
396 pair[ name ] = value;
399 if( pair[ name ] !== undefined ) delete pair[ name ];