OSDN Git Service

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