You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
63 lines
2.1 KiB
63 lines
2.1 KiB
from django.contrib.auth import get_user_model, logout, login
|
|
from django.contrib.auth.forms import AuthenticationForm
|
|
from django.core.mail import EmailMessage
|
|
from django.http import JsonResponse
|
|
from django.views.generic import FormView, View
|
|
|
|
from .forms import LearnerRegistrationForm
|
|
from .tokens import verification_email_token
|
|
|
|
User = get_user_model()
|
|
|
|
|
|
class LearnerRegistrationView(FormView):
|
|
form_class = LearnerRegistrationForm
|
|
template_name = "auth/registration-learner.html"
|
|
|
|
def form_valid(self, form):
|
|
first_name = form.cleaned_data['first_name']
|
|
last_name = form.cleaned_data['last_name']
|
|
email = form.cleaned_data['email']
|
|
password = form.cleaned_data['password']
|
|
|
|
user = User.objects.create_user(username=email, email=email, first_name=first_name, last_name=last_name, password=password)
|
|
login(self.request, user)
|
|
|
|
# fixme: change email text
|
|
# fixme: async send email
|
|
token = verification_email_token.make_token(user)
|
|
email = EmailMessage('VerificationEmail', f"{token}", to=[email])
|
|
email.send()
|
|
|
|
return JsonResponse({"success": True}, status=201)
|
|
|
|
def form_invalid(self, form):
|
|
return JsonResponse(form.errors.get_json_data(escape_html=True), status=400)
|
|
|
|
|
|
class LogoutView(View):
|
|
def post(self, request, *args, **kwargs):
|
|
logout(request)
|
|
return JsonResponse({"success": True})
|
|
|
|
|
|
class LoginView(FormView):
|
|
form_class = AuthenticationForm
|
|
template_name = "auth/login.html"
|
|
|
|
def form_valid(self, form):
|
|
login(self.request, form.get_user())
|
|
return JsonResponse({"success": True})
|
|
|
|
def form_invalid(self, form):
|
|
return JsonResponse({"success": False, "errors": form.errors.get_json_data(escape_html=True)}, status=400)
|
|
|
|
|
|
class VerificationEmailView(View):
|
|
def get(self, request, *args, **kwargs):
|
|
is_valid_token = verification_email_token.check_token(request.user, kwargs.get('token'))
|
|
|
|
if is_valid_token:
|
|
return JsonResponse({"success": True})
|
|
else:
|
|
return JsonResponse({"success": False}, status=400)
|
|
|