phantasmobile/app/user/views.py

56 lines
1.8 KiB
Python
Raw Normal View History

2023-07-24 11:05:45 +00:00
import json
2023-07-15 07:30:36 +00:00
from django.shortcuts import render
2023-07-24 11:05:45 +00:00
from django.shortcuts import redirect
import django.contrib.auth
from django.contrib.auth import get_user_model
from ..item.utils import render_to_json
from brake.decorators import ratelimit
User = get_user_model()
2023-07-24 21:00:43 +00:00
@ratelimit(method="POST", block=True, rate="5/m")
2023-07-24 11:05:45 +00:00
def register(request):
response = {}
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)
2023-07-24 21:00:43 +00:00
@ratelimit(method="POST", block=True, rate="5/m")
2023-07-24 11:05:45 +00:00
def login(request):
response = {}
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
2023-07-24 21:00:43 +00:00
else:
response['error'] = 'login failed'
2023-07-24 11:05:45 +00:00
return render_to_json(response)
2023-07-15 07:30:36 +00:00
2023-07-24 11:05:45 +00:00
def logout(request):
if request.user.is_authenticated:
django.contrib.auth.logout(request)
2023-07-24 21:00:43 +00:00
if request.method == "POST":
data = json.loads(request.body)
return render_to_json({})
return redirect('/')