OSDN Git Service

Version 0.5.151, fix X.Timer.remove & X.OAuth2 is working.
[pettanr/clientJs.git] / 0.6.x / js / 06_net / 10_XOAuth2.js
index e43d508..d8f3dd1 100644 (file)
@@ -17,9 +17,9 @@ var X_NET_OAUTH2_detection      = new Function( 'w', 'try{return w.location.sear
  * <dl>
  * <dt>0 : <dd>disconnected
  * <dt>1 : <dd>now authentication ...
- * <dt>+ : <dd>authorization_code
- * <dt>2 : <dd>refresh_token
- * <dt>3 : <dd>hasAccessToken
+ * <dt>2 : <dd>authorization_code
+ * <dt>3 : <dd>refresh_token
+ * <dt>4 : <dd>hasAccessToken
  * </dl>
  */
 X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
@@ -29,11 +29,13 @@ X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
                /** @lends OAuth2.prototype */
                {
                        'Constructor' : function( obj ){
+                               obj = X_Object_clone( obj );
                                
-                               X_Pair_create( this, obj = X_Object_clone( obj ) );
+                               X_Pair_create( this, obj );
                                
                                if( _getAccessToken( this ) ){
-                                       obj.oauth2State = 3;
+                                       obj.oauth2State = 4;
+                                       this[ 'asyncDispatch' ]( X_EVENT_SUCCESS );
                                } else {
                                        this[ 'asyncDispatch' ]( X_EVENT_NEED_AUTH );
                                }
@@ -44,7 +46,7 @@ X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
                                // TODO kill の cancel
                        },
 
-                       'authState' : function(){
+                       'state' : function(){
                                return X_Pair_get( this ).oauth2State || 0;
                        },
                        
@@ -62,7 +64,7 @@ X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
                                                {
                                                        'response_type' : 'code',
                                                        'client_id'     : pair[ 'clientID' ],
-                                                       'redirect_uri'  : tpair[ 'redirectURI' ],
+                                                       'redirect_uri'  : pair[ 'redirectURI' ],
                                                        'scope'         : ( pair[ 'scopes' ] || []).join(' ')
                                                }
                                        ), 'oauthauthorize',
@@ -80,14 +82,15 @@ X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
                        },
                        
                        'cancelAuth' : function(){
-                               pair = X_Pair_get( this );
+                               var pair = X_Pair_get( this );
                                
                                if( pair.net ){
                                        pair.net[ 'kill' ]();
                                        delete pair.net;
                                };
                                
-                               X_NET_OAUTH2_authorizationWindow && X_NET_OAUTH2_authorizationWindow.close();
+                               // http://kojikoji75.hatenablog.com/entry/2013/12/15/223839
+                               X_NET_OAUTH2_authorizationWindow && X_NET_OAUTH2_authorizationWindow.open( 'about:blank','_self' ).close();
                                X_NET_OAUTH2_authorizationWindow  = null;
                                
                                X_NET_OAUTH2_authorizationTimerID && X_Timer_remove( X_NET_OAUTH2_authorizationTimerID );
@@ -97,7 +100,7 @@ X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
                        },
                        
                        'refreshToken' : function(){
-                               /*
+                               /* TODO 自動リフレッシュ
                                 *                              var expires_at = this._getAccessTokenExpiry();
                                if (expires_at && Date.now() + millis > expires_at)
                                        this._refreshAccessToken({replay: false});
@@ -107,7 +110,7 @@ X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
                                
                                if( pair.net ) return;
                                
-                               pair.oauth2State = 2;
+                               pair.oauth2State = 3;
                                
                                pair.net = X.Net( {
                                        'xhr'      : pair[ 'tokenEndpoint' ],
@@ -118,10 +121,11 @@ X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
                                                'refresh_token' : _getRefreshToken( this )
                                        }),
                                        'dataType' : 'json',
-                                       'headers' : {
-                                               'Accept'       : 'application/json',
-                                               'Content-Type' : 'application/x-www-form-urlencoded'
-                                       }
+                                       'headers'  : {
+                                                                       'Accept'       : 'application/json',
+                                                                       'Content-Type' : 'application/x-www-form-urlencoded'
+                                                               },
+                                       'test'     : 'gadget'
                                } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], this, X_Net_OAuth2_responceHandler );
                                
                                this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Start to refresh token.' } );
@@ -130,11 +134,12 @@ X[ 'OAuth2' ] = X_EventDispatcher[ 'inherits' ](
        );
 
 function X_Net_OAuth2_detectAuthPopup(){
-       var closed, search, pair;
+       var closed, search, pair = X_Pair_get( this );
        
-       if( window.frames[ 'oauthauthorize' ] !== X_NET_OAUTH2_authorizationWindow || X_NET_OAUTH2_authorizationWindow.closed ){
+       if( X_NET_OAUTH2_authorizationWindow.closed ){
                pair.oauth2State = 0;
                closed = true;
+
                this[ 'asyncDispatch' ]( X_EVENT_CANCELED );
        } else
        if( search = X_NET_OAUTH2_detection( X_NET_OAUTH2_authorizationWindow ) ){
@@ -146,6 +151,7 @@ function X_Net_OAuth2_detectAuthPopup(){
 
                X_Net_OAuth2_authorizationCode( this, pair );
                
+               pair.oauth2State = 2;
                this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Get code success, then authorization code.' } );
        };
        
@@ -168,17 +174,18 @@ function X_Net_OAuth2_authorizationCode( oauth2, pair ){
                        'redirect_uri'  : pair[ 'redirectURI' ]
                }),
                'dataType' : 'json',
-               'headers' : {
+               'headers'  : {
                        'Accept'       : 'application/json',
                        'Content-Type' : 'application/x-www-form-urlencoded'
-               }
+               },
+               'test'     : 'gadget'
        } ).listenOnce( [ X_EVENT_SUCCESS, X_EVENT_ERROR ], oauth2, X_Net_OAuth2_responceHandler );
 };
 
 function X_Net_OAuth2_responceHandler( e ){
        var data = e.data,
                pair = X_Pair_get( this ),
-               isRefresh = pair.oauth2State === 2;
+               isRefresh = pair.oauth2State === 3;
        
        delete pair.net;
        
@@ -208,7 +215,7 @@ function X_Net_OAuth2_responceHandler( e ){
                                _removeAccessTokenExpiry( this );
                        };
                        
-                       pair.oauth2State = 3;
+                       pair.oauth2State = 4;
                        this[ 'asyncDispatch' ]( { type : X_EVENT_SUCCESS, message : isRefresh ? 'Refresh access token success.' : 'Get new access token success.' } );
                        break;
                        
@@ -225,7 +232,7 @@ function X_Net_OAuth2_responceHandler( e ){
                                this[ 'asyncDispatch' ]( { type : X_EVENT_ERROR, message : 'network-error' } );
                        } else {
                                pair.oauth2State = 0;
-                               _setAuthMechanism( 'param' );
+                               _setAuthMechanism( this, 'param' );
                                this[ 'asyncDispatch' ]( { type : X_EVENT_PROGRESS, message : 'Refresh access token failed. retry header -> param. ' } );
                                // retry
                                X_Net_OAuth2_authorizationCode( this, pair );
@@ -241,7 +248,7 @@ function X_NET_OAUTH2_onXHR401Error( oauth2 ){
        if( _getAuthMechanism( oauth2 ) !== 'param' ){
                xhr            = X_NET_currentWrapper[ '_rawObject' ];
                bearerParams   = xhr.getResponseHeader( 'WWW-Authenticate' );
-               headersExposed = !X_Net_XHR_X_DOMAIN || !!xhr.getAllResponseHeaders(); // this is a hack for Firefox and IE
+               headersExposed = !X_Net_XHR_createXDR || !!xhr.getAllResponseHeaders(); // this is a hack for Firefox and IE
        };
        
        // http://d.hatena.ne.jp/ritou/20110402/1301679908
@@ -251,7 +258,7 @@ function X_NET_OAUTH2_onXHR401Error( oauth2 ){
        } else
        if ((( bearerParams && bearerParams.indexOf( ' error="invalid_token"' ) !== -1 ) || !headersExposed) && _getRefreshToken( oauth2 ) ) {
                _removeAccessToken( oauth2 ); // It doesn't work any more.
-               pair.oauth2State = 2;
+               pair.oauth2State = 3;
                oauth2[ 'refreshToken' ]();
        } else
        if (!headersExposed && !_getRefreshToken( oauth2 )) {
@@ -266,12 +273,12 @@ function X_NET_OAUTH2_updateRequest( oauth2, request ){
                url       = request[ 'url' ],
                headers;
 
-       if( token && mechanism === 'param'){
+       if( token && mechanism === 'param' ){
                request[ 'url' ] = url + ((url.indexOf('?') !== -1) ? '&' : '?') + 'bearer_token=' + encodeURIComponent( token );
        };
        
        if( token && ( !mechanism || mechanism === 'header' ) ){
-               request[ 'headers' ] || ( headers = request[ 'headers' ] = {} );
+               headers = request[ 'headers' ] || ( request[ 'headers' ] = {} );
                headers[ 'Authorization' ] = 'Bearer ' + token;
        };
 };
@@ -280,8 +287,9 @@ function _getAccessToken( that ){ return updateLocalStorage( '', that, 'accessTo
 function _getRefreshToken( that){ return updateLocalStorage( '', that, 'refreshToken' ); }
 function _getAccessTokenExpiry( that ){ return updateLocalStorage( '', that, 'tokenExpiry' ); }
 function _getAuthMechanism( that ){
+               // TODO use gadget | flash ...
                // IE's XDomainRequest doesn't support sending headers, so don't try.
-               return X_Net_XHR_X_DOMAIN ? 'param' : updateLocalStorage( '', that, 'AuthMechanism' );
+               return X_Net_XHR_createXDR ? 'param' : updateLocalStorage( '', that, 'AuthMechanism' );
        }
 function _setAccessToken( that, value ){ updateLocalStorage( '+', that, 'accessToken' , value); }
 function _setRefreshToken( that, value ){ updateLocalStorage( '+', that, 'refreshToken', value); }
@@ -294,7 +302,7 @@ function _removeAccessTokenExpiry( that ){ updateLocalStorage( '-', that, 'token
 function _removeAuthMechanism( that ){ updateLocalStorage( '-', that, 'AuthMechanism' ); }
        
 function updateLocalStorage( cmd, that, name, value ){
-       var action = cmd === '+' ? 'setItem' : '-' ? 'removeItem' : 'getItem',
+       var action = cmd === '+' ? 'setItem' : cmd === '-' ? 'removeItem' : 'getItem',
                pair;
        
        if( window.localStorage ){