import json from django.shortcuts import render 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() @ratelimit(method="POST", block=True, rate="1/m") 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) @ratelimit(method="POST", block=True, rate="1/m") 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 return render_to_json(response) def logout(request): if request.user.is_authenticated: django.contrib.auth.logout(request) redirect('/')