OSDN Git Service

ef18be5608c59012f7901141ea440c6f39db26a5
[pettanr/clientJs.git] / 0.6.x / js / 06_net / 10_XOAuth2.js
1
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;
5
6 /**
7  * イベント
8  * <dl>
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 に切替
14  * </dl>
15  * 
16  * original :
17  *  oauth2.js , <opendata@oucs.ox.ac.uk>
18  * 
19  * @alias X.OAuth2
20  * @class OAuth2 サービスを定義し接続状況をモニタする。適宜にトークンのアップデートなどを行う
21  * @constructs OAuth2
22  * @extends {EventDispatcher}
23  * @example // OAuth2 サービスの定義
24 oauth2 = X.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 );
34
35 // XHR 時に oauth2 を渡す
36 X.Net( {
37         xhr      : 'https://www.googleapis.com/blogger/v3/users/self/blogs',
38         dataType : 'json',
39         auth     : oauth2,
40         test     : 'gadget' // http -> https:xProtocol なリクエストのため、google ガジェットを proxy に使用
41         } )
42         .listen( [ X.Event.SUCCESS, X.Event.ERROR, X.Event.PROGRESS ], updateOAuth2State );
43  */
44 X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
45                 'X.OAuth2',
46                 X_Class.NONE,
47                 
48                 /** @lends OAuth2.prototype */
49                 {
50                         'Constructor' : function( obj ){
51                                 var expires_at;
52                                 
53                                 obj = X_Object_clone( obj );
54                                 
55                                 X_Pair_create( this, obj );
56                                 
57                                 obj.onAuthError   = X_NET_OAUTH2_onXHR401Error;
58                                 obj.updateRequest = X_NET_OAUTH2_updateRequest;                         
59                                 
60                                 if( _getAccessToken( this ) && ( expires_at = _getAccessTokenExpiry( this ) ) ){
61                                         if( expires_at < X_Timer_now() + ( obj[ 'refreshMargin' ] || 300000 ) ){ // 寿命が5分を切った
62                                                 this[ 'refreshToken' ]();
63                                         } else {
64                                                 obj.oauth2State = 4;
65                                                 this[ 'asyncDispatch' ]( X_EVENT_SUCCESS );                                             
66                                         };
67                                 } else {
68                                         this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
69                                 };
70                                 
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 );
73                         },
74
75                         /**
76                          * OAuth2 の状態。
77                          * <dl>
78                          * <dt>0 : <dd>未接続
79                          * <dt>1 : <dd>認可用 window がポップアップ中
80                          * <dt>2 : <dd>コードを認可中
81                          * <dt>3 : <dd>トークンのリフレッシュ中
82                          * <dt>4 : <dd>接続
83                          * </dl>
84                          * @return {number}
85                          */
86                         'state' : function(){
87                                 return X_Pair_get( this ).oauth2State || 0;
88                         },
89                         
90                         /**
91                          * 認可用 window をポップアップする。ポップアップブロックが働かないように必ず pointer event 内で呼ぶこと。
92                          */
93                         'requestAuth' : function(){
94                                 var url, w, h;
95                                 // TODO pointer event 内か?チェック
96                                 // 二つ以上の popup を作らない
97                                 if( X_NET_OAUTH2_authorizationWindow ) return;
98                                 
99                                 pair = X_Pair_get( this );
100                                 
101                                 if( pair.net || pair.oauth2State ) return;
102                                 
103                                 url = pair[ 'authorizeEndpoint' ];
104                                 w   = pair[ 'authorizeWindowWidth' ]  || 500;
105                                 h   = pair[ 'authorizeWindowHeight' ] || 500;
106                                 
107                                 X_NET_OAUTH2_authorizationWindow = window.open(
108                                         X_URL_create( url,
109                                                 {
110                                                         'response_type' : 'code',
111                                                         'client_id'     : pair[ 'clientID' ],
112                                                         'redirect_uri'  : pair[ 'redirectURI' ],
113                                                         'scope'         : ( pair[ 'scopes' ] || []).join(' ')
114                                                 }
115                                         ),
116                                         'oauthauthorize',
117                                         'width=' + w
118                                         + ',height=' + h
119                                         + ',left=' + ( screen.width  - w ) / 2
120                                         + ',top='  + ( screen.height - h ) / 2
121                                         + ',menubar=no,toolbar=no');
122                                 
123                                 X_NET_OAUTH2_authorizationTimerID = X_Timer_add( 333, 0, this, X_Net_OAuth2_detectAuthPopup );
124                                 
125                                 pair.oauth2State = 1;
126                                 
127                                 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to auth.' } );
128                         },
129                         
130                         /**
131                          * 認可プロセスのキャンセル。ポップアップを閉じて認可用の通信は中断する。
132                          */
133                         'cancelAuth' : function(){
134                                 var pair = X_Pair_get( this );
135                                 
136                                 if( pair.net ){
137                                         pair.net[ 'kill' ]();
138                                         delete pair.net;
139                                 };
140                                 
141                                 if( pair.oauth2State !== 1 ){
142                                         return;
143                                 };
144                                 
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;
148                                 
149                                 X_NET_OAUTH2_authorizationTimerID && X_Timer_remove( X_NET_OAUTH2_authorizationTimerID );
150                                 X_NET_OAUTH2_authorizationTimerID = 0;
151                                 
152                                 this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
153                         },
154                         
155                         /**
156                          * アクセストークンのリフレッシュ。
157                          */
158                         'refreshToken' : function(){
159                                 var pair = X_Pair_get( this );
160                                 
161                                 if( pair.net ) return;
162                                 
163                                 if( pair.refreshTimerID ){
164                                         X_Timer_remove( pair.refreshTimerID );
165                                         delete pair.refreshTimerID;
166                                 };
167                                 
168                                 pair.oauth2State = 3;
169                                 
170                                 pair.net = X.Net( {
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 )
177                                         }),
178                                         'dataType' : 'json',
179                                         'headers'  : {
180                                                                         'Accept'       : 'application/json',
181                                                                         'Content-Type' : 'application/x-www-form-urlencoded'
182                                                                 },
183                                         'test'     : 'gadget'
184                                 } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], this, X_Net_OAuth2_responceHandler );
185                                 
186                                 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to refresh token.' } );
187                         }
188                 }
189         );
190
191 function X_NET_OAUTH2_handleEvent( e ){
192         var pair = X_Pair_get( this );
193         
194         switch( e.type ){
195                 case X_EVENT_KILL_INSTANCE :
196                         this[ 'cancelAuth' ]();
197                 
198                 case X_EVENT_ERROR :
199                 case X_EVENT_NEED_AUTH :
200                         pair.refreshTimerID && X_Timer_remove( pair.refreshTimerID );
201                         break;
202                         
203                 case X_EVENT_SUCCESS :
204                         pair.refreshTimerID && X_Timer_remove( pair.refreshTimerID );
205                         if( _getRefreshToken( this ) ){
206                                 // 自動リフレッシュ
207                                 pair.refreshTimerID = X_Timer_once( _getAccessTokenExpiry( this ) - X_Timer_now() - pair[ 'refreshMargin' ], this, this[ 'refreshToken' ] );
208                         };
209         };
210 };
211
212 function X_Net_OAuth2_detectAuthPopup(){
213         var closed, search, pair = X_Pair_get( this );
214         
215         if( X_NET_OAUTH2_authorizationWindow.closed ){
216                 pair.oauth2State = 0;
217                 closed = true;
218
219                 this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
220         } else
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' ];
224
225                 X_NET_OAUTH2_authorizationWindow.open( 'about:blank', '_self' ).close();
226                 closed = true;
227
228                 X_Net_OAuth2_authorizationCode( this, pair );
229                 
230                 pair.oauth2State = 2;
231                 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Get code success, then authorization code.' } );
232         };
233         
234         if( closed ){
235                 X_NET_OAUTH2_authorizationWindow  = null;
236                 X_NET_OAUTH2_authorizationTimerID = 0;
237                 
238                 return X_Callback_UN_LISTEN;    
239         };
240 };
241
242 function X_Net_OAuth2_authorizationCode( oauth2, pair ){        
243         pair.net = X.Net( {
244                 'xhr'      : pair[ 'tokenEndpoint' ],
245                 'postdata' : X_URL_objToParam({
246                         'client_id'     : pair[ 'clientID' ],
247                         'client_secret' : pair[ 'clientSecret' ],
248                         'grant_type'    : 'authorization_code',
249                         'code'          : pair.code,
250                         'redirect_uri'  : pair[ 'redirectURI' ]
251                 }),
252                 'dataType' : 'json',
253                 'headers'  : {
254                         'Accept'       : 'application/json',
255                         'Content-Type' : 'application/x-www-form-urlencoded'
256                 },
257                 'test'     : 'gadget'
258         } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], oauth2, X_Net_OAuth2_responceHandler );
259 };
260
261 function X_Net_OAuth2_responceHandler( e ){
262         var data = e.data,
263                 pair = X_Pair_get( this ),
264                 isRefresh = pair.oauth2State === 3;
265         
266         delete pair.net;
267         
268         switch( e.type ){
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 );
275                                 return;
276                         } else
277                         if( data.error ){
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 );
281                                 return;
282                         };
283                         
284                         _setAccessToken( this, data[ 'access_token' ] || '' );
285                         _setRefreshToken( this, data[ 'refresh_token' ] || '' );
286                         
287                         if( data[ 'expires_in' ] ){
288                                 _setAccessTokenExpiry( this, X_Timer_now() + data[ 'expires_in' ] * 1000 );
289                         } else
290                         if( _getAccessTokenExpiry( this ) ){
291                                 _removeAccessTokenExpiry( this );
292                         };
293                         
294                         pair.oauth2State = 4;
295                         this[ 'asyncDispatch' ]( { type : X_EVENT_SUCCESS, message : isRefresh ? 'Refresh access token success.' : 'Get new access token success.' } );
296                         break;
297                         
298                 case X_EVENT_ERROR :
299                         if( isRefresh ){
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 );
305                         } else
306                         if( _getAuthMechanism( this ) === 'param' ){
307                                 pair.oauth2State = 0;
308                                 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'network-error' } );
309                         } else {
310                                 pair.oauth2State = 0;
311                                 _setAuthMechanism( this, 'param' );
312                                 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Refresh access token failed. retry header -> param. ' } );
313                                 // retry
314                                 X_Net_OAuth2_authorizationCode( this, pair );
315                         };
316                         break;
317         };
318 };
319
320 function X_NET_OAUTH2_onXHR401Error( oauth2, e ){
321         var pair = this,
322                 headers = e[ 'headers' ],
323                 xhr, bearerParams, headersExposed = false;
324         
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' ) );
330         };
331         
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 );
336         } else
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' ]();
341         } else {
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 );
346         };
347 };
348
349 function X_NET_OAUTH2_updateRequest( oauth2, request ){
350         var token     = _getAccessToken( oauth2 ),
351                 mechanism = _getAuthMechanism( oauth2 ),
352                 url       = request[ 'url' ],
353                 headers;
354
355         if( token && mechanism === 'param' ){
356                 request[ 'url' ] = X_URL_create( url, { 'bearer_token' : encodeURIComponent( token ) } );
357         };
358         
359         if( token && ( !mechanism || mechanism === 'header' ) ){
360                 headers = request[ 'headers' ] || ( request[ 'headers' ] = {} );
361                 headers[ 'Authorization' ] = 'Bearer ' + token;
362         };
363 };
364
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' );
372         }
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); }
377
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' ); }
382         
383 function updateLocalStorage( cmd, that, name, value ){
384         var action = cmd === '+' ? 'setItem' : cmd === '-' ? 'removeItem' : 'getItem',
385                 pair;
386         
387         if( window.localStorage ){
388                 return window.localStorage[ action ]( X_Pair_get( that )[ 'clientID' ] + name, value );
389         };
390         
391         pair = X_Pair_get( that );
392         switch( cmd ){
393                 case '+' :
394                         pair[ name ] = value;
395                         break;
396                 case '-' :
397                         if( pair[ name ] !== undefined ) delete pair[ name ];
398         };
399         return pair[ name ];
400 };
401