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 ){
53 obj = X_Object_clone( obj );
55 X_Pair_create( this, obj );
57 obj.onAuthError = X_NET_OAUTH2_onXHR401Error;
58 obj.updateRequest = X_NET_OAUTH2_updateRequest;
60 if( _getAccessToken( this ) && ( expires_at = _getAccessTokenExpiry( this ) ) ){
61 if( expires_at < X_Timer_now() + ( obj[ 'refreshMargin' ] || 300000 ) ){ // 寿命が5分を切った
62 this[ 'refreshToken' ]();
65 this[ 'asyncDispatch' ]( X_EVENT_SUCCESS );
68 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
71 // TODO canUse gadgetProxy
72 this[ 'listen' ]( [ X_EVENT_KILL_INSTANCE, X_EVENT_SUCCESS, X_EVENT_ERROR, X_EVENT_NEED_AUTH ], X_NET_OAUTH2_handleEvent );
79 * <dt>1 : <dd>認可用 window がポップアップ中
81 * <dt>3 : <dd>トークンのリフレッシュ中
87 return X_Pair_get( this ).oauth2State || 0;
91 * 認可用 window をポップアップする。ポップアップブロックが働かないように必ず pointer event 内で呼ぶこと。
93 'requestAuth' : function(){
95 // TODO pointer event 内か?チェック
97 if( X_NET_OAUTH2_authorizationWindow ) return;
99 pair = X_Pair_get( this );
101 if( pair.net || pair.oauth2State ) return;
103 url = pair[ 'authorizeEndpoint' ];
104 w = pair[ 'authorizeWindowWidth' ] || 500;
105 h = pair[ 'authorizeWindowHeight' ] || 500;
107 X_NET_OAUTH2_authorizationWindow = window.open(
110 'response_type' : 'code',
111 'client_id' : pair[ 'clientID' ],
112 'redirect_uri' : pair[ 'redirectURI' ],
113 'scope' : ( pair[ 'scopes' ] || []).join(' ')
119 + ',left=' + ( screen.width - w ) / 2
120 + ',top=' + ( screen.height - h ) / 2
121 + ',menubar=no,toolbar=no');
123 X_NET_OAUTH2_authorizationTimerID = X_Timer_add( 333, 0, this, X_Net_OAuth2_detectAuthPopup );
125 pair.oauth2State = 1;
127 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to auth.' } );
131 * 認可プロセスのキャンセル。ポップアップを閉じて認可用の通信は中断する。
133 'cancelAuth' : function(){
134 var pair = X_Pair_get( this );
137 pair.net[ 'kill' ]();
141 if( pair.oauth2State !== 1 ){
145 // http://kojikoji75.hatenablog.com/entry/2013/12/15/223839
146 X_NET_OAUTH2_authorizationWindow && X_NET_OAUTH2_authorizationWindow.open( 'about:blank', '_self' ).close();
147 X_NET_OAUTH2_authorizationWindow = null;
149 X_NET_OAUTH2_authorizationTimerID && X_Timer_remove( X_NET_OAUTH2_authorizationTimerID );
150 X_NET_OAUTH2_authorizationTimerID = 0;
152 this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
158 'refreshToken' : function(){
159 var pair = X_Pair_get( this );
161 if( pair.net ) return;
163 if( pair.refreshTimerID ){
164 X_Timer_remove( pair.refreshTimerID );
165 delete pair.refreshTimerID;
168 pair.oauth2State = 3;
171 'xhr' : pair[ 'tokenEndpoint' ],
172 'postdata' : X_URL_objToParam({
173 'client_id' : pair[ 'clientID' ],
174 'client_secret' : pair[ 'clientSecret' ],
175 'grant_type' : 'refresh_token',
176 'refresh_token' : _getRefreshToken( this )
180 'Accept' : 'application/json',
181 'Content-Type' : 'application/x-www-form-urlencoded'
184 } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], this, X_Net_OAuth2_responceHandler );
186 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to refresh token.' } );
191 function X_NET_OAUTH2_handleEvent( e ){
192 var pair = X_Pair_get( this );
195 case X_EVENT_KILL_INSTANCE :
196 this[ 'cancelAuth' ]();
199 case X_EVENT_NEED_AUTH :
200 pair.refreshTimerID && X_Timer_remove( pair.refreshTimerID );
203 case X_EVENT_SUCCESS :
204 pair.refreshTimerID && X_Timer_remove( pair.refreshTimerID );
205 if( _getRefreshToken( this ) ){
207 pair.refreshTimerID = X_Timer_once( _getAccessTokenExpiry( this ) - X_Timer_now() - pair[ 'refreshMargin' ], this, this[ 'refreshToken' ] );
212 function X_Net_OAuth2_detectAuthPopup(){
213 var closed, search, pair = X_Pair_get( this );
215 if( X_NET_OAUTH2_authorizationWindow.closed ){
216 pair.oauth2State = 0;
219 this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
221 if( search = X_NET_OAUTH2_detection( X_NET_OAUTH2_authorizationWindow ) ){
222 pair = X_Pair_get( this );
223 pair.code = X_URL_ParamToObj( search.slice( 1 ) )[ 'code' ];
225 X_NET_OAUTH2_authorizationWindow.open( 'about:blank', '_self' ).close();
228 X_Net_OAuth2_authorizationCode( this, pair );
230 pair.oauth2State = 2;
231 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Get code success, then authorization code.' } );
235 X_NET_OAUTH2_authorizationWindow = null;
236 X_NET_OAUTH2_authorizationTimerID = 0;
238 return X_Callback_UN_LISTEN;
242 function X_Net_OAuth2_authorizationCode( oauth2, pair ){
244 'xhr' : pair[ 'tokenEndpoint' ],
245 'postdata' : X_URL_objToParam({
246 'client_id' : pair[ 'clientID' ],
247 'client_secret' : pair[ 'clientSecret' ],
248 'grant_type' : 'authorization_code',
250 'redirect_uri' : pair[ 'redirectURI' ]
254 'Accept' : 'application/json',
255 'Content-Type' : 'application/x-www-form-urlencoded'
258 } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], oauth2, X_Net_OAuth2_responceHandler );
261 function X_Net_OAuth2_responceHandler( e ){
263 pair = X_Pair_get( this ),
264 isRefresh = pair.oauth2State === 3;
269 case X_EVENT_SUCCESS :
270 if( isRefresh && data.error ){
271 _removeRefreshToken( this );
272 pair.oauth2State = 0;
273 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Refresh access token error.' + data.error, data : data } );
274 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
278 pair.oauth2State = 0;
279 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Get new access token error.' + data.error, data : data } );
280 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
284 _setAccessToken( this, data[ 'access_token' ] || '' );
285 _setRefreshToken( this, data[ 'refresh_token' ] || '' );
287 if( data[ 'expires_in' ] ){
288 _setAccessTokenExpiry( this, X_Timer_now() + data[ 'expires_in' ] * 1000 );
290 if( _getAccessTokenExpiry( this ) ){
291 _removeAccessTokenExpiry( this );
294 pair.oauth2State = 4;
295 this[ 'asyncDispatch' ]( { type : X_EVENT_SUCCESS, message : isRefresh ? 'Refresh access token success.' : 'Get new access token success.' } );
300 // other error, not auth
301 pair.oauth2State = 0;
302 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Refresh access token error.' } );
303 _removeRefreshToken( this );
304 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
306 if( _getAuthMechanism( this ) === 'param' ){
307 pair.oauth2State = 0;
308 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'network-error' } );
310 pair.oauth2State = 0;
311 _setAuthMechanism( this, 'param' );
312 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Refresh access token failed. retry header -> param. ' } );
314 X_Net_OAuth2_authorizationCode( this, pair );
320 function X_NET_OAUTH2_onXHR401Error( oauth2, e ){
322 headers = e[ 'headers' ],
323 xhr, bearerParams, headersExposed = false;
325 if( _getAuthMechanism( oauth2 ) !== 'param' ){
326 xhr = X_NET_currentWrapper[ '_rawObject' ];
327 headersExposed = !X_Net_XHR_createXDR || !!headers; // this is a hack for Firefox and IE
328 bearerParams = headersExposed && ( headers[ 'WWW-Authenticate' ] || headers[ 'www-authenticate' ] );
329 X_Type_isArray( bearerParams ) && ( bearerParams = bearerParams.join( '\n' ) );
332 // http://d.hatena.ne.jp/ritou/20110402/1301679908
333 if ( bearerParams && bearerParams.indexOf( ' error=' ) === -1 ) {
334 pair.oauth2State = 0;
335 oauth2[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
337 if ((( bearerParams && bearerParams.indexOf( 'invalid_token' ) !== -1 ) || !headersExposed) && _getRefreshToken( oauth2 ) ) {
338 _removeAccessToken( oauth2 ); // It doesn't work any more.
339 pair.oauth2State = 3;
340 oauth2[ 'refreshToken' ]();
342 //if (!headersExposed && !_getRefreshToken( oauth2 )) {
343 _removeAccessToken( oauth2 ); // It doesn't work any more.
344 pair.oauth2State = 0;
345 oauth2[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
349 function X_NET_OAUTH2_updateRequest( oauth2, request ){
350 var token = _getAccessToken( oauth2 ),
351 mechanism = _getAuthMechanism( oauth2 ),
352 url = request[ 'url' ],
355 if( token && mechanism === 'param' ){
356 request[ 'url' ] = X_URL_create( url, { 'bearer_token' : encodeURIComponent( token ) } );
359 if( token && ( !mechanism || mechanism === 'header' ) ){
360 headers = request[ 'headers' ] || ( request[ 'headers' ] = {} );
361 headers[ 'Authorization' ] = 'Bearer ' + token;
365 function _getAccessToken( that ){ return updateLocalStorage( '', that, 'accessToken' ); }
366 function _getRefreshToken( that){ return updateLocalStorage( '', that, 'refreshToken' ); }
367 function _getAccessTokenExpiry( that ){ return parseInt( updateLocalStorage( '', that, 'tokenExpiry' ) ) || 0; }
368 function _getAuthMechanism( that ){
369 // TODO use gadget | flash ...
370 // IE's XDomainRequest doesn't support sending headers, so don't try.
371 return X_Net_XHR_createXDR ? 'param' : updateLocalStorage( '', that, 'AuthMechanism' );
373 function _setAccessToken( that, value ){ updateLocalStorage( '+', that, 'accessToken' , value); }
374 function _setRefreshToken( that, value ){ updateLocalStorage( '+', that, 'refreshToken', value); }
375 function _setAccessTokenExpiry( that, value ){ updateLocalStorage( '+', that, 'tokenExpiry', value); }
376 function _setAuthMechanism( that, value ){ updateLocalStorage( '+', that, 'AuthMechanism', value); }
378 function _removeAccessToken( that ){ updateLocalStorage( '-', that, 'accessToken' ); }
379 function _removeRefreshToken( that ){ updateLocalStorage( '-', that, 'refreshToken' ); }
380 function _removeAccessTokenExpiry( that ){ updateLocalStorage( '-', that, 'tokenExpiry' ); }
381 function _removeAuthMechanism( that ){ updateLocalStorage( '-', that, 'AuthMechanism' ); }
383 function updateLocalStorage( cmd, that, name, value ){
384 var action = cmd === '+' ? 'setItem' : cmd === '-' ? 'removeItem' : 'getItem',
387 if( window.localStorage ){
388 return window.localStorage[ action ]( X_Pair_get( that )[ 'clientID' ] + name, value );
391 pair = X_Pair_get( that );
394 pair[ name ] = value;
397 if( pair[ name ] !== undefined ) delete pair[ name ];