def refresh(self, *args, **kwargs): """ `self` is an instance of YahooOAuthClient """ # Let's refresh 5 minutes before the expiration time expires = self.user_social_auth.extra_data['expires'] expires_time = int(expires) - 300 if expires else 0 now = int(time.time()) # print 'comparing n: {0} vs expire: {1}'.format(now, expires) if expires is None or expires < now: #print '------ Refreshing Token ------' r = self.oauth.get_raw_access_token( request_token=self.access_token['oauth_token'], request_token_secret=self.access_token['oauth_token_secret'], params={'oauth_session_handle':self.access_token['oauth_session_handle']}, ) keys = keys_from_response(r.text) access_token = process_token_request(r, parse_utf8_qsl, *keys) for i,k in enumerate(keys): self.access_token[k] = access_token[i] # Save back to UserSocialAuth Model self.user_social_auth.extra_data['access_token'] = self.access_token current_time = int(time.time()) self.user_social_auth.extra_data['expires'] = current_time + int(self.access_token['oauth_expires_in']) # print 'current time: {0}, expiring oauth at {1}'.format(current_time, self.user_social_auth.extra_data['expires']) self.user_social_auth.save() token = (self.access_token['oauth_token'], self.access_token['oauth_token_secret']) self.session = self.oauth.get_session(token) return func(self, *args, **kwargs)
def decorated(*args, **kwargs): resp = oauth_token = None if 'oauth_verifier' in request.args: resp = self.get_raw_access_token( method=method, data={'oauth_verifier': request.args['oauth_verifier']}, **session.pop(self._session_key('request_token'), {})) access_token = process_token_request(resp, parse_utf8_qsl, 'oauth_token', 'oauth_token_secret', 'xoauth_yahoo_guid') return f(*((resp, access_token) + args), **kwargs)
def exchange(self, code): data = dict(grant_type='authorization_code', redirect_uri=self.redirect_url, code=code) response = self.signon.get_raw_access_token('POST', data=data) access_token = None if response.status_code in [200, 201]: try: access_token = service.process_token_request( response, self.__json_access_token, 'access_token')[0] except KeyError as e: log.warn('Could not parse token from response :' + str(e)) return access_token
def _get_request_token(self, method='GET', decoder=parse_utf8_qsl, key_token='oauth_token', key_token_secret='oauth_token_secret', **kwargs): r = super(ChppOAuth1Service, self).get_raw_request_token(method=method, **kwargs) if r.status_code == 401: raise ChppNotAuthorized('NotAuthorized: Invalid consumer credentials') else: r.raise_for_status() request_token, request_token_secret = process_token_request(r, decoder, key_token, key_token_secret) return request_token, request_token_secret
def exchange(self, code): data = dict( grant_type='authorization_code', redirect_uri=self.redirect_url, code=code ) response = self.signon.get_raw_access_token('POST', data=data) access_token = None if response.status_code in [200, 201]: try: access_token = service.process_token_request( response, self.__json_access_token, 'access_token')[0] except KeyError as e: log.warn('Could not parse token from response :' + str(e)) return access_token
def authentication_callback(request, redirect_url=settings.LOGIN_REDIRECT_URL): """Second part of logging in a Twitter user. Finishes authenticating the user and logs them into the site. """ # Get access tokens to store with user req = twitter.get_raw_access_token( request_token=request.session['request_tokens']['token'], request_token_secret=request.session['request_tokens']['secret'], method='POST', params = {'oauth_verifier': request.GET['oauth_verifier']}) access_token, access_token_secret, screen_name = process_token_request( req, parse_utf8_qsl, 'oauth_token', 'oauth_token_secret', 'screen_name') # Check if linking accounts (i.e. user is already logged in) if request.user.is_authenticated: user_id = request.user.id logout(request) user = authenticate( oauth_token=access_token, oauth_token_secret=access_token_secret, screen_name=screen_name, user_id=user_id) else: user = authenticate( oauth_token=access_token, oauth_token_secret=access_token_secret, screen_name=screen_name) auth_login(request, user) if user.userprofile.is_registered(): # Redirect after login for users just logging in return HttpResponseRedirect(settings.LOGIN_REDIRECT_URL) else: # Have users input fill in information for their profile return HttpResponseRedirect(reverse('profiles:registration', args=[user.userprofile.id]))
def _get_access_token(self, request_token, request_token_secret, method='GET', decoder=parse_utf8_qsl, key_token='oauth_token', key_token_secret='oauth_token_secret', **kwargs): r = super(ChppOAuth1Service, self).get_raw_access_token(request_token, request_token_secret, method=method, **kwargs) if r.status_code == 401: raise ChppNotAuthorized('NotAuthorized: Invalid verifier') else: r.raise_for_status() #added since the original impl didn't raise on errors that would break the decoder access_token, access_token_secret = \ process_token_request(r, decoder, key_token, key_token_secret) return access_token, access_token_secret
def refresh(self, *args, **kwargs): """ `self` is an instance of YahooOAuthClient """ # Let's refresh 5 minutes before the expiration time expires = self.user_social_auth.extra_data['expires'] expires_time = int(expires) - 300 if expires else 0 now = int(time.time()) # print('comparing n: {0} vs expire: {1}'.format(now, expires)) if expires is None or expires < now: #print('------ Refreshing Token ------') r = self.oauth.get_raw_access_token( request_token=self.access_token['oauth_token'], request_token_secret=self.access_token['oauth_token_secret'], params={ 'oauth_session_handle': self.access_token['oauth_session_handle'] }, ) keys = keys_from_response(r.text) access_token = process_token_request(r, parse_utf8_qsl, *keys) for i, k in enumerate(keys): self.access_token[k] = access_token[i] # Save back to UserSocialAuth Model self.user_social_auth.extra_data[ 'access_token'] = self.access_token current_time = int(time.time()) self.user_social_auth.extra_data['expires'] = current_time + int( self.access_token['oauth_expires_in']) # print('current time: {0}, expiring oauth at {1}'.format(current_time, self.user_social_auth.extra_data['expires'])) self.user_social_auth.save() token = (self.access_token['oauth_token'], self.access_token['oauth_token_secret']) self.session = self.oauth.get_session(token) return func(self, *args, **kwargs)
def auth_user(self, username, password, req=None): """ Tries to find email and identity of the user from OAuth2 provider. If it doesn't find any of them, returns (None, None) @param username: Isn't used in this function @type username: str @param password: Isn't used in this function @type password: str @param req: request @type req: invenio.webinterface_handler_wsgi.SimulatedModPythonRequest @rtype: str|NoneType, str|NoneType """ from invenio.webinterface_handler import wash_urlargd from invenio.access_control_config import CFG_OAUTH2_CONFIGURATIONS from rauth.service import OAuth2Service from invenio.access_control_config import CFG_OAUTH2_PROVIDERS self.__init_req(req) args = wash_urlargd(req.form, { 'code': (str, ''), 'provider': (str, '') }) req.g['oauth2_provider_name'] = args['provider'] if not req.g['oauth2_provider_name']: # If provider name isn't given req.g['oauth2_msg'] = 21 return None, None # Some providers doesn't construct return uri properly. # Since the callback uri is: # /youraccount/login?login_method=oauth2&provider=something # they may return to: # /youraccount/login?login_method=oauth2&provider=something?code=# # instead of # /youraccount/login?login_method=oauth2&provider=something&code=# if '?' in req.g['oauth2_provider_name']: (req.g['oauth2_provider_name'], args['code']) = \ ( req.g['oauth2_provider_name'][:req.g['oauth2_provider_name'].index('?')], req.g['oauth2_provider_name'][req.g['oauth2_provider_name'].index('?') + 1 + len("code="):] ) if not req.g['oauth2_provider_name'] in CFG_OAUTH2_PROVIDERS: req.g['oauth2_msg'] = 22 return None, None # Load the configurations to construct OAuth2 service config = CFG_OAUTH2_CONFIGURATIONS[req.g['oauth2_provider_name']] req.g['oauth2_debug'] = config.get('debug', 0) provider = OAuth2Service(name=req.g['oauth2_provider_name'], client_id=config['consumer_key'], client_secret=config['consumer_secret'], access_token_url=config['access_token_url'], authorize_url=config['authorize_url']) data = dict( code=args['code'], client_id=config['consumer_key'], client_secret=config['consumer_secret'], grant_type="authorization_code", # Construct redirect uri without having '/' character at the # left most of SITE_SECURE_URL redirect_uri=CFG_SITE_URL + '/youraccount/login?' + urlencode({ 'login_method': 'oauth2', 'provider': req.g['oauth2_provider_name'] })) headers = dict(Accept="application/json") kwargs = dict(data=data, headers=headers) # Get the access token r = provider.get_raw_access_token(method='POST', **kwargs) keys = ['access_token', 'orcid'] try: access_token, orcid = process_token_request(r, json.loads, *keys) token_content = {'access_token': access_token, 'orcid': orcid} except: req.g['oauth2_msg'] = 22 return None, None req.g['oauth2_access_token'] = token_content['access_token'] if req.g['oauth2_debug']: req.g['oauth2_debug_msg'] = str(token_content) + "<br/>" if req.g['oauth2_provider_name'] == 'orcid': req.g['oauth2_orcid'] = token_content['orcid'] email, identity = self._get_user_email_and_id_from_orcid(req) else: # Some providers send the user information and access token together. email, identity = self._get_user_email_and_id(token_content, req) if not identity: profile = provider.request( 'GET', config['request_url'].format( access_token=token_content['access_token'], id=identity)) req.g['oauth2_access_token'] = token_content['access_token'] if req.g['oauth2_debug']: req.g['oauth2_debug_msg'] += str(profile.content) email, identity = self._get_user_email_and_id(profile.content, req) if identity: # If identity is found, add the name of the provider at the # beginning of the identity because different providers may have # different users with same id. identity = "%s:%s" % (req.g['oauth2_provider_name'], identity) else: req.g['oauth2_msg'] = 23 if req.g['oauth2_debug']: req.g['oauth2_msg'] = "<code>%s</code>" % req.g[ 'oauth2_debug_msg'].replace("\n", "<br/>") return None, None return email, identity
def auth_user(self, username, password, req=None): """ Tries to find email and identity of the user from OAuth2 provider. If it doesn't find any of them, returns (None, None) @param username: Isn't used in this function @type username: str @param password: Isn't used in this function @type password: str @param req: request @type req: invenio.legacy.wsgi.SimulatedModPythonRequest @rtype: str|NoneType, str|NoneType """ from invenio.ext.legacy.handler import wash_urlargd from invenio.modules.access.local_config import CFG_OAUTH2_CONFIGURATIONS from rauth.service import OAuth2Service from invenio.modules.access.local_config import CFG_OAUTH2_PROVIDERS self.__init_req(req) args = wash_urlargd(req.form, { 'code': (str, ''), 'provider': (str, '') }) req.g['oauth2_provider_name'] = args['provider'] if not req.g['oauth2_provider_name']: # If provider name isn't given req.g['oauth2_msg'] = 21 return None, None # Some providers doesn't construct return uri properly. # Since the callback uri is: # /youraccount/login?login_method=oauth2&provider=something # they may return to: # /youraccount/login?login_method=oauth2&provider=something?code=# # instead of # /youraccount/login?login_method=oauth2&provider=something&code=# if '?' in req.g['oauth2_provider_name']: (req.g['oauth2_provider_name'], args['code']) = \ ( req.g['oauth2_provider_name'][:req.g['oauth2_provider_name'].index('?')], req.g['oauth2_provider_name'][req.g['oauth2_provider_name'].index('?') + 1 + len("code="):] ) if not req.g['oauth2_provider_name'] in CFG_OAUTH2_PROVIDERS: req.g['oauth2_msg'] = 22 return None, None # Load the configurations to construct OAuth2 service config = CFG_OAUTH2_CONFIGURATIONS[req.g['oauth2_provider_name']] req.g['oauth2_debug'] = config.get('debug', 0) provider = OAuth2Service( name = req.g['oauth2_provider_name'], client_id = config['consumer_key'], client_secret = config['consumer_secret'], access_token_url = config['access_token_url'], authorize_url = config['authorize_url']) data = dict(code = args['code'], client_id = config['consumer_key'], client_secret = config['consumer_secret'], grant_type = "authorization_code", # Construct redirect uri without having '/' character at the # left most of SITE_SECURE_URL redirect_uri = CFG_SITE_SECURE_URL + '/youraccount/login?' + urlencode({'login_method': 'oauth2', 'provider': req.g['oauth2_provider_name']})) headers = dict(Accept = "application/json") kwargs = dict(data = data, headers = headers) # Get the access token r = provider.get_raw_access_token(method='POST', **kwargs) keys = ['access_token', 'orcid'] try: access_token, orcid = process_token_request(r, json.loads, *keys) token_content = {'access_token': access_token, 'orcid': orcid} except: req.g['oauth2_msg'] = 22 return None, None req.g['oauth2_access_token'] = token_content['access_token'] if req.g['oauth2_debug']: req.g['oauth2_debug_msg'] = str(token_content) + "<br/>" if req.g['oauth2_provider_name'] == 'orcid': req.g['oauth2_orcid'] = token_content['orcid'] email, identity = self._get_user_email_and_id_from_orcid(req) else: # Some providers send the user information and access token together. email, identity = self._get_user_email_and_id(token_content, req) if not identity: profile = provider.request('GET', config['request_url'].format( access_token = token_content['access_token'], id=identity)) req.g['oauth2_access_token'] = token_content['access_token'] if req.g['oauth2_debug']: req.g['oauth2_debug_msg'] += str(profile.content) email, identity = self._get_user_email_and_id(profile.content, req) if identity: # If identity is found, add the name of the provider at the # beginning of the identity because different providers may have # different users with same id. identity = "%s:%s" % (req.g['oauth2_provider_name'], identity) else: req.g['oauth2_msg'] = 23 if req.g['oauth2_debug']: req.g['oauth2_msg'] = "<code>%s</code>" % req.g['oauth2_debug_msg'].replace("\n", "<br/>") return None, None return email, identity