OSDN Git Service

Version 0.6.153, fix layout @X.UI.
[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                                 obj = X_Object_clone( obj );
52                                 
53                                 X_Pair_create( this, obj );
54                                 
55                                 if( _getAccessToken( this ) ){
56                                         obj.oauth2State = 4;
57                                         this[ 'asyncDispatch' ]( X_EVENT_SUCCESS );
58                                 } else {
59                                         this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
60                                 }
61                                 
62                                 obj.onAuthError   = X_NET_OAUTH2_onXHR401Error;
63                                 obj.updateRequest = X_NET_OAUTH2_updateRequest;
64                                 
65                                 // TODO canUse
66                                 // TODO kill の cancel
67                         },
68
69                         /**
70                          * OAuth2 の状態。
71                          * <dl>
72                          * <dt>0 : <dd>未接続
73                          * <dt>1 : <dd>認可用 window がポップアップ中
74                          * <dt>2 : <dd>コードを認可中
75                          * <dt>3 : <dd>トークンのリフレッシュ中
76                          * <dt>4 : <dd>接続
77                          * </dl>
78                          * @return {number}
79                          */
80                         'state' : function(){
81                                 return X_Pair_get( this ).oauth2State || 0;
82                         },
83                         
84                         /**
85                          * 認可用 window をポップアップする。ポップアップブロックが働かないように必ず pointer event 内で呼ぶこと。
86                          */
87                         'requestAuth' : function(){
88                                 // 二つ以上の popup を作らない
89                                 if( X_NET_OAUTH2_authorizationWindow ) return;
90                                 
91                                 pair = X_Pair_get( this );
92                                 
93                                 if( pair.net || pair.oauth2State ) return;
94                                 
95                                 X_NET_OAUTH2_authorizationWindow = window.open(
96                                         pair[ 'authorizeEndpoint' ] + '?' + X_URL_objToParam(
97                                                 {
98                                                         'response_type' : 'code',
99                                                         'client_id'     : pair[ 'clientID' ],
100                                                         'redirect_uri'  : pair[ 'redirectURI' ],
101                                                         'scope'         : ( pair[ 'scopes' ] || []).join(' ')
102                                                 }
103                                         ), 'oauthauthorize',
104                                         'width=' + pair[ 'authorizeWindowWidth' ]
105                                         + ',height=' + pair[ 'authorizeWindowHeight' ]
106                                         + ',left=' + (screen.width  - pair[ 'authorizeWindowWidth'  ] ) / 2
107                                         + ',top='  + (screen.height - pair[ 'authorizeWindowHeight' ] ) / 2
108                                         + ',menubar=no,toolbar=no');
109                                 
110                                 X_NET_OAUTH2_authorizationTimerID = X_Timer_add( 333, 0, this, X_Net_OAuth2_detectAuthPopup );
111                                 
112                                 pair.oauth2State = 1;
113                                 
114                                 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to auth.' } );
115                         },
116                         
117                         /**
118                          * 認可プロセスのキャンセル。ポップアップを閉じて認可用の通信は中断する。
119                          */
120                         'cancelAuth' : function(){
121                                 var pair = X_Pair_get( this );
122                                 
123                                 if( pair.net ){
124                                         pair.net[ 'kill' ]();
125                                         delete pair.net;
126                                 };
127                                 
128                                 // http://kojikoji75.hatenablog.com/entry/2013/12/15/223839
129                                 X_NET_OAUTH2_authorizationWindow && X_NET_OAUTH2_authorizationWindow.open( 'about:blank', '_self' ).close();
130                                 X_NET_OAUTH2_authorizationWindow  = null;
131                                 
132                                 X_NET_OAUTH2_authorizationTimerID && X_Timer_remove( X_NET_OAUTH2_authorizationTimerID );
133                                 X_NET_OAUTH2_authorizationTimerID = 0;
134                                 
135                                 this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
136                         },
137                         
138                         /**
139                          * アクセストークンのリフレッシュ。
140                          */
141                         'refreshToken' : function(){
142                                 /* TODO 自動リフレッシュ
143                                  *                              var expires_at = this._getAccessTokenExpiry();
144                                 if (expires_at && Date.now() + millis > expires_at)
145                                         this._refreshAccessToken({replay: false});
146                                  */
147                                 
148                                 pair = X_Pair_get( this );
149                                 
150                                 if( pair.net ) return;
151                                 
152                                 pair.oauth2State = 3;
153                                 
154                                 pair.net = X.Net( {
155                                         'xhr'      : pair[ 'tokenEndpoint' ],
156                                         'postdata' : X_URL_objToParam({
157                                                 'client_id'     : pair[ 'clientID' ],
158                                                 'client_secret' : pair[ 'clientSecret' ],
159                                                 'grant_type'    : 'refresh_token',
160                                                 'refresh_token' : _getRefreshToken( this )
161                                         }),
162                                         'dataType' : 'json',
163                                         'headers'  : {
164                                                                         'Accept'       : 'application/json',
165                                                                         'Content-Type' : 'application/x-www-form-urlencoded'
166                                                                 },
167                                         'test'     : 'gadget'
168                                 } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], this, X_Net_OAuth2_responceHandler );
169                                 
170                                 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to refresh token.' } );
171                         }
172                 }
173         );
174
175 function X_Net_OAuth2_detectAuthPopup(){
176         var closed, search, pair = X_Pair_get( this );
177         
178         if( X_NET_OAUTH2_authorizationWindow.closed ){
179                 pair.oauth2State = 0;
180                 closed = true;
181
182                 this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
183         } else
184         if( search = X_NET_OAUTH2_detection( X_NET_OAUTH2_authorizationWindow ) ){
185                 pair      = X_Pair_get( this );
186                 pair.code = X_URL_ParamToObj( search.slice( 1 ) )[ 'code' ];
187
188                 X_NET_OAUTH2_authorizationWindow.open( 'about:blank', '_self' ).close();
189                 closed = true;
190
191                 X_Net_OAuth2_authorizationCode( this, pair );
192                 
193                 pair.oauth2State = 2;
194                 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Get code success, then authorization code.' } );
195         };
196         
197         if( closed ){
198                 X_NET_OAUTH2_authorizationWindow  = null;
199                 X_NET_OAUTH2_authorizationTimerID = 0;
200                 
201                 return X_Callback_UN_LISTEN;    
202         };
203 };
204
205 function X_Net_OAuth2_authorizationCode( oauth2, pair ){        
206         pair.net = X.Net( {
207                 'xhr'      : pair[ 'tokenEndpoint' ],
208                 'postdata' : X_URL_objToParam({
209                         'client_id'     : pair[ 'clientID' ],
210                         'client_secret' : pair[ 'clientSecret' ],
211                         'grant_type'    : 'authorization_code',
212                         'code'          : pair.code,
213                         'redirect_uri'  : pair[ 'redirectURI' ]
214                 }),
215                 'dataType' : 'json',
216                 'headers'  : {
217                         'Accept'       : 'application/json',
218                         'Content-Type' : 'application/x-www-form-urlencoded'
219                 },
220                 'test'     : 'gadget'
221         } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], oauth2, X_Net_OAuth2_responceHandler );
222 };
223
224 function X_Net_OAuth2_responceHandler( e ){
225         var data = e.data,
226                 pair = X_Pair_get( this ),
227                 isRefresh = pair.oauth2State === 3;
228         
229         delete pair.net;
230         
231         switch( e.type ){
232                 case X_EVENT_SUCCESS :
233                         if( isRefresh && data.error ){
234                                 _removeRefreshToken( this );
235                                 pair.oauth2State = 0;
236                                 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Refresh access token error.' + data.error, data : data } );
237                                 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
238                                 return;
239                         } else
240                         if( data.error ){
241                                 pair.oauth2State = 0;
242                                 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Get new access token error.' + data.error, data : data } );
243                                 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
244                                 return;
245                         };
246                         
247                         _setAccessToken( this, data[ 'access_token' ] || '' );
248                         _setRefreshToken( this, data[ 'refresh_token' ] || '' );
249                         
250                         if( data[ 'expires_in' ] ){
251                                 _setAccessTokenExpiry( this, X_Timer_now() + data[ 'expires_in' ] * 1000 );
252                         } else
253                         if( _getAccessTokenExpiry( this ) ){
254                                 _removeAccessTokenExpiry( this );
255                         };
256                         
257                         pair.oauth2State = 4;
258                         this[ 'asyncDispatch' ]( { type : X_EVENT_SUCCESS, message : isRefresh ? 'Refresh access token success.' : 'Get new access token success.' } );
259                         break;
260                         
261                 case X_EVENT_ERROR :
262                         if( isRefresh ){
263                                 // other error, not auth
264                                 pair.oauth2State = 0;
265                                 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'Refresh access token error.' } );
266                                 _removeRefreshToken( this );
267                                 this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
268                         } else
269                         if( _getAuthMechanism( this ) === 'param' ){
270                                 pair.oauth2State = 0;
271                                 this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'network-error' } );
272                         } else {
273                                 pair.oauth2State = 0;
274                                 _setAuthMechanism( this, 'param' );
275                                 this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Refresh access token failed. retry header -> param. ' } );
276                                 // retry
277                                 X_Net_OAuth2_authorizationCode( this, pair );
278                         };
279                         break;
280         };
281 };
282
283 function X_NET_OAUTH2_onXHR401Error( oauth2, e ){
284         var pair = this,
285                 headers = e[ 'headers' ],
286                 xhr, bearerParams, headersExposed = false;
287         
288         if( _getAuthMechanism( oauth2 ) !== 'param' ){
289                 xhr            = X_NET_currentWrapper[ '_rawObject' ];
290                 headersExposed = !X_Net_XHR_createXDR || !!headers; // this is a hack for Firefox and IE
291                 bearerParams   = headersExposed && ( headers[ 'WWW-Authenticate' ] || headers[ 'www-authenticate' ] );
292                 X_Type_isArray( bearerParams ) && ( bearerParams = bearerParams.join( '\n' ) );
293         };
294         
295         // http://d.hatena.ne.jp/ritou/20110402/1301679908
296         if ( bearerParams && bearerParams.indexOf( ' error=' ) === -1 ) {
297                 pair.oauth2State = 0;
298                 oauth2[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
299         } else
300         if ((( bearerParams && bearerParams.indexOf( 'invalid_token' ) !== -1 ) || !headersExposed) && _getRefreshToken( oauth2 ) ) {
301                 _removeAccessToken( oauth2 ); // It doesn't work any more.
302                 pair.oauth2State = 3;
303                 oauth2[ 'refreshToken' ]();
304         } else {
305         //if (!headersExposed && !_getRefreshToken( oauth2 )) {
306                 _removeAccessToken( oauth2 ); // It doesn't work any more.
307                 pair.oauth2State = 0;
308                 oauth2[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
309         };
310 };
311
312 function X_NET_OAUTH2_updateRequest( oauth2, request ){
313         var token     = _getAccessToken( oauth2 ),
314                 mechanism = _getAuthMechanism( oauth2 ),
315                 url       = request[ 'url' ],
316                 headers;
317
318         if( token && mechanism === 'param' ){
319                 request[ 'url' ] = url + ((url.indexOf('?') !== -1) ? '&' : '?') + 'bearer_token=' + encodeURIComponent( token );
320         };
321         
322         if( token && ( !mechanism || mechanism === 'header' ) ){
323                 headers = request[ 'headers' ] || ( request[ 'headers' ] = {} );
324                 headers[ 'Authorization' ] = 'Bearer ' + token;
325         };
326 };
327
328 function _getAccessToken( that ){ return updateLocalStorage( '', that, 'accessToken' ); }
329 function _getRefreshToken( that){ return updateLocalStorage( '', that, 'refreshToken' ); }
330 function _getAccessTokenExpiry( that ){ return updateLocalStorage( '', that, 'tokenExpiry' ); }
331 function _getAuthMechanism( that ){
332                 // TODO use gadget | flash ...
333                 // IE's XDomainRequest doesn't support sending headers, so don't try.
334                 return X_Net_XHR_createXDR ? 'param' : updateLocalStorage( '', that, 'AuthMechanism' );
335         }
336 function _setAccessToken( that, value ){ updateLocalStorage( '+', that, 'accessToken' , value); }
337 function _setRefreshToken( that, value ){ updateLocalStorage( '+', that, 'refreshToken', value); }
338 function _setAccessTokenExpiry( that, value ){ updateLocalStorage( '+', that, 'tokenExpiry', value); }
339 function _setAuthMechanism( that, value ){ updateLocalStorage( '+', that, 'AuthMechanism', value); }
340
341 function _removeAccessToken( that ){ updateLocalStorage( '-', that, 'accessToken' ); }
342 function _removeRefreshToken( that ){ updateLocalStorage( '-', that, 'refreshToken' ); }
343 function _removeAccessTokenExpiry( that ){ updateLocalStorage( '-', that, 'tokenExpiry' ); }
344 function _removeAuthMechanism( that ){ updateLocalStorage( '-', that, 'AuthMechanism' ); }
345         
346 function updateLocalStorage( cmd, that, name, value ){
347         var action = cmd === '+' ? 'setItem' : cmd === '-' ? 'removeItem' : 'getItem',
348                 pair;
349         
350         if( window.localStorage ){
351                 return window.localStorage[ action ]( X_Pair_get( that )[ 'clientID' ] + name, value );
352         };
353         
354         pair = X_Pair_get( that );
355         switch( cmd ){
356                 case '+' :
357                         pair[ name ] = value;
358                         break;
359                 case '-' :
360                         if( pair[ name ] !== undefined ) delete pair[ name ];
361         };
362         return pair[ name ];
363 };
364