Skip to content

Commit

Permalink
Merge branch 'development' of https://github.com/Proyecto-integrador-…
Browse files Browse the repository at this point in the history
  • Loading branch information
bit-rec98 committed Jun 4, 2024
2 parents 1586c6d + 9ad5925 commit 9a24d19
Show file tree
Hide file tree
Showing 111 changed files with 4,276 additions and 3,565 deletions.
Binary file added Backend/Der.drawio.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added Backend/DiagramaClases.drawio.pdf
Binary file not shown.
Binary file removed Backend/DiagramaClases.png
Binary file not shown.
1 change: 1 addition & 0 deletions Backend/Tienda_Campeones/.vscode/settings.json
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{}
30 changes: 26 additions & 4 deletions Backend/Tienda_Campeones/Tienda_Campeones/settings.py
Original file line number Diff line number Diff line change
Expand Up @@ -37,11 +37,12 @@
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'web',
'rest_framework',
'corsheaders',
'web',
'users',
]
CORS_ORIGIN_ALLOW_ALL = True

MIDDLEWARE = [
'corsheaders.middleware.CorsMiddleware',
'django.middleware.security.SecurityMiddleware',
Expand All @@ -52,6 +53,27 @@
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
CORS_ORIGIN_WHITELIST = [
"http://localhost:4200",
]
CORS_ALLOW_CREDENTIALS = True


AUTH_USER_MODEL = 'users.Usuarios'
REST_FRAMEWORK = {
'DEFAULT_AUTHENTICATION_CLASSES': (
'rest_framework_simplejwt.authentication.JWTAuthentication',
),
'DEFAULT_PERMISSION_CLASSES':(
'rest_framework.permissions.IsAuthenticated',
),
'DEFAULT_PERMISSION_CLASSES':(
'rest_framework.permissions.AllowAny',
)
}
SIMPLE_JWT = {
'USER_ID_FIELD': 'id_usuario',
}

ROOT_URLCONF = 'Tienda_Campeones.urls'

Expand Down Expand Up @@ -80,9 +102,9 @@
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'campeones_del_mundo',
'NAME': 'campeones',
'USER': 'root',
'PASSWORD': 'root',
'PASSWORD': '****',
'HOST': 'localhost',
'PORT': '3306',
'OPTIONS': {
Expand Down
32 changes: 13 additions & 19 deletions Backend/Tienda_Campeones/Tienda_Campeones/urls.py
Original file line number Diff line number Diff line change
@@ -1,22 +1,16 @@
"""
URL configuration for Tienda_Campeones project.
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.2/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path

from django.urls import path,include
from users.views import Login,Logout
from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView
from web.routers import router
urlpatterns = [
path('admin/', admin.site.urls),
]
path('', include(router.urls)),
path('productos/',include('web.routers')),
path('pedidos/',include('web.routers')),
path('usuarios/',include('users.usuarioapi.routers')),
path('logout/', Logout.as_view(), name = 'logout'),
path('login/',Login.as_view(), name = 'login'),
path('api/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'),
path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'),
]
File renamed without changes.
6 changes: 6 additions & 0 deletions Backend/Tienda_Campeones/users/admin.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.contrib import admin
from .models import Usuarios



admin.site.register(Usuarios)
6 changes: 6 additions & 0 deletions Backend/Tienda_Campeones/users/apps.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
from django.apps import AppConfig


class UsuariosConfig(AppConfig):
default_auto_field = 'django.db.models.BigAutoField'
name = 'users'
37 changes: 37 additions & 0 deletions Backend/Tienda_Campeones/users/migrations/0001_initial.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
# Generated by Django 4.2 on 2024-05-30 23:23

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='Usuarios',
fields=[
('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')),
('id_usuario', models.AutoField(primary_key=True, serialize=False)),
('nombre', models.CharField(max_length=50)),
('apellido', models.CharField(max_length=50)),
('email', models.EmailField(max_length=50, unique=True)),
('domicilio', models.CharField(max_length=150)),
('rol', models.CharField(choices=[('CLIENTE', 'Cliente'), ('ADMIN', 'Admin')], max_length=7)),
('is_active', models.BooleanField(default=True)),
('is_staff', models.BooleanField(default=False)),
('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_plural': 'Usuarios',
'db_table': 'usuarios',
},
),
]
Empty file.
52 changes: 52 additions & 0 deletions Backend/Tienda_Campeones/users/models.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
from django.db import models
from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin

class UserManager(BaseUserManager):
def create_user(self, email, password=None, **extra_fields):
if not email:
raise ValueError('El email debe ser proporcionado')
email = self.normalize_email(email)
user = self.model(email=email, **extra_fields)
user.set_password(password)
user.save(using=self._db)
return user

def create_superuser(self, email, password=None, **extra_fields):
extra_fields.setdefault('is_staff', True)
extra_fields.setdefault('is_superuser', True)

return self.create_user(email, password, **extra_fields)

class Usuarios(AbstractBaseUser, PermissionsMixin):
ROLE_CHOICES = [
('CLIENTE', 'Cliente'),
('ADMIN', 'Admin'),
]
id_usuario = models.AutoField(primary_key=True)
nombre = models.CharField(max_length=50)
apellido = models.CharField(max_length=50)
email = models.EmailField(unique=True, max_length=50)
domicilio = models.CharField(max_length=150)
rol = models.CharField(max_length=7, choices=ROLE_CHOICES)
is_active = models.BooleanField(default=True)
is_staff = models.BooleanField(default=False)

objects = UserManager()

USERNAME_FIELD = 'email'
REQUIRED_FIELDS = ['nombre', 'apellido']

class Meta:
db_table = 'usuarios'
verbose_name_plural = 'Usuarios'

def __str__(self):
return f"Usuario ID: {self.id_usuario}, Nombre: {self.nombre}, Apellido: {self.apellido}, Email: {self.email}, Domicilio: {self.domicilio}, Rol: {self.rol}"

def save(self, *args, **kwargs):
if self.rol == 'ADMIN':
self.is_staff = True
else:
self.is_staff = False
super(Usuarios, self).save(*args, **kwargs)

3 changes: 3 additions & 0 deletions Backend/Tienda_Campeones/users/tests.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
from django.test import TestCase

# Create your tests here.
Empty file.
24 changes: 24 additions & 0 deletions Backend/Tienda_Campeones/users/usuarioapi/api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework import status
from users.usuarioapi.usuario_serializers import *
from users.models import Usuarios

class UsuarioViewSet(viewsets.ModelViewSet):
serializer_class = UsuarioSerializer
queryset = Usuarios.objects.all()

# def get_serializer_class(self):
# if self.action == 'list':
# UsuarioListSerializer
# UsuarioSerializer

def get_queryset(self, pk=None):
if pk is None:
return self.get_serializer().Meta.model.objects.filter(is_active=True)
return self.get_serializer().Meta.model.objects.filter(id_usuario=pk, is_active=True).first()

# def list(self, request):
# users = self.get_queryset()
# users_serializer = self.list_serializer_class(users, many=True)
# return Response(users_serializer.data, status=status.HTTP_200_OK)
7 changes: 7 additions & 0 deletions Backend/Tienda_Campeones/users/usuarioapi/routers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
from rest_framework.routers import DefaultRouter
from users.usuarioapi.api import UsuarioViewSet

router = DefaultRouter()
router.register(r'',UsuarioViewSet,basename='usuarios')
#router.register(r'login', LoginViewSet,basename='login')
urlpatterns = router.urls
42 changes: 42 additions & 0 deletions Backend/Tienda_Campeones/users/usuarioapi/usuario_serializers.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
from rest_framework import serializers
from users.models import Usuarios
from rest_framework_simplejwt.serializers import TokenObtainPairSerializer

class CustomTokenObtainPairSerializer(TokenObtainPairSerializer):
pass

class CustomUsuarioSerializer(serializers.ModelSerializer):
class Meta:
model = Usuarios
fields = ['email','password']

class UsuarioSerializer(serializers.ModelSerializer):
class Meta:
model = Usuarios
fields = ['id_usuario', 'nombre', 'apellido', 'email', 'domicilio', 'password']
extra_kwargs = {
'password': {'write_only': True}
}

def create(self, validated_data):
usuario = Usuarios(**validated_data)
usuario.set_password(validated_data['password'])
usuario.rol = 'CLIENTE'
usuario.save()
return usuario

class PasswordSerializer(serializers.Serializer):
password = serializers.CharField(max_length=128, min_length=6, write_only=True)
password2 = serializers.CharField(max_length=128, min_length=6, write_only=True)

def validate(self, data):
if data['password'] != data['password2']:
raise serializers.ValidationError(
{'password':'Debe ingresar ambas contraseñas iguales'}
)
return data

class UsuarioListSerializer(serializers.ModelSerializer):
class Meta:
model = Usuarios
fields = ['nombre', 'apellido', 'email', 'domicilio','rol']
45 changes: 45 additions & 0 deletions Backend/Tienda_Campeones/users/views.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
from rest_framework import viewsets
from rest_framework.request import Request
from users.models import Usuarios
from rest_framework.response import Response
from rest_framework import status
from rest_framework.generics import GenericAPIView
from rest_framework_simplejwt.views import TokenObtainPairView
from rest_framework.permissions import IsAuthenticated
from users.usuarioapi.usuario_serializers import *
from django.contrib.auth import authenticate
from rest_framework_simplejwt.tokens import RefreshToken

class Login(TokenObtainPairView):
serializer_class = CustomTokenObtainPairSerializer

def post(self,request,*args, **kwargs):
email = request.data.get('email', '')
password = request.data.get('password', '')

if not email or not password:
return Response({'error': 'Campos obligatorios'}, status=status.HTTP_400_BAD_REQUEST)

usuario =authenticate(email=email,
password=password)
if usuario:
login_serializer = self.serializer_class(data=request.data)
if login_serializer.is_valid():
usuario_serializer = CustomUsuarioSerializer(usuario)
return Response({
'token': login_serializer.validated_data.get('access'),
'refresh_token': login_serializer.validated_data.get('refresh'),
'usuario': usuario_serializer.data,
'message': 'Inicio de sesión exitoso'
}, status=status.HTTP_200_OK)

return Response({'error': 'Mail o contraseña incorrectos'}, status=status.HTTP_400_BAD_REQUEST)

class Logout(GenericAPIView):
def post(self,request,*args,**kwargs):
email = request.data.get('email', '')
usuario = Usuarios.objects.filter(email=email).first()
if usuario.exists():
RefreshToken.for_usuario(usuario)
return Response({'message':'Sesion cerrada correctamente'},status=status.HTTP_200_OK)
return Response({'error': 'No existe este mail'},status=status.HTTP_400_BAD_REQUEST)
Loading

0 comments on commit 9a24d19

Please sign in to comment.