コード例 #1
0
ファイル: service.py プロジェクト: cchienhao/data_collector
    def api_request(self, suid, url, post_args=None, resend=False, **args):
        auth_info = yield get_user_auth(suid, CACHED_PREFIX_KEY)
        if auth_info is None:
            _logger.warn("There is no login user info.")
            raise FlamesError(USER_NOT_FOUND, user_id=suid)
        if args:
            args.update({'access_token': auth_info['access_token']})            
        else :
            args = {'access_token': auth_info['access_token']}
        url += "?" + urllib_parse.urlencode(args)             
        httpc = self.get_auth_http_client()
        try:
            if post_args is not None:
                response = yield httpc.fetch(url, method="POST",
                                             body=urllib_parse.urlencode(post_args))
            else:
                response =  yield httpc.fetch(url)
            result = json2dict(response.body)
        except HTTPError as e:
            if e.code == 401 and resend == False:            
                auth_info = yield self.refresh_token(suid)
                # Update the auth token, and send request again.                
                yield update_user_auth(suid, auth_info, CACHED_PREFIX_KEY);
                result = yield self.api_request(suid, url, post_args, 
                                                resend=True, **args)
                raise Return(result)
            raise e

        _logger.info("Request %s done." % (url))
        raise Return(result)
コード例 #2
0
    def refresh_token(self, suid, extr_headers={}):
        auth_info = yield get_user_auth(suid, self._SERVC_PREFIX)
        if auth_info is None:
            self._logger.warn("There is no login user info.")
            raise FlamesError(USER_NOT_FOUND, user_id=suid)
        url = self._OAUTH_ACCESS_TOKEN_URL
 
        httpc = httpclient.AsyncHTTPClient()
        post_args = {
            "grant_type": "refresh_token",
            "client_id": self._APP_SETTINGS['client_id'],
            "client_secret": self._APP_SETTINGS['consumer_secret'], 
            "refresh_token": auth_info['refresh_token']
        }
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}
        for hdr_name, hdr_value in extr_headers.iteritems():
            headers[hdr_name] = hdr_value    
        try :
            response = yield httpc.fetch(url, method="POST", 
                                         body=urllib_parse.urlencode(post_args),
                                         headers=headers)
            result = json2dict(response.body)
            update_user_auth(suid, result, self._SERVC_PREFIX)
        except HTTPError as e:
            self._logger.error("Request %s %s" % (url, e))
            raise e
        self._logger.info("Request %s done." % (url))
        raise Return(result)
コード例 #3
0
ファイル: service.py プロジェクト: cchienhao/data_collector
    def refresh_token(self, suid):
        auth_info = yield get_user_auth(suid, CACHED_PREFIX_KEY)
        if auth_info is None:
            _logger.warn("There is no login user info.")
            raise FlamesError(USER_NOT_FOUND, user_id=suid)
        url = self._OAUTH_ACCESS_TOKEN_URL
 
        httpc = httpclient.AsyncHTTPClient()
        post_args = {
            "grant_type": "refresh_token",
            "client_id": _app_settings['client_id'],
            "client_secret": _app_settings['consumer_secret'], 
            "refresh_token": auth_info['refresh_token']
        }
        headers = {'Content-Type': 'application/x-www-form-urlencoded'}    
        try :
            response = yield httpc.fetch(url, method="POST", 
                                         body=urllib_parse.urlencode(post_args),
                                         headers=headers)
            result = json2dict(response.body)
            update_user_auth(suid, result, CACHED_PREFIX_KEY)
        except HTTPError as e:
            _logger.error("Request %s %s" % (url, e))
            raise e
        _logger.info("Request %s done." % (url))
        raise Return(result)    
コード例 #4
0
ファイル: handler.py プロジェクト: cchienhao/data_collector
    def auth_login(self):        
        ''' Login service with OAuth2 and binding with given service user id.
        '''        
        error = self.get_argument('error', None)
        if error:
            raise FlamesError(AUTH_FAILED, messages=error)
        
        suid = self.get_argument("suid", None)
        if suid is None: suid = self.get_cookie('suid', None)
        if suid:
            self.set_cookie("suid", suid)
            auth = yield get_user_auth(suid, CACHED_PREFIX_KEY)
            if auth:
                self.redirect(("/v1/user/%s/facebook/auth" % suid))
                return
        else :
            # Do not found in the query string or cookie, create a new one.
            suid = str(uuid.uuid4())
            self.set_cookie("suid", suid)

        code = self.get_argument("code", None)
        if code:
            auth = yield self.get_authenticated_user(code)  
            yield update_user_auth(suid, auth, CACHED_PREFIX_KEY)
            self.redirect(("/v1/user/%s/facebook/auth" % suid))
            return
        
        yield self.authorize_redirect(redirect_uri=_app_settings['redirect_uri'],
                                      client_id=_app_settings['client_id'],
                                      scope=_app_settings['scope'].split())
コード例 #5
0
ファイル: handler.py プロジェクト: cchienhao/data_collector
 def get_auth(self, suid):
     ''' Get the Spotify binding status with service user id.
     '''        
     auth = yield get_user_auth(suid, CACHED_PREFIX_KEY)
     if auth is None:
         raise FlamesError(USER_NOT_FOUND, user_id=suid)
     result = {"suid": suid, "auth": auth}          
     self.write_result(result)
コード例 #6
0
    def api_request(self, suid, url, hdr_auth=True, post_args=None, resend=False, 
                    json_schema=None, auth_info=None, **args):

        if auth_info is None:
            auth_info = yield get_user_auth(suid, self._SERVC_PREFIX)
            if auth_info is None:
                self._logger.warn("There is no login user info.")
                raise FlamesError(USER_NOT_FOUND, user_id=suid)

        hdr = {}
        all_args = {}
        if hdr_auth:
            oauth = "Bearer " + auth_info['access_token']
            hdr = {'Authorization': oauth}
        else :
            all_args = {'access_token': auth_info['access_token']}

        if args:
            all_args.update(args)

        if all_args:
            url += "?" + urllib_parse.urlencode(all_args)
        self._logger.debug(url)
        httpc = self.get_auth_http_client()
        result = {}
        try:
            if post_args is not None:
                response = yield httpc.fetch(url, method="POST",
                                             body=urllib_parse.urlencode(post_args), 
                                             headers=hdr)
            else:
                response =  yield httpc.fetch(url,headers=hdr)
            result = json2dict(response.body, schema=json_schema, validated=True)
            self._logger.info("Request %s done." % (url))
        except HTTPError as e:
            if e.code == 401 and resend == False:            
                auth_info = yield self.refresh_token(suid)
                # Update the auth token, and send request again.                
                yield update_user_auth(suid, auth_info, self._SERVC_PREFIX);
                result = yield self.api_request(suid, url, post_args, 
                                                resend=True, **args)
            result={'code': e.code, "message": e.message}
        finally:
            raise Return(result)
コード例 #7
0
ファイル: trigger.py プロジェクト: cchienhao/data_collector
 def task_isr(self):        
     # Query all the authorized user of fitbit service.
     users = yield get_keys("%s:auth:*" % CACHED_PREFIX_KEY)
     for user in users:
         suid = user.split(":")[-1]
         # TODO: check suid format.
         auth_info = yield get_user_auth(suid, prefix=CACHED_PREFIX_KEY)
         if auth_info is None:
             raise FlamesError(USER_NOT_FOUND, user_id=suid)
         curr_time = get_timestamp()
         lat = auth_info.get('lat', 0)
         expr_time = auth_info.get('expires_in', 3600)
         # Check the auth token status.
         if curr_time - lat >= expr_time:
             # Token need be updated.
             auth_info = yield self.api_clnt.refresh_token(suid)
         for act in self.api_clnt._actions:
             task_info ={'auth': auth_info, 'suid': suid, 'action': act}
             kafka_queue_send(self.producer, dict2json(task_info), partition_key=act)
     raise Return(None)
コード例 #8
0
ファイル: handler.py プロジェクト: cchienhao/data_collector
 def auth_login(self):        
     ''' Login service with OAuth2 and binding with given service user id.
     '''
     suid = self.get_argument("suid", None)
     if suid is None: suid = self.get_cookie('suid', None)
     if suid:
         self.set_cookie("suid", suid)
         auth = yield get_user_auth(suid, CACHED_PREFIX_WITHINGS)
         if auth:
             self.redirect(("/v1/user/%s/withings/auth" % suid))
             return
     else :
         # Do not found in the query string or cookie, create a new one.
         suid = str(uuid.uuid4())
         self.set_cookie("suid", suid)
     auth_token = self.get_argument("oauth_token", None)
     if auth_token:
         auth = yield self.get_authenticated_user()  
         yield update_user_auth(suid, auth, CACHED_PREFIX_WITHINGS)
         self.redirect(("/v1/user/%s/withings/auth" % suid))
         return
     yield self.authorize_redirect(callback_uri=_withings_settings['redirect_uri'])
コード例 #9
0
ファイル: handler.py プロジェクト: cchienhao/data_collector
    def auth_login(self):        
        ''' Login Fitbit service with OAuth2 and binding with given service user id.
        '''
        
        error = self.get_argument('error', None)
        if error:
            raise FlamesError(AUTH_FAILED, messages=error)        
        
        suid = self.get_argument("suid", None)
        if suid is None: suid = self.get_cookie('suid', None)
        if suid:
            self.set_cookie("suid", suid)
            auth = yield get_user_auth(suid, CACHED_PREFIX_KEY)
            if auth:
                self.redirect(("/v1/user/%s/fitbit/auth" % suid))
                return        
        else :
            # Do not found in the query string or cookie, create a new one.
            suid = str(uuid.uuid4())
            self.set_cookie("suid", suid)

        code = self.get_argument("code", None)
        client_id = _app_settings['client_id']
        client_secret = self._APP_SETTINGS['consumer_secret']

        if code:
            auth = client_id+":"+client_secret
            auth = base64.b64encode(auth)
            auth = "Basic " + auth
            extr_hdr = {'Authorization': auth}
            auth = yield self.get_authenticated_user(code, extr_headers=extr_hdr)  
            yield update_user_auth(suid, auth, CACHED_PREFIX_KEY)
            self.redirect(("/v1/user/%s/fitbit/auth" % suid))
            return
        
        yield self.authorize_redirect(redirect_uri=_app_settings['redirect_uri'],
                                      client_id=client_id,
                                      scope=_app_settings['scope'].split())
コード例 #10
0
ファイル: service.py プロジェクト: cchienhao/data_collector
    def api_request(self, user_id, path, post_args=None, **kwargs):
        if path.startswith('http:') or path.startswith('https:'):
            # Raw urls are useful for e.g. search which doesn't follow the
            # usual pattern: http://search.twitter.com/search.json
            url = path
        else:
            url = self._API_URL + path
        # Add the OAuth resource request signature if we have credentials
        access_token = yield get_user_auth(user_id, CACHED_PREFIX_WITHINGS)
        if kwargs:
            kwargs.update({'userid': access_token['userid']})
        if access_token:
            all_args = {}
            all_args.update(kwargs)            
            all_args.update(post_args or {})
            method = "POST" if post_args is not None else "GET"
            oauth = self._oauth_request_parameters(url, access_token, 
                                                   all_args, method=method)
            kwargs.update(oauth)
        if kwargs:            
            url += "?" + urllib_parse.urlencode(kwargs)
        http = self.get_auth_http_client()
        try:
            if post_args is not None:
                response = yield http.fetch(url, method="POST",
                                            body=urllib_parse.urlencode(post_args))
            else:
                response =  yield http.fetch(url)
            result = json2dict(response.body)
        except HTTPError as e:
            if response.error:
                raise AuthError( "Error response %s fetching %s" % 
                                 (response.error, response.request.url))
            else :
                raise e

        _logger.info("Request %s done." % (url))
        raise Return(result)