phantasmobile/app/user/views.py
2023-07-26 11:50:09 +02:00

77 lines
2.7 KiB
Python

import json
from django.shortcuts import render
from django.shortcuts import redirect
from django.conf import settings
import django.contrib.auth
from django.contrib.auth import get_user_model
from ..item.utils import render_to_json
from ..utils import default_context
from brake.decorators import ratelimit
User = get_user_model()
@ratelimit(method="POST", block=True, rate="5/m")
def register(request):
response = {}
if request.method == "POST":
data = json.loads(request.body)
if User.objects.filter(username__iexact=data['username']).exists():
response['error'] = 'username not allowed'
elif User.objects.filter(email__iexact=data['email']).exists():
response['error'] = 'username not allowed'
elif not data['password']:
response['error'] = 'password too simple'
if not response:
user = User(username=data['username'], email=data['email'].lower())
user.set_password(data['password'])
user.is_active = True
user.save()
user = django.contrib.auth.authenticate(username=data['username'], password=data['password'])
django.contrib.auth.login(request, user)
response['user'] = user.username
return render_to_json(response)
else:
context = default_context(request)
return render(request, 'register.html', context)
@ratelimit(method="POST", block=True, rate="5/m")
def login(request):
context = default_context(request)
response = {}
request_type = 'json'
if request.method == "POST":
if "username" in request.POST and "password" in request.POST:
data = request.POST
request_type = 'html'
else:
data = json.loads(request.body)
user = django.contrib.auth.authenticate(username=data['username'], password=data['password'])
if user is not None and user.is_active:
django.contrib.auth.login(request, user)
response['user'] = user.username
if request_type == 'html':
return redirect('/')
else:
response['error'] = 'login failed'
if request_type == 'html':
context['error'] = response['error']
return render(request, 'login.html', context)
return render_to_json(response)
else:
if request.user.is_authenticated:
return redirect('/')
return render(request, 'login.html', context)
def logout(request):
if request.user.is_authenticated:
django.contrib.auth.logout(request)
if request.method == "POST":
data = json.loads(request.body)
return render_to_json({})
return redirect('/')