38 lines
1.5 KiB
Python
Executable File
38 lines
1.5 KiB
Python
Executable File
import json
|
|
import re
|
|
from django.contrib.auth import authenticate, login as auth_login
|
|
from django.http import JsonResponse
|
|
from django.views.decorators.csrf import csrf_exempt
|
|
from django.shortcuts import render, redirect
|
|
from django.contrib.auth.decorators import login_required
|
|
from allauth.account.auth_backends import AuthenticationBackend
|
|
from .models import User
|
|
|
|
@csrf_exempt
|
|
def admin_login_view(request):
|
|
if request.user.is_authenticated:
|
|
return redirect('admin_home')
|
|
|
|
if request.method == 'POST':
|
|
try:
|
|
body = json.loads(request.body)
|
|
username = body.get('username')
|
|
password = body.get('password')
|
|
user = authenticate(request, username=username, password=password)
|
|
if user is not None:
|
|
user.backend = 'allauth.account.auth_backends.AuthenticationBackend'
|
|
auth_login(request, user)
|
|
return JsonResponse({'code': 200, 'message': '登录成功'})
|
|
else:
|
|
return JsonResponse({'code': 400, 'message': '用户名或密码错误'})
|
|
except json.JSONDecodeError:
|
|
return JsonResponse({'code': 400, 'message': '无效的请求数据'})
|
|
except Exception as e:
|
|
return JsonResponse({'code': 500, 'message': f'服务器内部错误: {str(e)}'})
|
|
|
|
return render(request, 'admin/admin_login.html')
|
|
|
|
@login_required
|
|
def admin_home_view(request):
|
|
return render(request, 'admin/home.html')
|