From 417c11683a475010a444ab2f48cb3082640a2db0 Mon Sep 17 00:00:00 2001 From: rohan-chaturvedi Date: Mon, 25 Sep 2023 14:29:37 +0530 Subject: [PATCH] refactor: emails --- .../{backend/api/email.py => api/emails.py} | 30 +++++- backend/api/views.py | 95 +++---------------- 2 files changed, 41 insertions(+), 84 deletions(-) rename backend/{backend/api/email.py => api/emails.py} (52%) diff --git a/backend/backend/api/email.py b/backend/api/emails.py similarity index 52% rename from backend/backend/api/email.py rename to backend/api/emails.py index 50a20074..e54c647e 100644 --- a/backend/backend/api/email.py +++ b/backend/api/emails.py @@ -1,6 +1,10 @@ from django.conf import settings from django.core.mail import send_mail from django.template.loader import render_to_string +from datetime import datetime + +from api.utils import get_client_ip + def send_email(subject, recipient_list, template_name, context): """ @@ -8,10 +12,10 @@ def send_email(subject, recipient_list, template_name, context): """ # Load the template email_html_message = render_to_string(template_name, context) - + # Get the DEFAULT_FROM_EMAIL from settings default_from_email = getattr(settings, "DEFAULT_FROM_EMAIL") - + # Send the email send_mail( subject, @@ -20,3 +24,25 @@ def send_email(subject, recipient_list, template_name, context): recipient_list, html_message=email_html_message ) + + +def send_login_email(request, email): + user_agent = request.META.get('HTTP_USER_AGENT', 'Unknown') + ip_address = get_client_ip(request) + timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') + + # Creating context dictionary + context = { + 'auth': 'GitHub', + 'email': email, + 'ip': ip_address, + 'user_agent': user_agent, + 'timestamp': timestamp + } + + send_email( + 'New Login Alert - Phase Console', + [email], + 'backend/api/email_templates/login.html', + context + ) diff --git a/backend/api/views.py b/backend/api/views.py index f02eff7d..3fb76ef9 100644 --- a/backend/api/views.py +++ b/backend/api/views.py @@ -2,6 +2,7 @@ from datetime import datetime import json from api.serializers import EnvironmentKeySerializer, SecretSerializer, ServiceTokenSerializer, UserTokenSerializer +from api.emails import send_login_email from backend.graphene.utils.permissions import user_can_access_environment from dj_rest_auth.registration.views import SocialLoginView from django.contrib.auth.mixins import LoginRequiredMixin @@ -30,22 +31,12 @@ from rest_framework import status from django.views.decorators.csrf import csrf_exempt from django.utils import timezone -from backend.api.email import send_email + CLOUD_HOSTED = settings.APP_HOST == 'cloud' # for custom gitlab adapter class -def get_client_ip(request): - """ - Get client IP address from request. - """ - x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') - if x_forwarded_for: - ip = x_forwarded_for.split(',')[0] - else: - ip = request.META.get('REMOTE_ADDR') - return ip def _check_errors(response): # 403 error's are presented as user-facing errors @@ -96,7 +87,7 @@ def complete_login(self, request, app, token, response, **kwargs): raise OAuth2Error("Invalid id_token") from e login = self.get_provider().sociallogin_from_response(request, identity_data) email = login.email_addresses[0] - + if CLOUD_HOSTED and not CustomUser.objects.filter(email=email).exists(): try: # Notify Slack @@ -104,28 +95,8 @@ def complete_login(self, request, app, token, response, **kwargs): except Exception as e: print(f"Error notifying Slack: {e}") - # Grabbing metadata - user_agent = request.META.get('HTTP_USER_AGENT', 'Unknown') - ip_address = get_client_ip(request) - timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') - - # Creating context dictionary - context = { - 'auth': 'GitHub', - 'email': email, - 'ip': ip_address, - 'user_agent': user_agent, - 'timestamp': timestamp - } - try: - # Calling send_email function - send_email( - 'New Login Alert - Phase Console', - [email], - 'backend/api/email_templates/login.html', - context - ) + send_login_email(request, email) except Exception as e: print(f"Error sending email: {e}") @@ -157,7 +128,7 @@ def complete_login(self, request, app, token, **kwargs): extra_data["email"] = self.get_email(headers) email = extra_data["email"] - + if CLOUD_HOSTED and not CustomUser.objects.filter(email=email).exists(): try: # Notify Slack @@ -165,30 +136,10 @@ def complete_login(self, request, app, token, **kwargs): except Exception as e: print(f"Error notifying Slack: {e}") - # Grabbing metadata - user_agent = request.META.get('HTTP_USER_AGENT', 'Unknown') - ip_address = get_client_ip(request) - timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') - - # Creating context dictionary - context = { - 'auth': 'GitHub', - 'email': email, - 'ip': ip_address, - 'user_agent': user_agent, - 'timestamp': timestamp - } - - try: - # Calling send_email function - send_email( - 'New Login Alert - Phase Console', - [email], - 'backend/api/email_templates/login.html', - context - ) - except Exception as e: - print(f"Error sending email: {e}") + try: + send_login_email(request, email) + except Exception as e: + print(f"Error sending email: {e}") return self.get_provider().sociallogin_from_response(request, extra_data) @@ -223,30 +174,10 @@ def complete_login(self, request, app, token, response): except Exception as e: print(f"Error notifying Slack: {e}") - # Grabbing metadata - user_agent = request.META.get('HTTP_USER_AGENT', 'Unknown') - ip_address = get_client_ip(request) - timestamp = datetime.now().strftime('%Y-%m-%d %H:%M:%S') - - # Creating context dictionary - context = { - 'auth': 'GitLab', - 'email': email, - 'ip': ip_address, - 'user_agent': user_agent, - 'timestamp': timestamp - } - - try: - # Calling send_email function - send_email( - 'New Login Alert - Phase Console', - [email], - 'backend/api/email_templates/login.html', - context - ) - except Exception as e: - print(f"Error sending email: {e}") + try: + send_login_email(request, email) + except Exception as e: + print(f"Error sending email: {e}") return login