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 'authorizeWindowWidth' : 500,
33 'authorizeWindowHeight' : 500
34 }).listen( [ X.Event.NEED_AUTH, X.Event.CANCELED, X.Event.SUCCESS, X.Event.ERROR, X.Event.PROGRESS ], updateOAuth2State );
38 xhr : 'https://www.googleapis.com/blogger/v3/users/self/blogs',
41 test : 'gadget' // http -> https:xProtocol なリクエストのため、google ガジェットを proxy に使用
43 .listen( [ X.Event.SUCCESS, X.Event.ERROR, X.Event.PROGRESS ], updateOAuth2State );
45 X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
49 /** @lends OAuth2.prototype */
51 'Constructor' : function( obj ){
54 obj = X_Object_clone( obj );
56 X_Pair_create( this, obj );
58 obj.onAuthError = X_NET_OAUTH2_onXHR401Error;
59 obj.updateRequest = X_NET_OAUTH2_updateRequest;
61 if( _getAccessToken( this ) && ( expires_at = _getAccessTokenExpiry( this ) ) ){
62 if( expires_at < X_Timer_now() + ( obj[ 'refreshMargin' ] || 300000 ) ){ // 寿命が5分を切った
63 this[ 'refreshToken' ]();
66 this[ 'asyncDispatch' ]( X_EVENT_SUCCESS );
69 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
72 // TODO canUse gadgetProxy
73 this[ 'listen' ]( [ X_EVENT_KILL_INSTANCE, X_EVENT_SUCCESS, X_EVENT_ERROR, X_EVENT_NEED_AUTH ], X_NET_OAUTH2_handleEvent );
80 * <dt>1 : <dd>認可用 window がポップアップ中
82 * <dt>3 : <dd>トークンのリフレッシュ中
88 return X_Pair_get( this ).oauth2State || 0;
92 * 認可用 window をポップアップする。ポップアップブロックが働かないように必ず pointer event 内で呼ぶこと。
94 'requestAuth' : function(){
96 // TODO pointer event 内か?チェック
98 if( X_NET_OAUTH2_authorizationWindow ) return;
100 pair = X_Pair_get( this );
102 if( pair.net || pair.oauth2State ) return;
104 url = pair[ 'authorizeEndpoint' ];
105 w = pair[ 'authorizeWindowWidth' ] || 500;
106 h = pair[ 'authorizeWindowHeight' ] || 500;
108 X_NET_OAUTH2_authorizationWindow = window.open(
111 'response_type' : 'code',
112 'client_id' : pair[ 'clientID' ],
113 'redirect_uri' : pair[ 'redirectURI' ],
114 'scope' : ( pair[ 'scopes' ] || []).join(' ')
120 + ',left=' + ( screen.width - w ) / 2
121 + ',top=' + ( screen.height - h ) / 2
122 + ',menubar=no,toolbar=no');
124 X_NET_OAUTH2_authorizationTimerID = X_Timer_add( 333, 0, this, X_Net_OAuth2_detectAuthPopup );
126 pair.oauth2State = 1;
128 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to auth.' } );
132 * 認可プロセスのキャンセル。ポップアップを閉じて認可用の通信は中断する。
134 'cancelAuth' : function(){
135 var pair = X_Pair_get( this );
138 pair.net[ 'kill' ]();
142 if( pair.oauth2State !== 1 ){
146 // http://kojikoji75.hatenablog.com/entry/2013/12/15/223839
147 X_NET_OAUTH2_authorizationWindow && X_NET_OAUTH2_authorizationWindow.open( 'about:blank', '_self' ).close();
148 X_NET_OAUTH2_authorizationWindow = null;
150 X_NET_OAUTH2_authorizationTimerID && X_Timer_remove( X_NET_OAUTH2_authorizationTimerID );
151 X_NET_OAUTH2_authorizationTimerID = 0;
153 this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
159 'refreshToken' : function(){
160 var pair = X_Pair_get( this );
162 if( pair.net ) return;
164 if( pair.refreshTimerID ){
165 X_Timer_remove( pair.refreshTimerID );
166 delete pair.refreshTimerID;
169 pair.oauth2State = 3;
172 'xhr' : pair[ 'tokenEndpoint' ],
173 'postdata' : X_URL_objToParam({
174 'client_id' : pair[ 'clientID' ],
175 'client_secret' : pair[ 'clientSecret' ],
176 'grant_type' : 'refresh_token',
177 'refresh_token' : _getRefreshToken( this )
181 'Accept' : 'application/json',
182 'Content-Type' : 'application/x-www-form-urlencoded'
185 } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], this, X_Net_OAuth2_responceHandler );
187 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to refresh token.' } );
192 function X_NET_OAUTH2_handleEvent( e ){
193 var pair = X_Pair_get( this );
196 case X_EVENT_KILL_INSTANCE :
197 this[ 'cancelAuth' ]();
200 case X_EVENT_NEED_AUTH :
201 pair.refreshTimerID && X_Timer_remove( pair.refreshTimerID );
204 case X_EVENT_SUCCESS :
205 pair.refreshTimerID && X_Timer_remove( pair.refreshTimerID );
206 if( _getRefreshToken( this ) ){
208 pair.refreshTimerID = X_Timer_once( _getAccessTokenExpiry( this ) - X_Timer_now() - pair[ 'refreshMargin' ], this, this[ 'refreshToken' ] );
213 function X_Net_OAuth2_detectAuthPopup(){
214 var closed, search, pair = X_Pair_get( this );
216 if( X_NET_OAUTH2_authorizationWindow.closed ){
217 pair.oauth2State = 0;
220 this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
222 if( search = X_NET_OAUTH2_detection( X_NET_OAUTH2_authorizationWindow ) ){
223 pair = X_Pair_get( this );
224 pair.code = X_URL_ParamToObj( search.slice( 1 ) )[ 'code' ];
226 X_NET_OAUTH2_authorizationWindow.open( 'about:blank', '_self' ).close();
229 X_Net_OAuth2_authorizationCode( this, pair );
231 pair.oauth2State = 2;
232 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Get code success, then authorization code.' } );
236 X_NET_OAUTH2_authorizationWindow = null;
237 X_NET_OAUTH2_authorizationTimerID = 0;
239 return X_Callback_UN_LISTEN;
243 function X_Net_OAuth2_authorizationCode( oauth2, pair ){
245 'xhr' : pair[ 'tokenEndpoint' ],
246 'postdata' : X_URL_objToParam({
247 'client_id' : pair[ 'clientID' ],
248 'client_secret' : pair[ 'clientSecret' ],
249 'grant_type' : 'authorization_code',
251 'redirect_uri' : pair[ 'redirectURI' ]
255 'Accept' : 'application/json',
256 'Content-Type' : 'application/x-www-form-urlencoded'
259 } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], oauth2, X_Net_OAuth2_responceHandler );
262 function X_Net_OAuth2_responceHandler( e ){
263 var data = e.response,
264 pair = X_Pair_get( this ),
265 isRefresh = pair.oauth2State === 3;
270 case X_EVENT_SUCCESS :
271 if( isRefresh && data.error ){
272 _removeRefreshToken( this );
273 pair.oauth2State = 0;
274 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Refresh access token error.' } );
275 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
279 pair.oauth2State = 0;
280 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Get new access token error.' } );
281 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
285 _setAccessToken( this, data[ 'access_token' ] || '' );
286 _setRefreshToken( this, data[ 'refresh_token' ] || '' );
288 if( data[ 'expires_in' ] ){
289 _setAccessTokenExpiry( this, X_Timer_now() + data[ 'expires_in' ] * 1000 );
291 if( _getAccessTokenExpiry( this ) ){
292 _removeAccessTokenExpiry( this );
295 pair.oauth2State = 4;
296 this[ 'asyncDispatch' ]( { type : X_EVENT_SUCCESS, message : isRefresh ? 'Refresh access token success.' : 'Get new access token success.' } );
301 // other error, not auth
302 pair.oauth2State = 0;
303 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Refresh access token error.' } );
304 _removeRefreshToken( this );
305 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
307 if( _getAuthMechanism( this ) === 'param' ){
308 pair.oauth2State = 0;
309 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'network-error' } );
311 pair.oauth2State = 0;
312 _setAuthMechanism( this, 'param' );
313 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Refresh access token failed. retry header -> param. ' } );
315 X_Net_OAuth2_authorizationCode( this, pair );
321 function X_NET_OAUTH2_onXHR401Error( oauth2, e ){
323 headers = e[ 'headers' ],
324 xhr, bearerParams, headersExposed = false;
326 if( _getAuthMechanism( oauth2 ) !== 'param' ){
327 xhr = X_NET_currentWrapper[ '_rawObject' ];
328 headersExposed = !X_Net_XHR_createXDR || !!headers; // this is a hack for Firefox and IE
329 bearerParams = headersExposed && ( headers[ 'WWW-Authenticate' ] || headers[ 'www-authenticate' ] );
330 X_Type_isArray( bearerParams ) && ( bearerParams = bearerParams.join( '\n' ) );
333 // http://d.hatena.ne.jp/ritou/20110402/1301679908
334 if ( bearerParams && bearerParams.indexOf( ' error=' ) === -1 ) {
335 pair.oauth2State = 0;
336 oauth2[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
338 if ((( bearerParams && bearerParams.indexOf( 'invalid_token' ) !== -1 ) || !headersExposed) && _getRefreshToken( oauth2 ) ) {
339 _removeAccessToken( oauth2 ); // It doesn't work any more.
340 pair.oauth2State = 3;
341 oauth2[ 'refreshToken' ]();
343 //if (!headersExposed && !_getRefreshToken( oauth2 )) {
344 _removeAccessToken( oauth2 ); // It doesn't work any more.
345 pair.oauth2State = 0;
346 oauth2[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
350 function X_NET_OAUTH2_updateRequest( oauth2, request ){
351 var token = _getAccessToken( oauth2 ),
352 mechanism = _getAuthMechanism( oauth2 ),
353 url = request[ 'url' ],
356 if( token && mechanism === 'param' ){
357 request[ 'url' ] = X_URL_create( url, { 'bearer_token' : encodeURIComponent( token ) } );
360 if( token && ( !mechanism || mechanism === 'header' ) ){
361 headers = request[ 'headers' ] || ( request[ 'headers' ] = {} );
362 headers[ 'Authorization' ] = 'Bearer ' + token;
366 function _getAccessToken( that ){ return updateLocalStorage( '', that, 'accessToken' ); }
367 function _getRefreshToken( that){ return updateLocalStorage( '', that, 'refreshToken' ); }
368 function _getAccessTokenExpiry( that ){ return parseInt( updateLocalStorage( '', that, 'tokenExpiry' ) ) || 0; }
369 function _getAuthMechanism( that ){
370 // TODO use gadget | flash ...
371 // IE's XDomainRequest doesn't support sending headers, so don't try.
372 return X_Net_XHR_createXDR ? 'param' : updateLocalStorage( '', that, 'AuthMechanism' );
374 function _setAccessToken( that, value ){ updateLocalStorage( '+', that, 'accessToken' , value); }
375 function _setRefreshToken( that, value ){ updateLocalStorage( '+', that, 'refreshToken', value); }
376 function _setAccessTokenExpiry( that, value ){ updateLocalStorage( '+', that, 'tokenExpiry', value); }
377 function _setAuthMechanism( that, value ){ updateLocalStorage( '+', that, 'AuthMechanism', value); }
379 function _removeAccessToken( that ){ updateLocalStorage( '-', that, 'accessToken' ); }
380 function _removeRefreshToken( that ){ updateLocalStorage( '-', that, 'refreshToken' ); }
381 function _removeAccessTokenExpiry( that ){ updateLocalStorage( '-', that, 'tokenExpiry' ); }
382 function _removeAuthMechanism( that ){ updateLocalStorage( '-', that, 'AuthMechanism' ); }
384 function updateLocalStorage( cmd, that, name, value ){
385 var action = cmd === '+' ? 'setItem' : cmd === '-' ? 'removeItem' : 'getItem',
388 if( window.localStorage ){
389 return window.localStorage[ action ]( X_Pair_get( that )[ 'clientID' ] + name, value );
392 pair = X_Pair_get( that );
395 pair[ name ] = value;
398 if( pair[ name ] !== undefined ) delete pair[ name ];