81 lines
1.9 KiB
Python
81 lines
1.9 KiB
Python
#!/usr/bin/env python3
|
|
"""
|
|
/signup app views.
|
|
"""
|
|
# TODO: make unique username validation be case insensitive
|
|
import random
|
|
import string
|
|
|
|
from django.shortcuts import redirect, render
|
|
from django.core.mail import send_mail
|
|
from django.urls import reverse
|
|
from django.conf import settings
|
|
|
|
from .forms import SignupForm
|
|
from .models import Confirmation
|
|
|
|
def index(request):
|
|
"""
|
|
The signup page.
|
|
"""
|
|
if request.user.is_authenticated:
|
|
return redirect('homepage:index')
|
|
if request.method == 'POST':
|
|
form = SignupForm(request.POST)
|
|
if form.is_valid():
|
|
user = form.save()
|
|
confirm = Confirmation(
|
|
user=user,
|
|
code=get_code(32)
|
|
)
|
|
confirm.save()
|
|
verify_url = request.build_absolute_uri(reverse('signup:verify'))
|
|
verify_url = verify_url.replace("http", "https")
|
|
email_confirmation(confirm, verify_url)
|
|
return render(request, 'signup/confirmation_sent.html', locals())
|
|
else:
|
|
form = SignupForm()
|
|
return render(request, 'signup/index.html', {'form': form})
|
|
|
|
|
|
def get_code(n):
|
|
"""
|
|
Helper function to generate n number of psudeo-random ASCII characters.
|
|
"""
|
|
chars = []
|
|
for _ in range(n):
|
|
chars.append(random.choice(string.ascii_letters + string.digits))
|
|
return "".join(chars)
|
|
|
|
|
|
def email_confirmation(confirm, verify_url):
|
|
"""
|
|
Sends out a confirmation to the user.
|
|
"""
|
|
message = "Please use the following link to verify your account: "
|
|
message += verify_url + "?code=" + confirm.code
|
|
send_mail(
|
|
"Email verification",
|
|
message,
|
|
settings.DEFAULT_FROM_EMAIL,
|
|
[confirm.user.email],
|
|
)
|
|
|
|
|
|
def verify(request):
|
|
"""
|
|
Verifies and activates the user's account.
|
|
"""
|
|
code = request.GET.get("code")
|
|
if not code:
|
|
return redirect('homepage:index')
|
|
try:
|
|
confirm = Confirmation.objects.get(code=code)
|
|
except Confirmation.DoesNotExist:
|
|
return redirect('homepage:index')
|
|
user = confirm.user
|
|
user.is_active = True
|
|
user.save()
|
|
confirm.delete()
|
|
return render(request, 'signup/confirmed.html', locals())
|