def test_get_github_primary_email(self): """Test the github utility get_github_primary_email method.""" data = [ {'primary': True, 'email': '*****@*****.**'}, {'email': '*****@*****.**'} ] url = 'https://api.github.com/user/emails' responses.add(responses.GET, url, json=data, headers=HEADERS, status=200) responses.add(responses.GET, url, json=data, headers=HEADERS, status=404) email = get_github_primary_email(self.user_oauth_token) no_email = get_github_primary_email(self.user_oauth_token) assert email == '*****@*****.**' assert no_email == ''
def github_callback(request): """Handle the Github authentication callback.""" # Get request parameters to handle authentication and the redirect. code = request.GET.get('code', None) redirect_uri = request.GET.get('redirect_uri') if not code or not redirect_uri: raise Http404 # Get OAuth token and github user data. access_token = get_github_user_token(code) github_user_data = get_github_user_data(access_token) handle = github_user_data.get('login') ip_address = '24.210.224.38' if settings.DEBUG else get_real_ip(request) geolocation_data = {} if ip_address: geolocation_data = get_location_from_ip(ip_address) if handle: # Create or update the Profile with the github user data. user_profile, _ = Profile.objects.update_or_create( handle=handle, defaults={ 'data': github_user_data or {}, 'email': get_github_primary_email(access_token), 'github_access_token': access_token }) # Update the user's session with handle and email info. session_data = { 'handle': user_profile.handle, 'email': user_profile.email, 'access_token': user_profile.github_access_token, 'profile_id': user_profile.pk, 'name': user_profile.data.get('name', None), 'access_token_last_validated': timezone.now().isoformat(), } for k, v in session_data.items(): request.session[k] = v # record a useraction for this UserAction.objects.create(profile=user_profile, action='Login', metadata={}, ip_address=ip_address, location_data=geolocation_data) response = redirect(redirect_uri) response.set_cookie('last_github_auth_mutation', int(time.time())) return response
def github_callback(request): """Handle the Github authentication callback.""" # Get request parameters to handle authentication and the redirect. code = request.GET.get('code', None) redirect_uri = request.GET.get('redirect_uri') if not code or not redirect_uri: raise Http404 # Get OAuth token and github user data. access_token = get_github_user_token(code) github_user_data = get_github_user_data(access_token) handle = github_user_data.get('login') github_repos = get_github_repos(access_token) if handle: # Create or update the Profile with the github user data. # user_profile, _ = Profile.objects.update_or_create( # handle=handle, # defaults={ # 'data': github_user_data or {}, # 'email': get_github_primary_email(access_token), # 'github_access_token': access_token # }) # Update the user's session with handle and email info. session_data = { 'handle': handle, 'user_repos': github_repos, 'email': get_github_primary_email(access_token), 'access_token': access_token, 'name': github_user_data.get('name', None), 'access_token_last_validated': timezone.now().isoformat(), } for k, v in session_data.items(): request.session[k] = v # # record a useraction for this # UserAction.objects.create( # profile=user_profile, # action='Login', # metadata={}, # ) response = redirect(redirect_uri) response.set_cookie('last_github_auth_mutation', int(time.time())) return response
def github_callback(request): """Handle the Github authentication callback.""" # Get request parameters to handle authentication and the redirect. code = request.GET.get('code', None) redirect_uri = request.GET.get('redirect_uri') if not code or not redirect_uri: raise Http404 # Get OAuth token and github user data. access_token = get_github_user_token(code) github_user_data = get_github_user_data(access_token) handle = github_user_data.get('login') if handle: # Create or update the Profile with the github user data. user_profile, _ = Profile.objects.update_or_create( handle=handle, defaults={ 'data': github_user_data or {}, 'email': get_github_primary_email(access_token), 'github_access_token': access_token }) # Update the user's session with handle and email info. session_data = { 'handle': user_profile.handle, 'email': user_profile.email, 'access_token': user_profile.github_access_token, 'profile_id': user_profile.pk, 'access_token_last_validated': timezone.now().isoformat(), } for k, v in session_data.items(): request.session[k] = v response = redirect(redirect_uri) response.set_cookie('last_github_auth_mutation', int(time.time())) return response
def send_tip_2(request): """Handle the second stage of sending a tip. TODO: * Convert this view-based logic to a django form. Returns: JsonResponse: If submitting tip, return response with success state. TemplateResponse: Render the submission form. """ from_username = request.session.get('handle', '') primary_from_email = request.session.get('email', '') access_token = request.session.get('access_token') to_emails = [] if request.body: # http response response = { 'status': 'OK', 'message': 'Notification has been sent', } params = json.loads(request.body) to_username = params['username'].lstrip('@') try: to_profile = Profile.objects.get(handle__iexact=to_username) if to_profile.email: to_emails.append(to_profile.email) if to_profile.github_access_token: to_emails = get_github_emails(to_profile.github_access_token) except Profile.DoesNotExist: pass if params.get('email'): to_emails.append(params['email']) # If no primary email in session, try the POST data. If none, fetch from GH. if params.get('fromEmail'): primary_from_email = params['fromEmail'] elif access_token and not primary_from_email: primary_from_email = get_github_primary_email(access_token) to_emails = list(set(to_emails)) expires_date = timezone.now() + timezone.timedelta( seconds=params['expires_date']) # db mutations tip = Tip.objects.create( emails=to_emails, url=params['url'], tokenName=params['tokenName'], amount=params['amount'], comments_priv=params['comments_priv'], comments_public=params['comments_public'], ip=get_ip(request), expires_date=expires_date, github_url=params['github_url'], from_name=params['from_name'], from_email=params['from_email'], from_username=from_username, username=params['username'], network=params['network'], tokenAddress=params['tokenAddress'], txid=params['txid'], from_address=params['from_address'], ) # notifications maybe_market_tip_to_github(tip) maybe_market_tip_to_slack(tip, 'new_tip') maybe_market_tip_to_email(tip, to_emails) if not to_emails: response['status'] = 'error' response[ 'message'] = 'Uh oh! No email addresses for this user were found via Github API. Youll have to let the tipee know manually about their tip.' return JsonResponse(response) params = { 'issueURL': request.GET.get('source'), 'class': 'send2', 'title': 'Send Tip', 'recommend_gas_price': recommend_min_gas_price_to_confirm_in_time( confirm_time_minutes_target), 'from_email': primary_from_email, 'from_handle': from_username, } return TemplateResponse(request, 'yge/send2.html', params)
def send_tip_3(request): """Handle the third stage of sending a tip (the POST) Returns: JsonResponse: response with success state. """ response = { 'status': 'OK', 'message': _('Tip Created'), } is_user_authenticated = request.user.is_authenticated from_username = request.user.username if is_user_authenticated else '' primary_from_email = request.user.email if is_user_authenticated else '' access_token = request.user.profile.get_access_token( ) if is_user_authenticated else '' to_emails = [] params = json.loads(request.body) to_username = params['username'].lstrip('@') try: to_profile = Profile.objects.get(handle__iexact=to_username) except Profile.MultipleObjectsReturned: to_profile = Profile.objects.filter(handle__iexact=to_username).first() except Profile.DoesNotExist: to_profile = None if to_profile: if to_profile.email: to_emails.append(to_profile.email) if to_profile.github_access_token: to_emails = get_github_emails(to_profile.github_access_token) if params.get('email'): to_emails.append(params['email']) # If no primary email in session, try the POST data. If none, fetch from GH. if params.get('fromEmail'): primary_from_email = params['fromEmail'] elif access_token and not primary_from_email: primary_from_email = get_github_primary_email(access_token) to_emails = list(set(to_emails)) expires_date = timezone.now() + timezone.timedelta( seconds=params['expires_date']) priv_key, pub_key, address = generate_pub_priv_keypair() # db mutations tip = Tip.objects.create(emails=to_emails, tokenName=params['tokenName'], amount=params['amount'], comments_priv=params['comments_priv'], comments_public=params['comments_public'], ip=get_ip(request), expires_date=expires_date, github_url=params['github_url'], from_name=params['from_name'], from_email=params['from_email'], from_username=from_username, username=params['username'], network=params['network'], tokenAddress=params['tokenAddress'], from_address=params['from_address'], metadata={ 'priv_key': priv_key, 'pub_key': pub_key, 'address': address, }) response['payload'] = { 'address': address, } return JsonResponse(response)