def renren_process(request): """Process the renren redirect""" config = request.registry.settings code = request.GET.get('code') if not code: reason = request.GET.get('error', 'No reason provided.') return AuthenticationDenied(reason) access_url = flat_url('https://graph.renren.com/oauth/token', client_id=config['velruse.renren.app_id'], client_secret=config['velruse.renren.app_secret'], grant_type='authorization_code', redirect_uri=request.route_url('renren_process'), code=code) r = requests.get(access_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) data = loads(r.content) access_token = data['access_token'] profile = { 'accounts': [{ 'domain': 'renren.com', 'userid': data['user']['id'] }], 'displayName': data['user']['name'], 'preferredUsername': data['user']['name'], } cred = {'oauthAccessToken': access_token} return RenrenAuthenticationComplete(profile=profile, credentials=cred)
def twitter_process(request): """Process the Twitter redirect""" if 'denied' in request.GET: return AuthenticationDenied("User denied authentication") settings = request.registry.settings request_token = oauth.Token.from_string(request.session['token']) verifier = request.GET.get('oauth_verifier') if not verifier: raise ThirdPartyFailure("Oauth verifier not returned") request_token.set_verifier(verifier) # Create the consumer and client, make the request consumer = oauth.Consumer(settings['velruse.twitter.consumer_key'], settings['velruse.twitter.consumer_secret']) client = oauth.Client(consumer, request_token) resp, content = client.request(ACCESS_URL, "POST") if resp['status'] != '200': raise ThirdPartyFailure("Status %s: %s" % (resp['status'], content)) access_token = dict(parse_qs(content)) # Setup the normalized contact info profile = {} profile['accounts'] = [{ 'domain': 'twitter.com', 'userid': access_token['user_id'][0] }] profile['displayName'] = access_token['screen_name'][0] cred = { 'oauthAccessToken': access_token['oauth_token'][0], 'oauthAccessTokenSecret': access_token['oauth_token_secret'][0] } return TwitterAuthenticationComplete(profile=profile, credentials=cred)
def facebook_process(request): """Process the facebook redirect""" if request.GET.get('state') != request.session.get('state'): raise CSRFError( "CSRF Validation check failed. Request state %s is " "not the same as session state %s" % (request.GET.get('state'), request.session.get('state'))) config = request.registry.settings code = request.GET.get('code') if not code: reason = request.GET.get('error_reason', 'No reason provided.') return AuthenticationDenied(reason) # Now retrieve the access token with the code access_url = flat_url('https://graph.facebook.com/oauth/access_token', client_id=config['velruse.facebook.app_id'], client_secret=config['velruse.facebook.app_secret'], redirect_uri=request.route_url('facebook_process'), code=code) r = requests.get(access_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) access_token = parse_qs(r.content)['access_token'][0] # Retrieve profile data graph_url = flat_url('https://graph.facebook.com/me', access_token=access_token) r = requests.get(graph_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) fb_profile = loads(r.content) profile = extract_fb_data(fb_profile) cred = {'oauthAccessToken': access_token} return FacebookAuthenticationComplete(profile=profile, credentials=cred)
def taobao_process(request): """Process the taobao redirect""" config = request.registry.settings code = request.GET.get('code') if not code: reason = request.GET.get('error', 'No reason provided.') return AuthenticationDenied(reason) # Now retrieve the access token with the code r = requests.post( 'https://oauth.taobao.com/token', dict(grant_type='authorization_code', client_id=config['velruse.taobao.app_id'], client_secret=config['velruse.taobao.app_secret'], redirect_uri=request.route_url('taobao_process'), code=code)) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) data = loads(r.content) access_token = data['access_token'] # Retrieve profile data params = { 'method': 'taobao.user.get', 'timestamp': time.strftime('%Y-%m-%d %H:%M:%S', time.localtime()), 'format': 'json', 'app_key': config['velruse.taobao.app_id'], 'v': '2.0', 'sign_method': 'md5', 'fields': 'user_id,nick', 'session': access_token } src = config['velruse.taobao.app_secret']\ + ''.join(["%s%s" % (k, v) for k, v in sorted(params.items())])\ + config['velruse.taobao.app_secret'] params['sign'] = md5(src).hexdigest().upper() get_user_info_url = flat_url('http://gw.api.taobao.com/router/rest', **params) r = requests.get(get_user_info_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) data = loads(r.content) username = data['user_get_response']['user']['nick'] userid = data['user_get_response']['user']['user_id'] profile = { 'accounts': [{ 'domain': 'taobao.com', 'userid': userid }], 'displayName': username, 'preferredUsername': username, } cred = {'oauthAccessToken': access_token} return TaobaoAuthenticationComplete(profile=profile, credentials=cred)
def linkedin_process(request): """Process the LinkedIn redirect""" if 'denied' in request.GET: return AuthenticationDenied("User denied authentication") config = request.registry.settings request_token = oauth.Token.from_string(request.session['token']) verifier = request.GET.get('oauth_verifier') if not verifier: raise ThirdPartyFailure("Oauth verifier not returned") request_token.set_verifier(verifier) # Create the consumer and client, make the request consumer = oauth.Consumer(config['velruse.linkedin.consumer_key'], config['velruse.linkedin.consumer_secret']) client = oauth.Client(consumer, request_token) resp, content = client.request(ACCESS_URL, "POST") if resp['status'] != '200': raise ThirdPartyFailure("Status %s: %s" % (resp['status'], content)) access_token = dict(parse_qs(content)) cred = {'oauthAccessToken': access_token['oauth_token'][0], 'oauthAccessTokenSecret': access_token['oauth_token_secret'][0]} # Make a request with the data for more user info token = oauth.Token(key=cred['oauthAccessToken'], secret=cred['oauthAccessTokenSecret']) client = oauth.Client(consumer, token) profile_url = 'http://api.linkedin.com/v1/people/~' profile_url += ':(first-name,last-name,id,date-of-birth,picture-url)' profile_url += '?format=json' resp, content = client.request(profile_url) if resp['status'] != '200': raise ThirdPartyFailure("Status %s: %s" % (resp['status'], content)) data = loads(content) # Setup the normalized contact info profile = {} profile['displayName'] = data['firstName'] + data['lastName'] profile['name'] = { 'givenName': data['firstName'], 'familyName': data['lastName'], 'formatted': '%s %s' % (data['firstName'], data['lastName']) } profile['accounts'] = [{ 'domain':'linkedin.com', 'userid':data['id'] }] return LinkedInAuthenticationComplete(profile=profile, credentials=cred)
def process(self, request): """Handle incoming redirect from OpenID Provider""" log_debug = self.log_debug if log_debug: log.debug('Handling processing of response from server') openid_session = request.session.get('openid_session', None) del request.session['openid_session'] if not openid_session: raise ThirdPartyFailure("No OpenID Session has begun.") # Setup the consumer and parse the information coming back oidconsumer = consumer.Consumer(openid_session, self.openid_store) return_to = request.route_url(self.process_url) info = oidconsumer.complete(request.params, return_to) if info.status in [consumer.FAILURE, consumer.CANCEL]: raise AuthenticationDenied("OpenID failure") elif info.status == consumer.SUCCESS: openid_identity = info.identity_url if info.endpoint.canonicalID: # If it's an i-name, use the canonicalID as its secure even if # the old one is compromised openid_identity = info.endpoint.canonicalID user_data = extract_openid_data( identifier=openid_identity, sreg_resp=sreg.SRegResponse.fromSuccessResponse(info), ax_resp=ax.FetchResponse.fromSuccessResponse(info), ) user_data['end_point'] = get_came_from(request) # Did we get any OAuth info? oauth = info.extensionResponse( 'http://specs.openid.net/extensions/oauth/1.0', False) cred = {} if oauth and 'request_token' in oauth: access_token = self._get_access_token(oauth['request_token']) if access_token: cred.update(access_token) # See if we need to update our profile data with an OAuth call self._update_profile_data(request, user_data, cred) # Delete the temporary token data used for the OpenID auth return self.AuthenticationComplete(profile=user_data, credentials=cred) else: raise ThirdPartyFailure("OpenID failed.")
def bitbucket_process(request): """Process the bitbucket redirect""" if 'denied' in request.GET: return AuthenticationDenied("User denied authentication") config = request.registry.settings request_token = oauth.Token.from_string(request.session['token']) verifier = request.GET.get('oauth_verifier') if not verifier: raise ThirdPartyFailure("No oauth_verifier returned") request_token.set_verifier(verifier) # Create the consumer and client, make the request consumer = oauth.Consumer(config['velruse.bitbucket.consumer_key'], config['velruse.bitbucket.consumer_secret']) client = oauth.Client(consumer, request_token) resp, content = client.request(ACCESS_URL, "POST") if resp['status'] != '200': raise ThirdPartyFailure("Status %s: %s" % (resp['status'], content)) access_token = dict(parse_qs(content)) cred = { 'oauthAccessToken': access_token['oauth_token'][0], 'oauthAccessTokenSecret': access_token['oauth_token_secret'][0] } # Make a request with the data for more user info token = oauth.Token(key=cred['oauthAccessToken'], secret=cred['oauthAccessTokenSecret']) client = oauth.Client(consumer, token) resp, content = client.request(USER_URL) user_data = json.loads(content) data = user_data['user'] # Setup the normalized contact info profile = {} profile['accounts'] = [{ 'domain': 'bitbucket.com', 'username': data['username'] }] profile['preferredUsername'] = data['username'] profile['name'] = { 'formatted': '%s %s' % (data['first_name'], data['last_name']), 'givenName': data['first_name'], 'familyName': data['last_name'] } profile['displayName'] = profile['name']['formatted'] return BitbucketAuthenticationComplete(profile=profile, credentials=cred)
def weibo_process(request): """Process the weibo redirect""" if request.GET.get('state') != request.session.get('state'): raise CSRFError( "CSRF Validation check failed. Request state %s is " "not the same as session state %s" % (request.GET.get('state'), request.session.get('state'))) config = request.registry.settings code = request.GET.get('code') if not code: reason = request.GET.get('error_reason', 'No reason provided.') return AuthenticationDenied(reason) # Now retrieve the access token with the code r = requests.post( 'https://api.weibo.com/oauth2/access_token', dict(client_id=config['velruse.weibo.app_id'], client_secret=config['velruse.weibo.app_secret'], redirect_uri=request.route_url('weibo_process'), grant_type='authorization_code', code=code)) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) data = loads(r.content) access_token = data['access_token'] uid = data['uid'] # Retrieve profile data graph_url = flat_url('https://api.weibo.com/2/users/show.json', access_token=access_token, uid=uid) r = requests.get(graph_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) data = loads(r.content) profile = { 'accounts': [{ 'domain': 'weibo.com', 'userid': data['id'] }], 'gender': data.get('gender'), 'displayName': data['screen_name'], 'preferredUsername': data['name'], } cred = {'oauthAccessToken': access_token} return WeiboAuthenticationComplete(profile=profile, credentials=cred)
def qq_process(request): """Process the qq redirect""" config = request.registry.settings code = request.GET.get('code') if not code: reason = request.GET.get('error', 'No reason provided.') return AuthenticationDenied(reason) # Now retrieve the access token with the code access_url = flat_url('https://graph.qq.com/oauth2.0/token', client_id=config['velruse.qq.app_id'], client_secret=config['velruse.qq.app_secret'], grant_type='authorization_code', redirect_uri=request.route_url('qq_process'), code=code) r = requests.get(access_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) access_token = parse_qs(r.content)['access_token'][0] # Retrieve profile data graph_url = flat_url('https://graph.qq.com/oauth2.0/me', access_token=access_token) r = requests.get(graph_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) data = loads(r.content[10:-3]) openid = data.get('openid', '') user_info_url = flat_url('https://graph.qq.com/user/get_user_info', access_token=access_token, oauth_consumer_key=config['velruse.qq.app_id'], openid=openid) r = requests.get(user_info_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) data = loads(r.content) profile = { 'accounts': [{'domain':'qq.com', 'userid':openid}], 'displayName': data['nickname'], 'preferredUsername': data['nickname'], } cred = {'oauthAccessToken': access_token} return QQAuthenticationComplete(profile=profile, credentials=cred)
def github_process(request): """Process the github redirect""" config = request.registry.settings code = request.GET.get('code') if not code: reason = request.GET.get('error', 'No reason provided.') return AuthenticationDenied(reason) # Now retrieve the access token with the code access_url = flat_url( 'https://github.com/login/oauth/access_token', client_id=config['velruse.github.consumer_key'], client_secret=config['velruse.github.consumer_secret'], redirect_uri=request.route_url('github_process'), code=code) r = requests.get(access_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) access_token = parse_qs(r.content)['access_token'][0] # Retrieve profile data graph_url = flat_url('https://github.com/api/v2/json/user/show', access_token=access_token) r = requests.get(graph_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) data = loads(r.content)['user'] profile = {} profile['accounts'] = [{ 'domain': 'github.com', 'username': data['login'], 'userid': data['id'] }] profile['displayName'] = data['name'] profile['preferredUsername'] = data['login'] profile['end_point'] = get_came_from(request) # We don't add this to verifiedEmail because ppl can change email addresses # without verifying them if 'email' in data: profile['emails'] = [{'value': data['email']}] cred = {'oauthAccessToken': access_token} return GithubAuthenticationComplete(profile=profile, credentials=cred)
def douban_process(request): """Process the douban redirect""" if 'denied' in request.GET: return AuthenticationDenied("User denied authentication") config = request.registry.settings request_token = oauth.Token.from_string(request.session['token']) # Create the consumer and client, make the request consumer = oauth.Consumer(config['velruse.douban.consumer_key'], config['velruse.douban.consumer_secret']) client = oauth.Client(consumer, request_token) resp, content = client.request(ACCESS_URL) if resp['status'] != '200': raise ThirdPartyFailure("Status %s: %s" % (resp['status'], content)) access_token = dict(parse_qs(content)) cred = { 'oauthAccessToken': access_token['oauth_token'][0], 'oauthAccessTokenSecret': access_token['oauth_token_secret'][0] } douban_user_id = access_token['douban_user_id'][0] token = oauth.Token(key=cred['oauthAccessToken'], secret=cred['oauthAccessTokenSecret']) client = oauth.Client(consumer, token) resp, content = client.request(USER_URL) user_data = json.loads(content) # Setup the normalized contact info profile = { 'accounts': [{ 'domain': 'douban.com', 'userid': douban_user_id }], 'displayName': user_data['title']['$t'], 'preferredUsername': user_data['title']['$t'], } return DoubanAuthenticationComplete(profile=profile, credentials=cred)
def live_process(request): """Process the Live redirect""" if 'error' in request.GET: raise ThirdPartyFailure(request.GET.get('error_description', 'No reason provided.')) config = request.registry.settings code = request.GET.get('code') if not code: reason = request.GET.get('error_reason', 'No reason provided.') return AuthenticationDenied(reason) # Now retrieve the access token with the code access_url = flat_url('https://oauth.live.com/token', client_id=config['velruse.live.client_id'], client_secret=config['velruse.live.client_secret'], redirect_uri=request.route_url('live_process'), grant_type="authorization_code", code=code) r = requests.get(access_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) data = loads(r.content) access_token = data['access_token'] # Retrieve profile data graph_url = flat_url('https://apis.live.net/v5.0/me', access_token=access_token) r = requests.get(graph_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) live_profile = loads(r.content) profile = extract_live_data(live_profile) cred = {'oauthAccessToken': access_token} if 'refresh_token' in data: cred['oauthRefreshToken'] = data['refresh_token'] return LiveAuthenticationComplete(profile=profile, credentials=cred)
def lastfm_process(request): """Process the LastFM redirect""" if 'error' in request.GET: raise ThirdPartyFailure( request.GET.get('error_description', 'No reason provided.')) config = request.registry.settings api_key = config['velruse.lastfm.api_key'] token = request.GET.get('token') if not token: reason = request.GET.get('error_reason', 'No reason provided.') return AuthenticationDenied(reason) # Now establish a session with the token params = {'method': 'auth.getSession', 'api_key': api_key, 'token': token} signed_params = sign_call(params, config['velruse.lastfm.secret']) session_url = flat_url(API_BASE, format='json', **signed_params) r = requests.get(session_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) data = loads(r.content) session = data['session'] cred = {'sessionKey': session['key']} # Fetch the user data user_url = flat_url(API_BASE, format='json', method='user.getInfo', user=session['name'], api_key=api_key) r = requests.get(user_url) if r.status_code != 200: raise ThirdPartyFailure("Status %s: %s" % (r.status_code, r.content)) data = loads(r.content)['user'] profile = { 'displayName': data['name'], 'gender': 'male' if data['gender'] == 'm' else 'female', 'name': { 'formatted': data.get('realname'), }, 'urls': { 'type': 'profile', 'value': data.get('url') }, 'photos': [], 'accounts': [{ 'domain': 'last.fm', 'username': session['name'], 'userid': data['id'] }] } images = {} for img in data.get('image', []): images[img['size']] = img['#text'] if 'medium' in images: profile['photos'].append({ 'type': 'thumbnail', 'value': images['medium'] }) larger = images.get('extralarge', images.get('large')) if larger: profile['photos'].append({'type': '', 'value': larger}) return LastFMAuthenticationComplete(profile=profile, credentials=cred)
try: # We have suceed to connect, break the loop con = ldap.initialize(url) bind = con.simple_bind_s(dn, password) verified_login = True items = con.search_s(dn, ldap.SCOPE_SUBTREE) if items: for item in items: if item[0] == dn: data = item[1] break except Exception, e: pass if not verified_login: reason = "Cannot verify the credentials with any of the ldap servers %s." % url return AuthenticationDenied(reason) profile = {} email, emails = '', data.get('mail', '') if emails: if isinstance(emails, list): email = emails[0] else: email = emails profile['accounts'] = [{ 'domain': 'ldap', 'username': username, 'userid': username, }] if email: profile['verifiedEmail'] = email profile['emails'] = [{'value': email}]