Skip to content

Commit

Permalink
fix thread
Browse files Browse the repository at this point in the history
  • Loading branch information
asennoussi committed Apr 16, 2023
1 parent 16b290d commit 03cbc81
Show file tree
Hide file tree
Showing 7 changed files with 91 additions and 8 deletions.
24 changes: 23 additions & 1 deletion accounts/forms.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,12 +9,14 @@
import django_rq

from .models import CustomUser
from referral.models import Referral


class SignUpForm(UserCreationForm):
password1 = forms.CharField(widget=forms.PasswordInput())
password2 = forms.CharField(widget=forms.PasswordInput())
email = forms.EmailField(label='Email', max_length=254)
referral_code = forms.CharField(required=False, widget=forms.HiddenInput())

class Meta:
model = CustomUser
Expand All @@ -23,8 +25,8 @@ class Meta:
'password1',
'password2',
]

# We need the user object, so it's an additional parameter

def send_activation_email(self, request, user):
current_site = get_current_site(request)
subject = 'Activate Your Account'
Expand All @@ -40,6 +42,26 @@ def send_activation_email(self, request, user):
django_rq.enqueue(user.email_user,
subject, message, html_message=message)

def clean_referral_code(self):
referral_code = self.cleaned_data['referral_code']
if referral_code:
# Validate the referral code and retrieve the referral object
try:
referral = CustomUser.objects.get(referral_code=referral_code)
except CustomUser.DoesNotExist:
raise forms.ValidationError('Invalid referral code')
return referral.referral_code
return None

def create_referral(self, referral_code, user):
referrer = CustomUser.objects.get(
referral_code=referral_code)

referral, created = Referral.objects.get_or_create(user=referrer)
import pdb
pdb.set_trace()
return referral.referred_users.add(user)


class LoginForm(AuthenticationForm):
username = forms.CharField(label='Email')
12 changes: 12 additions & 0 deletions accounts/models.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@

import random
import string
from django.conf import settings
from django.db import models
from django.contrib.auth.models import AbstractUser
Expand Down Expand Up @@ -42,6 +45,13 @@ def create_superuser(self, email, password, **extra_fields):
return self.create_user(email, password, **extra_fields)


def generate_referral_code():
# Generate a random string of 6 characters
referral_code = ''.join(random.choices(
string.ascii_uppercase + string.digits, k=6))
return referral_code


class CustomUser(AbstractUser):
SUBSCRIPTION_STATUS = (
('subscribed', 'SUBSCRIBED'),
Expand All @@ -55,6 +65,8 @@ class CustomUser(AbstractUser):
subscription_status = models.CharField(
max_length=20, choices=SUBSCRIPTION_STATUS, default='trial')
created_at = models.DateTimeField(auto_now_add=True)
referral_code = models.CharField(
max_length=50, default=generate_referral_code)
expires_at = models.DateTimeField(null=True)
is_verified = models.BooleanField(default=False)
USERNAME_FIELD = 'email'
Expand Down
1 change: 1 addition & 0 deletions accounts/templates/accounts/sign-up.html
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ <h1>Sign Up</h1>
Password</label>
<div class="help-block with-errors">{{ form.password2.errors }}</div>
</div>
{{ form.referral_code }}
<div class="form-group checkbox">
By signing up, I agree with Tivo's <a href="privacy-policy.html">Privacy Policy</a> and <a
href="terms-conditions.html">Terms Conditions</a>
Expand Down
15 changes: 11 additions & 4 deletions accounts/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,15 +30,22 @@ class SignUpView(CreateView):
success_url = reverse_lazy(
'onboarding', kwargs={'step_name': 'link-account'})

def get_form_kwargs(self):
kwargs = super().get_form_kwargs()
# Set the default value for the form field using the value stored in the cookies
kwargs['initial'] = {
'referral_code': self.request.COOKIES.get('referral_code', '')}
return kwargs

def form_valid(self, form):
to_return = super().form_valid(form)

user = form.save()
user.is_verified = False # Turns the user status to inactive
user.is_verified = False # Turns the user email verification to False
user.save()

form.send_activation_email(self.request, user)

# form.send_activation_email(self.request, user)
# When the user signs up check if the referral is there.
form.create_referral(form.cleaned_data['referral_code'], user)
login(self.request, self.object,
backend='accounts.backends.EmailBackend')
return to_return
Expand Down
4 changes: 3 additions & 1 deletion emailguru/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,8 @@
ALLOWED_HOSTS = [
'127.0.0.1', 'localhost']

CSRF_TRUSTED_ORIGINS = ['https://*.ngrok.io', 'https://*.127.0.0.1']
CSRF_TRUSTED_ORIGINS = ['https://*.ngrok.io',
'https://*.127.0.0.1', 'https://*.ngrok-free.app']

# Application definition

Expand All @@ -42,6 +43,7 @@
'accounts.apps.AccountsConfig',
'dashboard.apps.DashboardConfig',
'onboarding.apps.OnboardingConfig',
'referral.apps.ReferralConfig',

'django_rq',
'paypal.standard.ipn',
Expand Down
34 changes: 32 additions & 2 deletions emailguru/utils.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
from datetime import datetime, timedelta
from hashlib import sha256


import django_rq
from accounts.models import LinkedAccounts
from contacts.models import Contact
Expand All @@ -15,6 +16,7 @@
from googleapiclient.discovery import build
from googleapiclient.errors import HttpError
from django.core.signing import Signer
import re

signer = Signer()

Expand Down Expand Up @@ -63,6 +65,34 @@ def get_google_flow():
return flow


def is_part_of_contact_thread(service, email_id, user, la):
try:
message = service.users().messages().get(
userId='me', id=email_id, format='full').execute()
thread_id = message['threadId']
thread = service.users().threads().get(userId='me', id=thread_id).execute()
email_pattern = r'([\w\.-]+@[\w\.-]+)'

for msg in thread['messages']:
headers = msg['payload']['headers']
for header in headers:
if header["name"].lower() == "from":
from_value = header["value"]
match = re.search(email_pattern, from_value)
if match:
from_email = match.group(1)
encrypted_contact = sha256(
from_email.encode('utf-8')).hexdigest()
if Contact.objects.filter(hashed_email=encrypted_contact, linked_account=la).exists():
return True

except HttpError as error:
print(f"An error occurred: {error}")
return False

return False


def handle_email(email_id, from_email, user, associated_email):

encrypted_contact = sha256(from_email.encode('utf-8')).hexdigest()
Expand All @@ -86,8 +116,8 @@ def handle_email(email_id, from_email, user, associated_email):
return

service = build('gmail', 'v1', credentials=credentials)

if(qs.exists()):
print(is_part_of_contact_thread(service, email_id, user, la))
if(qs.exists() or is_part_of_contact_thread(service, email_id, user, la)):
update_label = {
"addLabelIds": [],
"removeLabelIds": [la.label]
Expand Down
9 changes: 9 additions & 0 deletions landing/views.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,16 @@
from django.shortcuts import render
from django.views.generic import TemplateView

# Create your views here.


class HomeView(TemplateView):
template_name = "landing/index.html"

def get(self, request):
# Save the referral code in a cookie
ref = request.GET.get('ref', '')
response = render(request, self.template_name, {
'referral_code': ref})
response.set_cookie('referral_code', ref)
return response

0 comments on commit 03cbc81

Please sign in to comment.