from django.contrib.auth.models import User
from django.core.mail import send_mail
from django.template.loader import render_to_string
from django.utils.safestring import mark_safe
from rest_framework_jwt.settings import api_settings
from rest_framework.response import Response
from rest_framework.views import APIView
from rest_framework import status
import jwt
# 创建 JWT 配置实例
jwt_payload_handler = api_settings.JWT_PAYLOAD_HANDLER
jwt_encode_handler = api_settings.JWT_ENCODE_HANDLER
class RegisterView(APIView):
def post(self, request):
email = request.data.get('email')
username = request.data.get('username')
password = request.data.get('password')
# 创建用户
user = User.objects.create_user(username=username, password=password, email=email)
user.is_active = False # 设置用户未激活状态
user.save()
# 发送邮箱进行激活
current_site = request.META['HTTP_HOST']
relative_activate_url = "/activate/" + user.email_token
activate_url = 'http://' + current_site + relative_activate_url
message = render_to_string('activation_email.html', {
'user': user,
'activate_url': activate_url
})
send_mail('Activate Your MySite Account', 'Hello', 'noreply@example.com', [email], html_message=mark_safe(message))
return Response({'detail': '注册成功,请检查您的邮箱进行激活。'}, status=status.HTTP_201_CREATED)
class ActivateView(APIView):
def get(self, request, email):
user = User.objects.get(email=email)
user.is_active = True
user.email_token = ''
user.save()
return Response({'detail': '账户已激活,请登录。'}, status=status.HTTP_200_OK)
class LoginView(APIView):
def post(self, request):
email = request.data.get('email')
password = request.data.get('password')
user = User.objects.filter(email=email).first()
if user and user.check_password(password) and user.is_active:
payload = jwt_payload_handler(user)
token = jwt_encode_handler(payload)
return Response({'token': token}, status=status.HTTP_200_OK)
return Respo
评论已关闭