This commit is contained in:
2025-05-24 13:47:37 +02:00
parent 54d8cb9846
commit 635ad35c55
11 changed files with 319 additions and 12 deletions

View File

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

View File

@@ -0,0 +1,47 @@
# Generated by Django 5.2.1 on 2025-05-23 03:58
import django.contrib.auth.models
import django.contrib.auth.validators
import django.utils.timezone
from django.db import migrations, models
class Migration(migrations.Migration):
initial = True
dependencies = [
('auth', '0012_alter_user_first_name_max_length'),
]
operations = [
migrations.CreateModel(
name='User',
fields=[
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('password', models.CharField(max_length=128, verbose_name='password')),
('last_login', models.DateTimeField(blank=True, null=True, verbose_name='last login')),
('is_superuser', models.BooleanField(default=False, help_text='Designates that this user has all permissions without explicitly assigning them.', verbose_name='superuser status')),
('username', models.CharField(error_messages={'unique': 'A user with that username already exists.'}, help_text='Required. 150 characters or fewer. Letters, digits and @/./+/-/_ only.', max_length=150, unique=True, validators=[django.contrib.auth.validators.UnicodeUsernameValidator()], verbose_name='username')),
('first_name', models.CharField(blank=True, max_length=150, verbose_name='first name')),
('last_name', models.CharField(blank=True, max_length=150, verbose_name='last name')),
('email', models.EmailField(blank=True, max_length=254, verbose_name='email address')),
('is_staff', models.BooleanField(default=False, help_text='Designates whether the user can log into this admin site.', verbose_name='staff status')),
('is_active', models.BooleanField(default=True, help_text='Designates whether this user should be treated as active. Unselect this instead of deleting accounts.', verbose_name='active')),
('date_joined', models.DateTimeField(default=django.utils.timezone.now, verbose_name='date joined')),
('can_be_contacted', models.BooleanField(default=False)),
('can_data_be_shared', models.BooleanField(default=False)),
('age', models.IntegerField()),
('groups', models.ManyToManyField(blank=True, help_text='The groups this user belongs to. A user will get all permissions granted to each of their groups.', related_name='user_set', related_query_name='user', to='auth.group', verbose_name='groups')),
('user_permissions', models.ManyToManyField(blank=True, help_text='Specific permissions for this user.', related_name='user_set', related_query_name='user', to='auth.permission', verbose_name='user permissions')),
],
options={
'verbose_name': 'user',
'verbose_name_plural': 'users',
'abstract': False,
},
managers=[
('objects', django.contrib.auth.models.UserManager()),
],
),
]

View File

@@ -0,0 +1,18 @@
# Generated by Django 5.2.1 on 2025-05-23 04:00
from django.db import migrations, models
class Migration(migrations.Migration):
dependencies = [
('authentication', '0001_initial'),
]
operations = [
migrations.AlterField(
model_name='user',
name='age',
field=models.IntegerField(null=True),
),
]

View File

@@ -5,10 +5,8 @@ from django.contrib.auth.models import AbstractUser, Group
class User(AbstractUser):
can_be_contacted = models.BooleanField(default=False)
can_data_be_shared = models.BooleanField(default=False)
age = models.IntegerField()
age = models.IntegerField(null=True)
def __str__(self):
return self.username

View File

@@ -0,0 +1,66 @@
from rest_framework.serializers import ModelSerializer, SerializerMethodField, ValidationError
from rest_framework import serializers
from support.models import Project, Issue, Comment, Contributor
from authentication.models import User
class UserSerializer(ModelSerializer):
class Meta:
model = User
fields = ['id', 'username', 'email', 'age', 'can_be_contacted', 'can_data_be_shared']
class UserUpdateSerializer(ModelSerializer):
class Meta:
model = User
fields = ['email', 'can_be_contacted', 'can_data_be_shared']
class UserRegisterSerializer(ModelSerializer):
password2 = serializers.CharField(style={'input-type': 'password'}, write_only=True)
class Meta:
model = User
fields = ['username', 'email', 'password', 'password2', 'age', 'can_be_contacted', 'can_data_be_shared']
extra_kwargs = {'password': {'write_only': True}}
def validate(self, data):
if data['password'] != data['password2']:
raise ValidationError("Passwords don't match.")
return data
def validate_age(self, value):
if value < 15:
raise ValidationError("You must be older than 15")
return value
def create(self, validated_data):
"""
Create and return a new `User` instance, given the validated data.
"""
#if self.validate(validated_data):
user = User.objects.create_user(
username=validated_data['username'],
email=validated_data['email'],
password=validated_data['password'],
age=validated_data['age'],
can_be_contacted=validated_data['can_be_contacted'],
can_data_be_shared=validated_data['can_data_be_shared'],
)
return user
class PasswordUpdateSerializer(ModelSerializer):
old_password = serializers.CharField(required=True)
new_password = serializers.CharField(required=True)
class Meta:
model = User
fields = ['old_password', 'new_password']

View File

@@ -1,3 +1,87 @@
from django.contrib.auth import update_session_auth_hash
from django.shortcuts import render
from django.utils.autoreload import raise_last_exception
from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet, ReadOnlyModelViewSet
from rest_framework import status
from rest_framework.permissions import IsAuthenticated
from authentication.models import User
from authentication.serializers import (UserSerializer,
UserUpdateSerializer,
UserRegisterSerializer,
PasswordUpdateSerializer)
class UserCreateView(APIView):
"""
Allow user registration for anyone
"""
#TODELETE : for testing purpose
def get(self, request, *args, **kwargs):
user = User.objects.all()
print(request.user)
serializer = UserSerializer(user, many=True)
print(serializer.data)
#if serializer.is_valid():
return Response(serializer.data)
#return Response("prout", status=status.HTTP_226_IM_USED)
def post(self, request):
serializer = UserRegisterSerializer(data=request.data)
if serializer.is_valid(raise_exception=True):
serializer.save()
response = {
"message": "User created successfully",
"data": serializer.data
}
return Response(data=response, status=status.HTTP_201_CREATED)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class PasswordUpdateView(APIView):
permission_classes = [IsAuthenticated]
def put(self, request):
user = request.user
serializer = PasswordUpdateSerializer(data=request.data)
if serializer.is_valid():
if not user.check_password(serializer.data.get("old_password")):
return Response({"old_password":"Wrong password"}, status=status.HTTP_400_BAD_REQUEST)
user.set_password(serializer.data.get('new_password'))
user.save()
update_session_auth_hash(request, user)
return Response(serializer.errors, status=status.HTTP_204_NO_CONTENT)
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
class UserView(APIView):
permission_classes = [IsAuthenticated]
def get(self, request, *args, **kwargs):
return Response(UserSerializer(request.user).data)
def put(self, request):
user = request.user
serializer = UserUpdateSerializer(user, data=request.data)
print(serializer.initial_data)
if serializer.is_valid():
serializer.save()
return Response("Data updated", status=status.HTTP_201_CREATED)
return Response("Error", status=status.HTTP_400_BAD_REQUEST)
def delete(self, request):
user = request.user
username = request.user.username
user.delete()
return Response(f"User {username} deleted.", status=status.HTTP_204_NO_CONTENT)
class UserRegistrationViewSet(ModelViewSet):
#serializer_class = UserRegistrationSerializer
def get_queryset(self):
return User.objects.get(self.request.user)
# Create your views here.