This commit is contained in:
AdrienLSH
2024-05-14 08:50:37 +02:00
parent 95f0097ce5
commit e308e8f012
231 changed files with 70 additions and 22 deletions

View File

3
django/accounts/admin.py Normal file
View File

@ -0,0 +1,3 @@
from django.contrib import admin
# Register your models here.

6
django/accounts/apps.py Normal file
View File

@ -0,0 +1,6 @@
from django.apps import AppConfig
class AccountsConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'accounts'

View File

@ -0,0 +1,39 @@
# SOME DESCRIPTIVE TITLE.
# Copyright (C) YEAR THE PACKAGE'S COPYRIGHT HOLDER
# This file is distributed under the same license as the PACKAGE package.
# FIRST AUTHOR <EMAIL@ADDRESS>, YEAR.
#
#, fuzzy
msgid ""
msgstr ""
"Project-Id-Version: PACKAGE VERSION\n"
"Report-Msgid-Bugs-To: \n"
"POT-Creation-Date: 2024-03-20 10:25+0100\n"
"PO-Revision-Date: YEAR-MO-DA HO:MI+ZONE\n"
"Last-Translator: FULL NAME <EMAIL@ADDRESS>\n"
"Language-Team: LANGUAGE <LL@li.org>\n"
"Language: \n"
"MIME-Version: 1.0\n"
"Content-Type: text/plain; charset=UTF-8\n"
"Content-Transfer-Encoding: 8bit\n"
"Plural-Forms: nplurals=2; plural=(n > 1);\n"
#: serializers/update_password.py:19
msgid "Current password is incorrect."
msgstr "Mot de passe actuel incorrect."
#: serializers/update_password.py:24
msgid "The password does not match."
msgstr "Le mot de passe ne correspond pas."
#: serializers/update_password.py:31 serializers/update_user.py:15
msgid "You dont have permission for this user."
msgstr "Vous n'avez pas de permissions pour cet utilisateur."
#: views/delete.py:19
msgid "Password incorrect."
msgstr "Mot de passe incorrect."
#: views/login.py:23
msgid "Invalid username or password."
msgstr "Nom d'utilisateur ou mot de passe incorect."

View File

@ -0,0 +1,12 @@
from rest_framework.serializers import Serializer, CharField
from django.contrib.auth import authenticate
from django.core.exceptions import ValidationError
class LoginSerializer(Serializer):
username = CharField()
password = CharField()
def get_user(self, data):
user = authenticate(username=data['username'], password=data['password'])
return user

View File

@ -0,0 +1,12 @@
from rest_framework.serializers import ModelSerializer
from django.contrib.auth.models import User
class RegisterSerialiser(ModelSerializer):
class Meta:
model = User
fields = ['username', 'password']
def create(self, data):
user_obj = User.objects.create_user(username=data['username'], password=data['password'])
user_obj.save()
return user_obj

View File

@ -0,0 +1,37 @@
from rest_framework.serializers import ModelSerializer, ValidationError
from rest_framework.fields import CharField
from django.contrib.auth.models import User
from django.contrib.auth import login
from django.utils.translation import gettext as _
class UpdatePasswordSerializer(ModelSerializer):
current_password = CharField(write_only=True, required=True)
new_password = CharField(write_only=True, required=True)
new_password2 = CharField(write_only=True, required=True)
class Meta:
model = User
fields = ['current_password', 'new_password', 'new_password2']
def validate_current_password(self, value):
if not self.instance.check_password(value):
raise ValidationError(_('Current password is incorrect.'))
return value
def validate(self, data):
if data['new_password'] != data['new_password2']:
raise ValidationError({'new_password2': _('The password does not match.')})
return data
def update(self, instance, validated_data):
user = self.context['request'].user
if user.pk != instance.pk:
raise ValidationError({'authorize': _('You dont have permission for this user.')})
instance.set_password(validated_data['new_password'])
instance.save()
login(self.context['request'], instance)
return instance

View File

@ -0,0 +1,20 @@
from rest_framework.serializers import ModelSerializer, ValidationError
from django.contrib.auth.models import User
from django.utils.translation import gettext as _
class UpdateUserSerializer(ModelSerializer):
class Meta:
model = User
fields = ['username']
def update(self, instance, validated_data):
user = self.context['request'].user
if user.pk != instance.pk:
raise ValidationError({'authorize': _('You dont have permission for this user.')})
instance.username = validated_data.get('username', instance.username)
instance.save()
return instance

View File

@ -0,0 +1,5 @@
from .register import *
from .login import *
from .logout import *
from .edit import *
from .delete import *

View File

@ -0,0 +1,37 @@
from django.test import TestCase
# Create your tests here.
from django.test.client import Client
from django.http import HttpResponse
from django.contrib.auth.models import User
import uuid
class DeleteTest(TestCase):
def setUp(self):
self.client = Client()
self.url = "/api/accounts/delete"
self.username: str = str(uuid.uuid4())
self.password: str = str(uuid.uuid4())
user: User = User.objects.create_user(username=self.username, password=self.password)
self.client.login(username=self.username, password=self.password)
def test_normal_delete(self):
response: HttpResponse = self.client.delete(self.url, {"password": self.password}, content_type='application/json')
response_text: str = response.content.decode("utf-8")
self.assertEqual(response_text, '"user deleted"')
def test_wrong_pass(self):
response: HttpResponse = self.client.delete(self.url, {"password": "cacaman a frapper"}, content_type='application/json')
errors: dict = eval(response.content)
self.assertDictEqual(errors, {"password": ["Password wrong."]})
def test_no_logged(self):
self.client.logout()
response: HttpResponse = self.client.delete(self.url, {"password": self.password}, content_type='application/json')
errors: dict = eval(response.content)
self.assertDictEqual(errors, {"detail":"Authentication credentials were not provided."})

View File

@ -0,0 +1,49 @@
from django.test import TestCase
# Create your tests here.
from django.test.client import Client
from django.http import HttpResponse
from django.contrib.auth.models import User
import uuid
class EditTest(TestCase):
def setUp(self):
self.client = Client()
self.url = "/api/accounts/edit"
self.username: str = str(uuid.uuid4())
self.password: str = str(uuid.uuid4())
self.new_password: str = str(uuid.uuid4())
User.objects.create_user(username = self.username, password = self.password)
def test_normal(self):
self.client.login(username = self.username, password = self.password)
response: HttpResponse = self.client.patch(self.url, {"current_password": self.password, "new_password": self.new_password, "username": "bozo"}, content_type='application/json')
response_text: str = response.content.decode('utf-8')
self.assertEqual(response_text, '"data has been alterate"')
def test_invalid_current_password(self):
self.client.login(username = self.username, password = self.password)
response: HttpResponse = self.client.patch(self.url, {"current_password": "bozo", "new_password": self.new_password, "username": "bozo"}, content_type='application/json')
errors: dict = eval(response.content)
self.assertDictEqual(errors, {"current_password":["Password is wrong."]})
def test_invalid_new_username_blank(self):
self.client.login(username = self.username, password = self.password)
response: HttpResponse = self.client.patch(self.url, {"current_password": self.password, "username": " "}, content_type='application/json')
errors: dict = eval(response.content)
self.assertDictEqual(errors, {'username': ['This field may not be blank.']})
def test_invalid_new_username_char(self):
self.client.login(username = self.username, password = self.password)
response: HttpResponse = self.client.patch(self.url, {"current_password": self.password, "username": "*&"}, content_type='application/json')
errors: dict = eval(response.content)
self.assertDictEqual(errors, {'username': ['Enter a valid username. This value may contain only letters, numbers, and @/./+/-/_ characters.']})
def test_nologged(self):
response: HttpResponse = self.client.patch(self.url, {"current_password": self.password, "new_password": self.new_password}, content_type='application/json')
errors: dict = eval(response.content)
self.assertDictEqual(errors, {'detail': 'Authentication credentials were not provided.'})

View File

@ -0,0 +1,53 @@
from django.test import TestCase
# Create your tests here.
from django.test.client import Client
from django.contrib.auth.models import User
from django.http import HttpResponse
import uuid
class LoginTest(TestCase):
def setUp(self):
self.client = Client()
self.url = "/api/accounts/login"
self.username: str = str(uuid.uuid4())
self.password: str = str(uuid.uuid4())
User.objects.create_user(username=self.username, password=self.password)
def test_normal_login(self):
response: HttpResponse = self.client.post(self.url, {'username': self.username, 'password': self.password})
response_text = response.content.decode('utf-8')
#self.assertEqual(response_text, 'user connected')
def test_invalid_username(self):
response: HttpResponse = self.client.post(self.url, {"username": self.password, "password": self.password})
errors: dict = eval(response.content)
errors_expected: dict = {'user': ['Username or password wrong.']}
self.assertEqual(errors, errors_expected)
def test_invalid_password(self):
response: HttpResponse = self.client.post(self.url, {"username": self.username, "password": self.username})
errors: dict = eval(response.content)
errors_expected: dict = {'user': ['Username or password wrong.']}
self.assertEqual(errors, errors_expected)
def test_invalid_no_username(self):
response: HttpResponse = self.client.post(self.url, {"password": self.password})
errors: dict = eval(response.content)
errors_expected: dict = {'username': ['This field is required.']}
self.assertEqual(errors, errors_expected)
def test_invalid_no_password(self):
response: HttpResponse = self.client.post(self.url, {"username": self.username})
errors: dict = eval(response.content)
errors_expected: dict = {'password': ['This field is required.']}
self.assertEqual(errors, errors_expected)
def test_invalid_no_password_no_username(self):
response: HttpResponse = self.client.post(self.url, {})
errors: dict = eval(response.content)
errors_expected: dict = {'username': ['This field is required.'], 'password': ['This field is required.']}
self.assertEqual(errors, errors_expected)

View File

@ -0,0 +1,17 @@
from django.test import TestCase
from django.test.client import Client
from django.contrib.auth.models import User
from django.contrib.auth import login
class LoginTest(TestCase):
def setUp(self):
self.client = Client()
self.url = "/api/accounts/logout"
self.client.login()
def test_normal_logout(self):
self.client.post(self.url)
self.assertNotIn('_auth_user_id', self.client.session)

View File

@ -0,0 +1,52 @@
from django.test import TestCase
# Create your tests here.
from rest_framework import status
from django.test.client import Client
from django.contrib.auth.models import User
from django.http import HttpResponse
import uuid
class RegisterTest(TestCase):
def setUp(self):
self.client = Client()
self.url: str = "/api/accounts/register"
self.username: str = str(uuid.uuid4())
self.password: str = str(uuid.uuid4())
def test_normal_register(self):
response: HttpResponse = self.client.post(self.url, {'username': self.username, 'password': self.password})
self.assertEqual(response.status_code, status.HTTP_201_CREATED)
def test_incomplet_form_no_username_no_password(self):
response: HttpResponse = self.client.post(self.url)
errors: dict = eval(response.content)
errors_expected: dict = {'username': ['This field is required.'], 'password': ['This field is required.']}
self.assertEqual(errors, errors_expected)
def test_incomplet_form_no_password(self):
response: HttpResponse = self.client.post(self.url, {"username": self.username})
errors: dict = eval(response.content)
errors_expected: dict = {'password': ['This field is required.']}
self.assertEqual(errors, errors_expected)
def test_incomplet_form_no_username(self):
response: HttpResponse = self.client.post(self.url, {"password": self.password})
errors: dict = eval(response.content)
errors_expected: dict = {}
self.assertEqual(errors, errors_expected)
def test_incomplet_form_no_username(self):
response: HttpResponse = self.client.post(self.url, {"password": self.password})
errors: dict = eval(response.content)
errors_expected: dict = {'username': ['This field is required.']}
self.assertEqual(errors, errors_expected)
def test_already_registered(self):
User(username=self.username, password=self.password).save()
response: HttpResponse = self.client.post(self.url, {'username': self.username, 'password': self.password})
errors: dict = eval(response.content)
errors_expected: dict = {'username': ['A user with that username already exists.']}
self.assertEqual(errors, errors_expected)

13
django/accounts/urls.py Normal file
View File

@ -0,0 +1,13 @@
from django.urls import path
from .views import register, login, logout, delete, logged, update_profile, update_password
urlpatterns = [
path("register", register.RegisterView.as_view(), name="register"),
path("login", login.LoginView.as_view(), name="login"),
path("logout", logout.LogoutView.as_view(), name="logout"),
path("logged", logged.LoggedView.as_view(), name="logged"),
path("delete", delete.DeleteView.as_view(), name="delete"),
path('update_profile', update_profile.UpdateProfileView.as_view(), name='update_profile'),
path('update_password', update_password.UpdatePasswordView.as_view(), name='update_password')
]

View File

@ -0,0 +1,23 @@
from rest_framework.views import APIView
from rest_framework import permissions, status
from rest_framework.response import Response
from django.contrib.auth import logout
from django.http import HttpRequest
from rest_framework.authentication import SessionAuthentication
from django.utils.translation import gettext as _
class DeleteView(APIView):
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
def delete(self, request: HttpRequest):
data: dict = request.data
password: str = data["password"]
if (request.user.check_password(password) is False):
return Response({"password": _("Password incorrect.")},
status.HTTP_401_UNAUTHORIZED)
request.user.delete()
logout(request)
return Response(status=status.HTTP_200_OK)

View File

@ -0,0 +1,14 @@
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions, status
from django.http import HttpRequest
from rest_framework.authentication import SessionAuthentication
class LoggedView(APIView):
permission_classes = (permissions.AllowAny,)
authentication_classes = (SessionAuthentication,)
def get(self, request: HttpRequest):
return Response(status=status.HTTP_200_OK if request.user.is_authenticated else status.HTTP_400_BAD_REQUEST)

View File

@ -0,0 +1,25 @@
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import permissions, status
from django.http import HttpRequest
from django.contrib.auth import login
from rest_framework.authentication import SessionAuthentication
from django.utils.translation import gettext as _
from ..serializers.login import LoginSerializer
class LoginView(APIView):
permission_classes = (permissions.AllowAny,)
authentication_classes = (SessionAuthentication,)
def post(self, request: HttpRequest):
data = request.data
serializer = LoginSerializer(data=data)
serializer.is_valid(raise_exception=True)
user = serializer.get_user(data)
if user is None:
return Response({'login': [_('Invalid username or password.')]}, status.HTTP_401_UNAUTHORIZED)
login(request, user)
return Response({'id': user.pk}, status=status.HTTP_200_OK)

View File

@ -0,0 +1,15 @@
from rest_framework.views import APIView
from django.contrib.auth import logout
from rest_framework import permissions, status
from rest_framework.response import Response
from django.http import HttpRequest
from rest_framework.authentication import SessionAuthentication
class LogoutView(APIView):
permission_classes = (permissions.IsAuthenticated,)
authentication_classes = (SessionAuthentication,)
def get(self, request: HttpRequest):
logout(request)
return Response("user logged out", status.HTTP_200_OK)

View File

@ -0,0 +1,20 @@
from rest_framework import permissions, status
from ..serializers.register import RegisterSerialiser
from rest_framework.views import APIView
from rest_framework.response import Response
from django.http import HttpRequest
from django.contrib.auth import login
class RegisterView(APIView):
permission_classes = (permissions.AllowAny,)
def post(self, request: HttpRequest):
data = request.data
serializer = RegisterSerialiser(data=data)
if serializer.is_valid(raise_exception=True):
user = serializer.create(data)
if user:
login(request, user)
return Response("user created", status=status.HTTP_201_CREATED)
return Response(status=status.HTTP_400_BAD_REQUEST)

View File

@ -0,0 +1,13 @@
from ..serializers.update_password import UpdatePasswordSerializer
from rest_framework.generics import UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth.models import User
class UpdatePasswordView(UpdateAPIView):
queryset = User.objects.all()
permission_classes = (IsAuthenticated,)
serializer_class = UpdatePasswordSerializer
def get_object(self):
return self.queryset.get(pk=self.request.user.pk)

View File

@ -0,0 +1,14 @@
from ..serializers.update_user import UpdateUserSerializer
from rest_framework.generics import UpdateAPIView
from rest_framework.permissions import IsAuthenticated
from django.contrib.auth.models import User
class UpdateProfileView(UpdateAPIView):
queryset = User.objects.all()
permission_classes = (IsAuthenticated,)
serializer_class = UpdateUserSerializer
def get_object(self):
return self.queryset.get(pk=self.request.user.pk)