def settings_helper_get_auth(request, key=None): # setup github_handle = request.user.username if request.user.is_authenticated else False is_logged_in = bool(request.user.is_authenticated) es = EmailSubscriber.objects.none() # check if user's email has changed if request.user.is_authenticated: current_email = get_github_primary_email( request.user.profile.github_access_token) if current_email != request.user.profile.email: request.user.profile.email = current_email request.user.profile.save() if current_email != request.user.email: request.user.email = current_email request.user.save() # find the user info if key is None or not EmailSubscriber.objects.filter(priv=key).exists(): email = request.user.email if request.user.is_authenticated else None if not email: github_handle = request.user.username if request.user.is_authenticated else None if hasattr(request.user, 'profile'): if request.user.profile.email_subscriptions.exists(): es = request.user.profile.email_subscriptions.first() if es.email != request.user.profile.email: es.email = request.user.profile.email es.save() if not es or es and not es.priv: es = get_or_save_email_subscriber(request.user.email, 'settings', profile=request.user.profile) else: try: es = EmailSubscriber.objects.get(priv=key) email = es.email except EmailSubscriber.DoesNotExist: pass # lazily create profile if needed profiles = Profile.objects.none() if github_handle: profiles = Profile.objects.prefetch_related('alumni').filter( handle=github_handle.lower()) profile = None if not profiles.exists() else profiles.first() if not profile and github_handle: profile = sync_profile(github_handle, user=request.user) # lazily create email settings if needed if not es: if request.user.is_authenticated and request.user.email: es = EmailSubscriber.objects.create( email=request.user.email, source='settings_page', profile=request.user.profile, ) es.set_priv() es.save() return profile, es, request.user, is_logged_in
def get_primary_from_email(params, request): """Find the primary_from_email address. This function finds the address using this priority: 1. If the email field is filed out in the Send POST request, use the `fromEmail` field. 2. If the user is logged in, they should have an email address associated with their account. Use this as the second option. `request_user_email`. 3. If all else fails, attempt to pull the email from the user's github account. Args: params (dict): A dictionary parsed form the POST request. Typically this is a POST request coming in from a Tips/Kudos send. Returns: str: The primary_from_email string. """ request_user_email = request.user.email if request.user.is_authenticated else '' logger.info(request.user.profile) access_token = request.user.profile.get_access_token() if request.user.is_authenticated else '' if params.get('fromEmail'): primary_from_email = params['fromEmail'] elif request_user_email: primary_from_email = request_user_email elif access_token: primary_from_email = get_github_primary_email(access_token) else: primary_from_email = '*****@*****.**' return primary_from_email
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 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 and request.user.profile else '' params = json.loads(request.body) to_username = params['username'].lstrip('@') to_emails = get_emails_by_category(to_username) primary_email = '' if params.get('email'): primary_email = params['email'] elif to_emails.get('primary', None): primary_email = to_emails['primary'] elif to_emails.get('github_profile', None): primary_email = to_emails['github_profile'] else: if len(to_emails.get('events', None)): primary_email = to_emails['events'][0] else: print("TODO: no email found. in the future, we should handle this case better because it's GOING to end up as a support request") if primary_email and isinstance(primary_email, list): primary_email = primary_email[0] # 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) expires_date = timezone.now() + timezone.timedelta(seconds=params['expires_date']) # metadata metadata = params['metadata'] metadata['user_agent'] = request.META.get('HTTP_USER_AGENT', '') # db mutations tip = Tip.objects.create( primary_email=primary_email, 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'] if params['from_name'] != 'False' else '', from_email=params['from_email'], from_username=from_username, username=params['username'], network=params['network'], tokenAddress=params['tokenAddress'], from_address=params['from_address'], is_for_bounty_fulfiller=params['is_for_bounty_fulfiller'], metadata=metadata, recipient_profile=get_profile(to_username), sender_profile=get_profile(from_username), ) is_over_tip_tx_limit = False is_over_tip_weekly_limit = False max_per_tip = request.user.profile.max_tip_amount_usdt_per_tx if request.user.is_authenticated and request.user.profile else 500 if tip.value_in_usdt_now: is_over_tip_tx_limit = tip.value_in_usdt_now > max_per_tip if request.user.is_authenticated and request.user.profile: tips_last_week_value = tip.value_in_usdt_now tips_last_week = Tip.objects.send_happy_path().filter(sender_profile=get_profile(from_username), created_on__gt=timezone.now() - timezone.timedelta(days=7)) for this_tip in tips_last_week: if this_tip.value_in_usdt_now: tips_last_week_value += this_tip.value_in_usdt_now is_over_tip_weekly_limit = tips_last_week_value > request.user.profile.max_tip_amount_usdt_per_week increase_funding_form_title = _('Request a Funding Limit Increasement') increase_funding_form = f'<a target="_blank" href="{settings.BASE_URL}'\ f'requestincrease">{increase_funding_form_title}</a>' if is_over_tip_tx_limit: response['status'] = 'error' response['message'] = _('This tip is over the per-transaction limit of $') +\ str(max_per_tip) + '. ' + increase_funding_form elif is_over_tip_weekly_limit: response['status'] = 'error' response['message'] = _('You are over the weekly tip send limit of $') +\ str(request.user.profile.max_tip_amount_usdt_per_week) +\ '. ' + increase_funding_form return JsonResponse(response)
def send_3(request): """Handle the third stage of sending a kudos (the POST). This function is derived from send_tip_3. The request to send the kudos is added to the database, but the transaction has not happened yet. The txid is added in `send_kudos_4`. Returns: JsonResponse: The response with success state. """ response = { 'status': 'OK', 'message': _('Kudos 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 and request.user.profile else '' params = json.loads(request.body) to_username = params.get('username', '').lstrip('@') to_emails = get_emails_by_category(to_username) primary_email = '' if params.get('email'): primary_email = params['email'] elif to_emails.get('primary', None): primary_email = to_emails['primary'] elif to_emails.get('github_profile', None): primary_email = to_emails['github_profile'] else: if len(to_emails.get('events', None)): primary_email = to_emails['events'][0] else: print("TODO: no email found. in the future, we should handle this case better because it's GOING to end up as a support request") if primary_email and isinstance(primary_email, list): primary_email = primary_email[0] # If no primary email in session, try the POST data. If none, fetch from GH. primary_from_email = params.get('fromEmail') if access_token and not primary_from_email: primary_from_email = get_github_primary_email(access_token) # Validate that the token exists on the back-end kudos_id = params.get('kudosId') if not kudos_id: raise Http404 try: kudos_token_cloned_from = Token.objects.get(pk=kudos_id) except Token.DoesNotExist: raise Http404 # db mutations KudosTransfer.objects.create( primary_email=primary_email, emails=to_emails, # For kudos, `token` is a kudos.models.Token instance. kudos_token_cloned_from=kudos_token_cloned_from, amount=params['amount'], comments_public=params['comments_public'], ip=get_ip(request), 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.get('tokenAddress', ''), from_address=params['from_address'], is_for_bounty_fulfiller=params['is_for_bounty_fulfiller'], metadata=params['metadata'], recipient_profile=get_profile(to_username), sender_profile=get_profile(from_username), ) return JsonResponse(response)
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('@') to_emails = get_emails_master(to_username) 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, 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'], is_for_bounty_fulfiller=params['is_for_bounty_fulfiller'], metadata=params['metadata'], recipient_profile=get_profile(to_username), sender_profile=get_profile(from_username), ) is_over_tip_tx_limit = False is_over_tip_weekly_limit = False max_per_tip = request.user.profile.max_tip_amount_usdt_per_tx if request.user.is_authenticated and request.user.profile else 500 if tip.value_in_usdt_now: is_over_tip_tx_limit = tip.value_in_usdt_now > max_per_tip if request.user.is_authenticated and request.user.profile: tips_last_week_value = tip.value_in_usdt_now tips_last_week = Tip.objects.exclude(txid='').filter( sender_profile=get_profile(from_username), created_on__gt=timezone.now() - timezone.timedelta(days=7)) for this_tip in tips_last_week: if this_tip.value_in_usdt_now: tips_last_week_value += this_tip.value_in_usdt_now is_over_tip_weekly_limit = tips_last_week_value > request.user.profile.max_tip_amount_usdt_per_week if is_over_tip_tx_limit: response['status'] = 'error' response['message'] = _( 'This tip is over the per-transaction limit of $') + str( max_per_tip) + ( '. Please try again later or contact support.') elif is_over_tip_weekly_limit: response['status'] = 'error' response['message'] = _( 'You are over the weekly tip send limit of $') + str( request.user.profile.max_tip_amount_usdt_per_week) + ( '. Please try again later or contact support.') return JsonResponse(response)
def send_3(request): """Handle the third stage of sending a kudos (the POST). This function is derived from send_tip_3. The request to send the kudos is added to the database, but the transaction has not happened yet. The txid is added in `send_kudos_4`. Returns: JsonResponse: The response with success state. """ response = { 'status': 'OK', 'message': _('Kudos 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 and request.user.profile else '' to_emails = [] params = json.loads(request.body) to_username = params.get('username', '').lstrip('@') to_emails = get_emails_master(to_username) email = params.get('email') if email: to_emails.append(email) # If no primary email in session, try the POST data. If none, fetch from GH. primary_from_email = params.get('fromEmail') if access_token and not primary_from_email: primary_from_email = get_github_primary_email(access_token) to_emails = list(set(to_emails)) # Validate that the token exists on the back-end kudos_id = params.get('kudosId') if not kudos_id: raise Http404 try: kudos_token_cloned_from = Token.objects.get(pk=kudos_id) except Token.DoesNotExist: raise Http404 # db mutations KudosTransfer.objects.create( emails=to_emails, # For kudos, `token` is a kudos.models.Token instance. kudos_token_cloned_from=kudos_token_cloned_from, amount=params['amount'], comments_public=params['comments_public'], ip=get_ip(request), 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'], is_for_bounty_fulfiller=params['is_for_bounty_fulfiller'], metadata=params['metadata'], recipient_profile=get_profile(to_username), sender_profile=get_profile(from_username), ) return JsonResponse(response)
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 and request.user.profile else '' params = json.loads(request.body) to_username = params['username'].lstrip('@') to_emails = get_emails_by_category(to_username) primary_email = '' if params.get('email'): primary_email = params['email'] elif to_emails.get('primary', None): primary_email = to_emails['primary'] elif to_emails.get('github_profile', None): primary_email = to_emails['github_profile'] else: if len(to_emails.get('events', None)): primary_email = to_emails['events'][0] else: print("TODO: no email found. in the future, we should handle this case better because it's GOING to end up as a support request") if primary_email and isinstance(primary_email, list): primary_email = primary_email[0] # 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) expires_date = timezone.now() + timezone.timedelta(seconds=params['expires_date']) # metadata metadata = params['metadata'] metadata['user_agent'] = request.META.get('HTTP_USER_AGENT', '') # db mutations tip = Tip.objects.create( primary_email=primary_email, 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'] if params['from_name'] != 'False' else '', from_email=params['from_email'], from_username=from_username, username=params['username'], network=params.get('network', 'unknown'), tokenAddress=params['tokenAddress'], from_address=params['from_address'], is_for_bounty_fulfiller=params['is_for_bounty_fulfiller'], metadata=metadata, recipient_profile=get_profile(to_username), sender_profile=get_profile(from_username), ) return JsonResponse(response)
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.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)