ft_transcendence/accounts/views/login.py

31 lines
1.1 KiB
Python
Raw Normal View History

from django.shortcuts import render
from django.views import View
from django.http import HttpResponse, HttpRequest, JsonResponse
from django.contrib.auth.models import User
2023-11-03 16:33:48 -04:00
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 *
2023-10-25 10:10:23 -04:00
from ..forms.login import LoginForm
2023-10-25 10:10:23 -04:00
class LoginView(View):
def get(self, request: HttpRequest):
if request.user.is_authenticated:
logout(request)
2023-10-25 10:10:23 -04:00
return render(request, "login.html", {"form": LoginForm})
def post(self, request: HttpRequest):
if request.user.is_authenticated:
logout(request)
2023-10-25 10:10:23 -04:00
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)