Skip to content

Commit

Permalink
refactor: emails
Browse files Browse the repository at this point in the history
  • Loading branch information
rohan-chaturvedi committed Sep 25, 2023
1 parent a5f5a70 commit 417c116
Show file tree
Hide file tree
Showing 2 changed files with 41 additions and 84 deletions.
30 changes: 28 additions & 2 deletions backend/backend/api/email.py → backend/api/emails.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,21 @@
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):
"""
Send email via SMTP gateway through Django's email backend.
"""
# 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,
Expand All @@ -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
)
95 changes: 13 additions & 82 deletions backend/api/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down Expand Up @@ -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
Expand Down Expand Up @@ -96,36 +87,16 @@ 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
notify_slack(f"New user signup: {email}")
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}")

Expand Down Expand Up @@ -157,38 +128,18 @@ 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
notify_slack(f"New user signup: {email}")
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)

Expand Down Expand Up @@ -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

Expand Down

0 comments on commit 417c116

Please sign in to comment.