feat: agrega rol 'publico' con UserProfile y permisos diferenciados
- Crea modelo UserProfile (OneToOne con User) con user_type: publico/user/administrator - Señal post_save que crea UserProfile automáticamente al crear User - UserSerializer.get_role() lee desde profile.user_type - Nuevos permisos: IsNotPublico, IsPublico y actualiza IsAdministrator - IsNotPublico restringe acceso a vistas de gestión (productos, clientes, ventas) - CatalogSaleView.create permite publico; otras acciones requieren IsNotPublico - UserProfile inline en admin de Usuarios - Data migration para backfill de usuarios existentes
This commit is contained in:
@@ -1,3 +1,23 @@
|
||||
from django.contrib import admin
|
||||
from django.contrib.auth.models import User
|
||||
from django.contrib.auth.admin import UserAdmin
|
||||
|
||||
# Register your models here.
|
||||
from .models import UserProfile
|
||||
|
||||
|
||||
class UserProfileInline(admin.StackedInline):
|
||||
model = UserProfile
|
||||
can_delete = False
|
||||
|
||||
|
||||
class CustomUserAdmin(UserAdmin):
|
||||
inlines = [UserProfileInline]
|
||||
|
||||
def get_inline_instances(self, request, obj=None):
|
||||
if not obj:
|
||||
return []
|
||||
return super().get_inline_instances(request, obj)
|
||||
|
||||
|
||||
admin.site.unregister(User)
|
||||
admin.site.register(User, CustomUserAdmin)
|
||||
|
||||
@@ -3,3 +3,6 @@ from django.apps import AppConfig
|
||||
|
||||
class UsersConfig(AppConfig):
|
||||
name = 'users'
|
||||
|
||||
def ready(self):
|
||||
import users.signals # noqa
|
||||
|
||||
25
tienda_ilusion/users/migrations/0001_initial.py
Normal file
25
tienda_ilusion/users/migrations/0001_initial.py
Normal file
@@ -0,0 +1,25 @@
|
||||
# Generated by Django 5.0.6 on 2026-06-22 17:26
|
||||
|
||||
import django.db.models.deletion
|
||||
from django.conf import settings
|
||||
from django.db import migrations, models
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
initial = True
|
||||
|
||||
dependencies = [
|
||||
migrations.swappable_dependency(settings.AUTH_USER_MODEL),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.CreateModel(
|
||||
name='UserProfile',
|
||||
fields=[
|
||||
('id', models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
|
||||
('user_type', models.CharField(choices=[('publico', 'Público'), ('user', 'Usuario'), ('administrator', 'Administrador')], default='user', max_length=20)),
|
||||
('user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='profile', to=settings.AUTH_USER_MODEL)),
|
||||
],
|
||||
),
|
||||
]
|
||||
@@ -0,0 +1,24 @@
|
||||
from django.db import migrations
|
||||
|
||||
|
||||
def backfill_user_profiles(apps, schema_editor):
|
||||
User = apps.get_model("auth", "User")
|
||||
UserProfile = apps.get_model("users", "UserProfile")
|
||||
for user in User.objects.all():
|
||||
UserProfile.objects.get_or_create(
|
||||
user=user,
|
||||
defaults={
|
||||
"user_type": "administrator" if user.is_staff else "user",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
class Migration(migrations.Migration):
|
||||
|
||||
dependencies = [
|
||||
('users', '0001_initial'),
|
||||
]
|
||||
|
||||
operations = [
|
||||
migrations.RunPython(backfill_user_profiles, migrations.RunPython.noop),
|
||||
]
|
||||
@@ -1,3 +1,19 @@
|
||||
from django.db import models
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
# Create your models here.
|
||||
|
||||
class UserProfile(models.Model):
|
||||
USER_TYPE_CHOICES = [
|
||||
("publico", "Público"),
|
||||
("user", "Usuario"),
|
||||
("administrator", "Administrador"),
|
||||
]
|
||||
user = models.OneToOneField(
|
||||
User, on_delete=models.CASCADE, related_name="profile"
|
||||
)
|
||||
user_type = models.CharField(
|
||||
max_length=20, choices=USER_TYPE_CHOICES, default="user"
|
||||
)
|
||||
|
||||
def __str__(self):
|
||||
return f"{self.user.username} - {self.user_type}"
|
||||
|
||||
@@ -1,13 +1,25 @@
|
||||
from django.contrib.auth.models import User
|
||||
from rest_framework import serializers
|
||||
|
||||
from .models import UserProfile
|
||||
|
||||
|
||||
class UserSerializer(serializers.ModelSerializer):
|
||||
role = serializers.SerializerMethodField()
|
||||
|
||||
class Meta:
|
||||
model = User
|
||||
fields = ('id', 'username', 'email', 'first_name', 'last_name', 'role')
|
||||
fields = (
|
||||
"id",
|
||||
"username",
|
||||
"email",
|
||||
"first_name",
|
||||
"last_name",
|
||||
"role",
|
||||
)
|
||||
|
||||
def get_role(self, obj):
|
||||
return 'administrator' if obj.is_staff else 'user'
|
||||
try:
|
||||
return obj.profile.user_type
|
||||
except UserProfile.DoesNotExist:
|
||||
return "administrator" if obj.is_staff else "user"
|
||||
|
||||
12
tienda_ilusion/users/signals.py
Normal file
12
tienda_ilusion/users/signals.py
Normal file
@@ -0,0 +1,12 @@
|
||||
from django.db.models.signals import post_save
|
||||
from django.dispatch import receiver
|
||||
from django.contrib.auth.models import User
|
||||
|
||||
from .models import UserProfile
|
||||
|
||||
|
||||
@receiver(post_save, sender=User)
|
||||
def create_user_profile(sender, instance, created, **kwargs):
|
||||
if created:
|
||||
user_type = "administrator" if instance.is_staff else "user"
|
||||
UserProfile.objects.create(user=instance, user_type=user_type)
|
||||
@@ -4,6 +4,8 @@ from django.contrib.auth.models import User
|
||||
from rest_framework.test import APIClient
|
||||
from rest_framework_simplejwt.tokens import RefreshToken
|
||||
|
||||
from .models import UserProfile
|
||||
|
||||
|
||||
class MeEndpointTests(TestCase):
|
||||
def setUp(self):
|
||||
@@ -49,7 +51,6 @@ class MeEndpointTests(TestCase):
|
||||
username='regular',
|
||||
email='regular@example.com',
|
||||
password='regularpass',
|
||||
is_staff=False
|
||||
)
|
||||
|
||||
refresh = RefreshToken.for_user(regular_user)
|
||||
@@ -87,6 +88,31 @@ class MeEndpointTests(TestCase):
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json()['role'], 'administrator')
|
||||
|
||||
def test_publico_user_role_is_publico(self):
|
||||
"""
|
||||
Verifica que un usuario con user_type='publico' recibe role 'publico'.
|
||||
"""
|
||||
publico_user = User.objects.create_user(
|
||||
username='publico',
|
||||
email='publico@example.com',
|
||||
password='publicopass',
|
||||
)
|
||||
profile = UserProfile.objects.get(user=publico_user)
|
||||
profile.user_type = 'publico'
|
||||
profile.save()
|
||||
|
||||
refresh = RefreshToken.for_user(publico_user)
|
||||
access_token = str(refresh.access_token)
|
||||
|
||||
client = APIClient()
|
||||
client.credentials(HTTP_AUTHORIZATION=f'Bearer {access_token}')
|
||||
|
||||
url = reverse('current-user')
|
||||
response = client.get(url)
|
||||
|
||||
self.assertEqual(response.status_code, 200)
|
||||
self.assertEqual(response.json()['role'], 'publico')
|
||||
|
||||
def test_me_endpoint_requires_authentication(self):
|
||||
"""
|
||||
Sin token el endpoint debe devolver 401 Unauthorized.
|
||||
|
||||
Reference in New Issue
Block a user