$ django-admin startproject authentication_example $ cd authentication_example $ pip install django-allauth django-rest-auth python # settings.py INSTALLED_APPS = [ ... 'django.contrib.sites', 'allauth', 'allauth.account', 'rest_auth', 'rest_auth.registration', ... ] SITE_ID = 1 REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ) $ python manage.py migrate $ python manage.py createsuperuser python # urls.py from django.urls import include, path urlpatterns = [ ... path('api/accounts/', include('rest_auth.urls')), path('api/accounts/registration/', include('rest_auth.registration.urls')), ... ] $ python manage.py runserver bash $ python manage.py startapp authentication_app python # authentication_app/views.py from rest_framework.decorators import api_view, permission_classes from rest_framework.response import Response from rest_framework.permissions import AllowAny from allauth.account.models import EmailConfirmation, EmailConfirmationHMAC @api_view(['POST']) @permission_classes([AllowAny]) def register(request): email = request.data.get('email') password = request.data.get('password') if email and password: user = User.objects.create_user(email=email, password=password) email_confirmation = EmailConfirmation.create(user) email_confirmation.sent = timezone.now() email_confirmation.sent_from = settings.DEFAULT_FROM_EMAIL email_confirmation.sent_to = email email_confirmation.save() return Response({'detail': 'User registered successfully. Please check your email for confirmation instructions.'}) else: return Response({'detail': 'Please provide both email and password.'}) @api_view(['POST']) @permission_classes([AllowAny]) def login(request): email = request.data.get('email') password = request.data.get('password') if email and password: user = User.objects.filter(email=email).first() if user and user.check_password(password): return Response({'detail': 'User logged in successfully.'}) else: return Response({'detail': 'Invalid email or password.'}) else: return Response({'detail': 'Please provide both email and password.'}) python # authentication_app/urls.py from django.urls import path from .views import register, login urlpatterns = [ path('register/', register, name='register'), path('login/', login, name='login'), ] python # urls.py from django.urls import include, path urlpatterns = [ ... path('api/accounts/', include('authentication_app.urls')), ... ]


上一篇:
下一篇:
切换中文