|
| 1 | +from django.core.mail import send_mail |
| 2 | +from django.template.loader import render_to_string |
| 3 | +from django.utils.html import strip_tags |
| 4 | +from rest_framework import status |
| 5 | +from rest_framework.decorators import api_view |
| 6 | +from django.http import JsonResponse |
| 7 | +from balancer_backend.models.users import RegistrationProfile |
| 8 | +import requests |
| 9 | +import json |
| 10 | +import os |
| 11 | + |
| 12 | +# XXX: remove csrf_exempt usage before production |
| 13 | +from django.views.decorators.csrf import csrf_exempt |
| 14 | + |
| 15 | + |
| 16 | +@csrf_exempt |
| 17 | +def send_verification_email(user): |
| 18 | + subject = 'Activate Your Account' |
| 19 | + activation_key = user.registrationprofile.activation_key |
| 20 | + message = render_to_string('email/verification_email.html', {'activation_key': activation_key, 'user': user}) |
| 21 | + plain_message = strip_tags(message) # This is the plain text version of the HTML content |
| 22 | + |
| 23 | + send_mail(subject, plain_message, 'your_email@example.com', [user.email], html_message=message) |
| 24 | + |
| 25 | +@csrf_exempt |
| 26 | +def register_user(request: str) -> JsonResponse: |
| 27 | + data: dict[str, str] = json.loads(request.body) |
| 28 | + email: str = data["email"] |
| 29 | + password: str = data["password"] |
| 30 | + |
| 31 | + if not email or not password: |
| 32 | + return JsonResponse({"error": "Email and password are required."}) |
| 33 | + |
| 34 | + if RegistrationProfile.objects.filter(user__email=email).exists(): |
| 35 | + return JsonResponse({"error": "Email is already registred."}) |
| 36 | + |
| 37 | + user = User.objects.create_user(email, email, password) |
| 38 | + user.is_active = False |
| 39 | + user.save() |
| 40 | + |
| 41 | + send_verification_email(user) |
| 42 | + |
| 43 | + return JsonResponse({"message": "Registration successful. Check your email for verification."}) |
| 44 | + |
| 45 | +@csrf_exempt |
| 46 | +def activate_account(request, activation_key): |
| 47 | + user = RegistrationProfile.objects.activate_user(activation_key) |
| 48 | + |
| 49 | + if user: |
| 50 | + return JsonResponse({"message": "Account activated successfully."}) |
| 51 | + else: |
| 52 | + return JsonResponse({"error": "Invalid or expired activation key."}) |
0 commit comments