ft_transcendence/accounts/views/login.py

31 lines
1.1 KiB
Python

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, HttpRequest, JsonResponse
from django.contrib.auth.models import User
from django.contrib.auth import authenticate, login, logout
from django.contrib.auth.decorators import login_required
from django.db.models.query import QuerySet
from ..status_code import *
from ..forms.login import LoginForm
class LoginView(View):
def get(self, request: HttpRequest):
if request.user.is_authenticated:
logout(request)
return render(request, "login.html", {"form": LoginForm})
def post(self, request: HttpRequest):
if request.user.is_authenticated:
logout(request)
form: LoginForm = LoginForm(request.POST)
if not form.is_valid():
return JsonResponse(form.errors)
user: User = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password'])
if user is None:
return JsonResponse({'user': [USER_INVALID]})
login(request, user)
return HttpResponse(USER_LOGGED)