Initial commit: Plataforma de Economía
Features: - React 18 + TypeScript frontend with Vite - Go + Gin backend API - PostgreSQL database - JWT authentication with refresh tokens - User management (admin panel) - Docker containerization - Progress tracking system - 4 economic modules structure Fixed: - Login with username or email - User creation without required email - Database nullable timestamps - API response field naming
This commit is contained in:
47
backend/internal/config/config.go
Normal file
47
backend/internal/config/config.go
Normal file
@@ -0,0 +1,47 @@
|
||||
package config
|
||||
|
||||
import (
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
DBHost string
|
||||
DBPort int
|
||||
DBUser string
|
||||
DBPassword string
|
||||
DBName string
|
||||
|
||||
JWTSecret string
|
||||
JWTExpirationHours int
|
||||
RefreshExpDays int
|
||||
}
|
||||
|
||||
func Load() *Config {
|
||||
return &Config{
|
||||
DBHost: getEnv("DB_HOST", "localhost"),
|
||||
DBPort: getEnvAsInt("DB_PORT", 5432),
|
||||
DBUser: getEnv("DB_USER", "econ_user"),
|
||||
DBPassword: getEnv("DB_PASSWORD", "econ_pass"),
|
||||
DBName: getEnv("DB_NAME", "econ_db"),
|
||||
JWTSecret: getEnv("JWT_SECRET", "your-secret-key-change-in-production"),
|
||||
JWTExpirationHours: 15 * 60, // 15 minutes in minutes (900 minutes = 15 hours)
|
||||
RefreshExpDays: 7,
|
||||
}
|
||||
}
|
||||
|
||||
func getEnv(key, defaultValue string) string {
|
||||
if value, exists := os.LookupEnv(key); exists {
|
||||
return value
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
|
||||
func getEnvAsInt(key string, defaultValue int) int {
|
||||
if value, exists := os.LookupEnv(key); exists {
|
||||
if intValue, err := strconv.Atoi(value); err == nil {
|
||||
return intValue
|
||||
}
|
||||
}
|
||||
return defaultValue
|
||||
}
|
||||
111
backend/internal/handlers/auth.go
Normal file
111
backend/internal/handlers/auth.go
Normal file
@@ -0,0 +1,111 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/ren/econ/backend/internal/models"
|
||||
"github.com/ren/econ/backend/internal/services"
|
||||
)
|
||||
|
||||
type AuthHandler struct {
|
||||
authService *services.AuthService
|
||||
}
|
||||
|
||||
func NewAuthHandler(authService *services.AuthService) *AuthHandler {
|
||||
return &AuthHandler{authService: authService}
|
||||
}
|
||||
|
||||
// Login godoc
|
||||
// @Summary Iniciar sesión
|
||||
// @Description Autentica usuario y devuelve tokens JWT
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param login body models.LoginRequest true "Credenciales"
|
||||
// @Success 200 {object} models.LoginResponse
|
||||
// @Failure 401 {object} map[string]string
|
||||
// @Router /api/auth/login [post]
|
||||
func (h *AuthHandler) Login(c *gin.Context) {
|
||||
var req models.LoginRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.authService.Login(c.Request.Context(), &req)
|
||||
if err != nil {
|
||||
switch err {
|
||||
case services.ErrInvalidCredentials:
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Credenciales inválidas"})
|
||||
case services.ErrUserInactive:
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Usuario inactivo"})
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error interno"})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// RefreshToken godoc
|
||||
// @Summary Renovar token de acceso
|
||||
// @Description Renueva el token de acceso usando el refresh token
|
||||
// @Tags auth
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param refresh body models.RefreshRequest true "Refresh token"
|
||||
// @Success 200 {object} models.LoginResponse
|
||||
// @Failure 401 {object} map[string]string
|
||||
// @Router /api/auth/refresh [post]
|
||||
func (h *AuthHandler) RefreshToken(c *gin.Context) {
|
||||
var req models.RefreshRequest
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
resp, err := h.authService.RefreshToken(c.Request.Context(), req.RefreshToken)
|
||||
if err != nil {
|
||||
switch err {
|
||||
case services.ErrInvalidToken, services.ErrTokenExpired:
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Token inválido o expirado"})
|
||||
case services.ErrUserNotFound:
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||
case services.ErrUserInactive:
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Usuario inactivo"})
|
||||
default:
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error interno"})
|
||||
}
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resp)
|
||||
}
|
||||
|
||||
// Logout godoc
|
||||
// @Summary Cerrar sesión
|
||||
// @Description Cierra la sesión del usuario
|
||||
// @Tags auth
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Router /api/auth/logout [post]
|
||||
func (h *AuthHandler) Logout(c *gin.Context) {
|
||||
userID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado"})
|
||||
return
|
||||
}
|
||||
|
||||
err := h.authService.Logout(c.Request.Context(), userID.(uuid.UUID))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al cerrar sesión"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Sesión cerrada exitosamente"})
|
||||
}
|
||||
71
backend/internal/handlers/contenido.go
Normal file
71
backend/internal/handlers/contenido.go
Normal file
@@ -0,0 +1,71 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
|
||||
"github.com/ren/econ/backend/internal/models"
|
||||
"github.com/ren/econ/backend/internal/repository"
|
||||
)
|
||||
|
||||
type ContenidoHandler struct {
|
||||
contenidoRepo *repository.ContenidoRepository
|
||||
}
|
||||
|
||||
func NewContenidoHandler(contenidoRepo *repository.ContenidoRepository) *ContenidoHandler {
|
||||
return &ContenidoHandler{contenidoRepo: contenidoRepo}
|
||||
}
|
||||
|
||||
// GetModulos godoc
|
||||
// @Summary Listar módulos
|
||||
// @Description Lista todos los módulos disponibles
|
||||
// @Tags contenido
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {array} models.ModuloResumen
|
||||
// @Router /api/contenido/modulos [get]
|
||||
func (h *ContenidoHandler) GetModulos(c *gin.Context) {
|
||||
modulos, err := h.contenidoRepo.GetModulos(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al obtener módulos"})
|
||||
return
|
||||
}
|
||||
|
||||
if modulos == nil {
|
||||
modulos = []models.ModuloResumen{}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, modulos)
|
||||
}
|
||||
|
||||
// GetModulo godoc
|
||||
// @Summary Obtener contenido de módulo
|
||||
// @Description Obtiene el contenido de un módulo específico
|
||||
// @Tags contenido
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param numero path int true "Número del módulo"
|
||||
// @Success 200 {object} models.Modulo
|
||||
// @Router /api/contenido/modulos/{numero} [get]
|
||||
func (h *ContenidoHandler) GetModulo(c *gin.Context) {
|
||||
moduloNumero, err := strconv.Atoi(c.Param("numero"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Número de módulo inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
modulo, err := h.contenidoRepo.GetModulo(c.Request.Context(), moduloNumero)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al obtener módulo"})
|
||||
return
|
||||
}
|
||||
|
||||
if modulo == nil || len(modulo.Ejercicios) == 0 {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Módulo no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, modulo)
|
||||
}
|
||||
146
backend/internal/handlers/progreso.go
Normal file
146
backend/internal/handlers/progreso.go
Normal file
@@ -0,0 +1,146 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strconv"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/ren/econ/backend/internal/models"
|
||||
"github.com/ren/econ/backend/internal/repository"
|
||||
)
|
||||
|
||||
type ProgresoHandler struct {
|
||||
progresoRepo *repository.ProgresoRepository
|
||||
}
|
||||
|
||||
func NewProgresoHandler(progresoRepo *repository.ProgresoRepository) *ProgresoHandler {
|
||||
return &ProgresoHandler{progresoRepo: progresoRepo}
|
||||
}
|
||||
|
||||
// GetProgreso godoc
|
||||
// @Summary Obtener todo el progreso
|
||||
// @Description Obtiene todo el progreso del usuario autenticado
|
||||
// @Tags progreso
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {array} models.Progreso
|
||||
// @Router /api/progreso [get]
|
||||
func (h *ProgresoHandler) GetProgreso(c *gin.Context) {
|
||||
userID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado"})
|
||||
return
|
||||
}
|
||||
|
||||
progresos, err := h.progresoRepo.GetByUsuario(c.Request.Context(), userID.(uuid.UUID))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al obtener progreso"})
|
||||
return
|
||||
}
|
||||
|
||||
if progresos == nil {
|
||||
progresos = []models.Progreso{}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, progresos)
|
||||
}
|
||||
|
||||
// GetProgresoModulo godoc
|
||||
// @Summary Obtener progreso por módulo
|
||||
// @Description Obtiene el progreso del usuario en un módulo específico
|
||||
// @Tags progreso
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param numero path int true "Número del módulo"
|
||||
// @Success 200 {array} models.Progreso
|
||||
// @Router /api/progreso/modulo/{numero} [get]
|
||||
func (h *ProgresoHandler) GetProgresoModulo(c *gin.Context) {
|
||||
userID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado"})
|
||||
return
|
||||
}
|
||||
|
||||
moduloNumero, err := strconv.Atoi(c.Param("numero"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "Número de módulo inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
progresos, err := h.progresoRepo.GetByModulo(c.Request.Context(), userID.(uuid.UUID), moduloNumero)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al obtener progreso"})
|
||||
return
|
||||
}
|
||||
|
||||
if progresos == nil {
|
||||
progresos = []models.Progreso{}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, progresos)
|
||||
}
|
||||
|
||||
// UpdateProgreso godoc
|
||||
// @Summary Guardar avance
|
||||
// @Description Guarda el progreso de un ejercicio
|
||||
// @Tags progreso
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param ejercicioId path int true "ID del ejercicio"
|
||||
// @Param progreso body models.ProgresoUpdate true "Datos del progreso"
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Router /api/progreso/{ejercicioId} [put]
|
||||
func (h *ProgresoHandler) UpdateProgreso(c *gin.Context) {
|
||||
userID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado"})
|
||||
return
|
||||
}
|
||||
|
||||
ejercicioID, err := strconv.Atoi(c.Param("ejercicioId"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID de ejercicio inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
var req models.ProgresoUpdate
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
err = h.progresoRepo.Upsert(c.Request.Context(), userID.(uuid.UUID), ejercicioID, &req)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al guardar progreso: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Progreso guardado exitosamente"})
|
||||
}
|
||||
|
||||
// GetResumen godoc
|
||||
// @Summary Obtener resumen
|
||||
// @Description Obtiene estadísticas del progreso del usuario
|
||||
// @Tags progreso
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} models.ProgresoResumen
|
||||
// @Router /api/progreso/resumen [get]
|
||||
func (h *ProgresoHandler) GetResumen(c *gin.Context) {
|
||||
userID, exists := c.Get("user_id")
|
||||
if !exists {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "No autorizado"})
|
||||
return
|
||||
}
|
||||
|
||||
resumen, err := h.progresoRepo.GetResumen(c.Request.Context(), userID.(uuid.UUID))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al obtener resumen"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, resumen)
|
||||
}
|
||||
230
backend/internal/handlers/users.go
Normal file
230
backend/internal/handlers/users.go
Normal file
@@ -0,0 +1,230 @@
|
||||
package handlers
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/google/uuid"
|
||||
|
||||
"github.com/ren/econ/backend/internal/models"
|
||||
"github.com/ren/econ/backend/internal/repository"
|
||||
"github.com/ren/econ/backend/internal/services"
|
||||
)
|
||||
|
||||
type UsersHandler struct {
|
||||
userRepo *repository.UserRepository
|
||||
progresoRepo *repository.ProgresoRepository
|
||||
authService *services.AuthService
|
||||
}
|
||||
|
||||
func NewUsersHandler(userRepo *repository.UserRepository, progresoRepo *repository.ProgresoRepository, authService *services.AuthService) *UsersHandler {
|
||||
return &UsersHandler{
|
||||
userRepo: userRepo,
|
||||
progresoRepo: progresoRepo,
|
||||
authService: authService,
|
||||
}
|
||||
}
|
||||
|
||||
// ListUsers godoc
|
||||
// @Summary Listar usuarios
|
||||
// @Description Lista todos los usuarios (solo admin)
|
||||
// @Tags admin
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {array} models.Usuario
|
||||
// @Router /api/admin/usuarios [get]
|
||||
func (h *UsersHandler) ListUsers(c *gin.Context) {
|
||||
users, err := h.userRepo.List(c.Request.Context())
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al listar usuarios"})
|
||||
return
|
||||
}
|
||||
|
||||
if users == nil {
|
||||
users = []models.Usuario{}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, users)
|
||||
}
|
||||
|
||||
// CreateUser godoc
|
||||
// @Summary Crear usuario
|
||||
// @Description Crea un nuevo usuario (solo admin)
|
||||
// @Tags admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param usuario body models.UsuarioCreate true "Usuario a crear"
|
||||
// @Security BearerAuth
|
||||
// @Success 201 {object} models.Usuario
|
||||
// @Router /api/admin/usuarios [post]
|
||||
func (h *UsersHandler) CreateUser(c *gin.Context) {
|
||||
var req models.UsuarioCreate
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// Hash password if provided
|
||||
passwordHash := req.Password
|
||||
if passwordHash != "" {
|
||||
hash, err := h.authService.HashPassword(passwordHash)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al hashear password"})
|
||||
return
|
||||
}
|
||||
passwordHash = hash
|
||||
}
|
||||
|
||||
user := &models.Usuario{
|
||||
Username: req.Username,
|
||||
Email: req.Email,
|
||||
PasswordHash: passwordHash,
|
||||
Nombre: req.Nombre,
|
||||
Rol: req.Rol,
|
||||
}
|
||||
|
||||
// Si no se proporciona email, generar uno automáticamente basado en el username
|
||||
if user.Email == "" {
|
||||
user.Email = req.Username + "@econ.local"
|
||||
}
|
||||
|
||||
if user.Rol == "" {
|
||||
user.Rol = "estudiante"
|
||||
}
|
||||
|
||||
err := h.userRepo.Create(c.Request.Context(), user)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al crear usuario: " + err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusCreated, user)
|
||||
}
|
||||
|
||||
// GetUser godoc
|
||||
// @Summary Obtener usuario
|
||||
// @Description Obtiene un usuario por ID (solo admin)
|
||||
// @Tags admin
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path string true "ID del usuario"
|
||||
// @Success 200 {object} models.Usuario
|
||||
// @Router /api/admin/usuarios/{id} [get]
|
||||
func (h *UsersHandler) GetUser(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.userRepo.GetByID(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
// UpdateUser godoc
|
||||
// @Summary Actualizar usuario
|
||||
// @Description Actualiza un usuario (solo admin)
|
||||
// @Tags admin
|
||||
// @Accept json
|
||||
// @Produce json
|
||||
// @Param id path string true "ID del usuario"
|
||||
// @Param usuario body models.UsuarioUpdate true "Datos a actualizar"
|
||||
// @Security BearerAuth
|
||||
// @Success 200 {object} models.Usuario
|
||||
// @Router /api/admin/usuarios/{id} [put]
|
||||
func (h *UsersHandler) UpdateUser(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
var req models.UsuarioUpdate
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
user, err := h.userRepo.GetByID(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusNotFound, gin.H{"error": "Usuario no encontrado"})
|
||||
return
|
||||
}
|
||||
|
||||
if req.Email != "" {
|
||||
user.Email = req.Email
|
||||
}
|
||||
if req.Nombre != "" {
|
||||
user.Nombre = req.Nombre
|
||||
}
|
||||
if req.Activo != nil {
|
||||
user.Activo = *req.Activo
|
||||
}
|
||||
|
||||
err = h.userRepo.Update(c.Request.Context(), user)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al actualizar usuario"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, user)
|
||||
}
|
||||
|
||||
// DeleteUser godoc
|
||||
// @Summary Eliminar usuario
|
||||
// @Description Desactiva un usuario (solo admin)
|
||||
// @Tags admin
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path string true "ID del usuario"
|
||||
// @Success 200 {object} map[string]string
|
||||
// @Router /api/admin/usuarios/{id} [delete]
|
||||
func (h *UsersHandler) DeleteUser(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
err = h.userRepo.Delete(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al eliminar usuario"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, gin.H{"message": "Usuario desactivado exitosamente"})
|
||||
}
|
||||
|
||||
// GetUserProgreso godoc
|
||||
// @Summary Ver progreso de usuario
|
||||
// @Description Obtiene el progreso de un usuario (solo admin)
|
||||
// @Tags admin
|
||||
// @Produce json
|
||||
// @Security BearerAuth
|
||||
// @Param id path string true "ID del usuario"
|
||||
// @Success 200 {array} models.Progreso
|
||||
// @Router /api/admin/usuarios/{id}/progreso [get]
|
||||
func (h *UsersHandler) GetUserProgreso(c *gin.Context) {
|
||||
id, err := uuid.Parse(c.Param("id"))
|
||||
if err != nil {
|
||||
c.JSON(http.StatusBadRequest, gin.H{"error": "ID inválido"})
|
||||
return
|
||||
}
|
||||
|
||||
progresos, err := h.progresoRepo.GetByUsuarioID(c.Request.Context(), id)
|
||||
if err != nil {
|
||||
c.JSON(http.StatusInternalServerError, gin.H{"error": "Error al obtener progreso"})
|
||||
return
|
||||
}
|
||||
|
||||
if progresos == nil {
|
||||
progresos = []models.Progreso{}
|
||||
}
|
||||
|
||||
c.JSON(http.StatusOK, progresos)
|
||||
}
|
||||
51
backend/internal/middleware/auth.go
Normal file
51
backend/internal/middleware/auth.go
Normal file
@@ -0,0 +1,51 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"github.com/ren/econ/backend/internal/services"
|
||||
)
|
||||
|
||||
func AuthMiddleware(authService *services.AuthService) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
if authHeader == "" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header requerido"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": "Formato de authorization header inválido"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := authService.ValidateToken(parts[1])
|
||||
if err != nil {
|
||||
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("user_email", claims.Email)
|
||||
c.Set("user_rol", claims.Rol)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
func AdminMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
rol, exists := c.Get("user_rol")
|
||||
if !exists || rol != "admin" {
|
||||
c.JSON(http.StatusForbidden, gin.H{"error": "Acceso denegado - se requiere rol admin"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
23
backend/internal/models/contenido.go
Normal file
23
backend/internal/models/contenido.go
Normal file
@@ -0,0 +1,23 @@
|
||||
package models
|
||||
|
||||
type Modulo struct {
|
||||
Numero int `json:"numero"`
|
||||
Titulo string `json:"titulo"`
|
||||
Descripcion string `json:"descripcion"`
|
||||
Ejercicios []Ejercicio `json:"ejercicios"`
|
||||
}
|
||||
|
||||
type Ejercicio struct {
|
||||
ID int `json:"id"`
|
||||
Numero int `json:"numero"`
|
||||
Titulo string `json:"titulo"`
|
||||
Tipo string `json:"tipo"`
|
||||
Contenido map[string]interface{} `json:"contenido"`
|
||||
Orden int `json:"orden"`
|
||||
}
|
||||
|
||||
type ModuloResumen struct {
|
||||
Numero int `json:"numero"`
|
||||
Titulo string `json:"titulo"`
|
||||
Descripcion string `json:"descripcion"`
|
||||
}
|
||||
32
backend/internal/models/progreso.go
Normal file
32
backend/internal/models/progreso.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Progreso struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
UsuarioID uuid.UUID `json:"usuario_id"`
|
||||
ModuloNumero int `json:"modulo_numero"`
|
||||
EjercicioID int `json:"ejercicio_id"`
|
||||
Completado bool `json:"completado"`
|
||||
Puntuacion int `json:"puntuacion"`
|
||||
Intentos int `json:"intentos"`
|
||||
UltimaVez time.Time `json:"ultima_vez"`
|
||||
RespuestaJSON string `json:"respuesta_json,omitempty"`
|
||||
}
|
||||
|
||||
type ProgresoUpdate struct {
|
||||
Completado bool `json:"completado"`
|
||||
Puntuacion int `json:"puntuacion"`
|
||||
RespuestaJSON string `json:"respuesta_json,omitempty"`
|
||||
}
|
||||
|
||||
type ProgresoResumen struct {
|
||||
TotalEjercicios int `json:"total_ejercicios"`
|
||||
EjerciciosCompletados int `json:"ejercicios_completados"`
|
||||
PromedioPuntuacion int `json:"promedio_puntuacion"`
|
||||
ModulosCompletados int `json:"modulos_completados"`
|
||||
}
|
||||
50
backend/internal/models/user.go
Normal file
50
backend/internal/models/user.go
Normal file
@@ -0,0 +1,50 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type Usuario struct {
|
||||
ID uuid.UUID `json:"id"`
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username"`
|
||||
PasswordHash string `json:"-"`
|
||||
Nombre string `json:"nombre"`
|
||||
Rol string `json:"rol"` // admin, estudiante
|
||||
CreadoEn time.Time `json:"creado_en"`
|
||||
UltimoLogin *time.Time `json:"ultimo_login"`
|
||||
Activo bool `json:"activo"`
|
||||
}
|
||||
|
||||
type UsuarioCreate struct {
|
||||
Username string `json:"username" binding:"required"`
|
||||
Email string `json:"email"`
|
||||
Password string `json:"password"`
|
||||
Nombre string `json:"nombre" binding:"required"`
|
||||
Rol string `json:"rol"`
|
||||
}
|
||||
|
||||
type UsuarioUpdate struct {
|
||||
Email string `json:"email"`
|
||||
Nombre string `json:"nombre"`
|
||||
Activo *bool `json:"activo"`
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
Email string `json:"email"`
|
||||
Username string `json:"username"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
AccessToken string `json:"access_token"`
|
||||
RefreshToken string `json:"refresh_token"`
|
||||
ExpiresIn int `json:"expires_in"` // seconds
|
||||
User *Usuario `json:"user"`
|
||||
}
|
||||
|
||||
type RefreshRequest struct {
|
||||
RefreshToken string `json:"refresh_token" binding:"required"`
|
||||
}
|
||||
89
backend/internal/repository/contenido.go
Normal file
89
backend/internal/repository/contenido.go
Normal file
@@ -0,0 +1,89 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/ren/econ/backend/internal/models"
|
||||
)
|
||||
|
||||
type ContenidoRepository struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewContenidoRepository(db *pgxpool.Pool) *ContenidoRepository {
|
||||
return &ContenidoRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *ContenidoRepository) GetModulos(ctx context.Context) ([]models.ModuloResumen, error) {
|
||||
query := `
|
||||
SELECT DISTINCT modulo_numero, titulo, contenido::text
|
||||
FROM ejercicios
|
||||
ORDER BY modulo_numero
|
||||
`
|
||||
rows, err := r.db.Query(ctx, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var modulos []models.ModuloResumen
|
||||
for rows.Next() {
|
||||
var m models.ModuloResumen
|
||||
var contenidoJSON string
|
||||
err := rows.Scan(&m.Numero, &m.Titulo, &contenidoJSON)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
// Extraer descripción del contenido JSON
|
||||
var contenido map[string]interface{}
|
||||
json.Unmarshal([]byte(contenidoJSON), &contenido)
|
||||
if desc, ok := contenido["descripcion"].(string); ok {
|
||||
m.Descripcion = desc
|
||||
} else {
|
||||
m.Descripcion = ""
|
||||
}
|
||||
modulos = append(modulos, m)
|
||||
}
|
||||
return modulos, nil
|
||||
}
|
||||
|
||||
func (r *ContenidoRepository) GetModulo(ctx context.Context, numero int) (*models.Modulo, error) {
|
||||
query := `
|
||||
SELECT id, titulo, tipo, contenido, orden
|
||||
FROM ejercicios WHERE modulo_numero = $1
|
||||
ORDER BY orden
|
||||
`
|
||||
rows, err := r.db.Query(ctx, query, numero)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
modulo := &models.Modulo{Numero: numero}
|
||||
var ejercicios []models.Ejercicio
|
||||
|
||||
for rows.Next() {
|
||||
var e models.Ejercicio
|
||||
var contenidoJSON string
|
||||
err := rows.Scan(&e.ID, &e.Titulo, &e.Tipo, &contenidoJSON, &e.Orden)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
json.Unmarshal([]byte(contenidoJSON), &e.Contenido)
|
||||
e.Numero = e.ID
|
||||
ejercicios = append(ejercicios, e)
|
||||
}
|
||||
|
||||
if len(ejercicios) > 0 {
|
||||
modulo.Titulo = ejercicios[0].Titulo
|
||||
modulo.Ejercicios = ejercicios
|
||||
// Extraer descripción del primer ejercicio
|
||||
if desc, ok := ejercicios[0].Contenido["descripcion"].(string); ok {
|
||||
modulo.Descripcion = desc
|
||||
}
|
||||
}
|
||||
|
||||
return modulo, nil
|
||||
}
|
||||
141
backend/internal/repository/progreso.go
Normal file
141
backend/internal/repository/progreso.go
Normal file
@@ -0,0 +1,141 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/ren/econ/backend/internal/models"
|
||||
)
|
||||
|
||||
type ProgresoRepository struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewProgresoRepository(db *pgxpool.Pool) *ProgresoRepository {
|
||||
return &ProgresoRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *ProgresoRepository) GetByUsuario(ctx context.Context, usuarioID uuid.UUID) ([]models.Progreso, error) {
|
||||
query := `
|
||||
SELECT id, usuario_id, modulo_numero, ejercicio_id, completado, puntuacion, intentos, ultima_vez, respuesta_json
|
||||
FROM progreso_usuario WHERE usuario_id = $1
|
||||
ORDER BY ultima_vez DESC
|
||||
`
|
||||
rows, err := r.db.Query(ctx, query, usuarioID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var progresos []models.Progreso
|
||||
for rows.Next() {
|
||||
var p models.Progreso
|
||||
err := rows.Scan(
|
||||
&p.ID, &p.UsuarioID, &p.ModuloNumero, &p.EjercicioID,
|
||||
&p.Completado, &p.Puntuacion, &p.Intentos, &p.UltimaVez, &p.RespuestaJSON)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
progresos = append(progresos, p)
|
||||
}
|
||||
return progresos, nil
|
||||
}
|
||||
|
||||
func (r *ProgresoRepository) GetByModulo(ctx context.Context, usuarioID uuid.UUID, moduloNumero int) ([]models.Progreso, error) {
|
||||
query := `
|
||||
SELECT id, usuario_id, modulo_numero, ejercicio_id, completado, puntuacion, intentos, ultima_vez, respuesta_json
|
||||
FROM progreso_usuario WHERE usuario_id = $1 AND modulo_numero = $2
|
||||
ORDER BY ejercicio_id
|
||||
`
|
||||
rows, err := r.db.Query(ctx, query, usuarioID, moduloNumero)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var progresos []models.Progreso
|
||||
for rows.Next() {
|
||||
var p models.Progreso
|
||||
err := rows.Scan(
|
||||
&p.ID, &p.UsuarioID, &p.ModuloNumero, &p.EjercicioID,
|
||||
&p.Completado, &p.Puntuacion, &p.Intentos, &p.UltimaVez, &p.RespuestaJSON)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
progresos = append(progresos, p)
|
||||
}
|
||||
return progresos, nil
|
||||
}
|
||||
|
||||
func (r *ProgresoRepository) GetByEjercicio(ctx context.Context, usuarioID uuid.UUID, ejercicioID int) (*models.Progreso, error) {
|
||||
query := `
|
||||
SELECT id, usuario_id, modulo_numero, ejercicio_id, completado, puntuacion, intentos, ultima_vez, respuesta_json
|
||||
FROM progreso_usuario WHERE usuario_id = $1 AND ejercicio_id = $2
|
||||
`
|
||||
var p models.Progreso
|
||||
err := r.db.QueryRow(ctx, query, usuarioID, ejercicioID).Scan(
|
||||
&p.ID, &p.UsuarioID, &p.ModuloNumero, &p.EjercicioID,
|
||||
&p.Completado, &p.Puntuacion, &p.Intentos, &p.UltimaVez, &p.RespuestaJSON)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &p, nil
|
||||
}
|
||||
|
||||
func (r *ProgresoRepository) Upsert(ctx context.Context, usuarioID uuid.UUID, ejercicioID int, update *models.ProgresoUpdate) error {
|
||||
query := `
|
||||
INSERT INTO progreso_usuario (id, usuario_id, modulo_numero, ejercicio_id, completado, puntuacion, intentos, ultima_vez, respuesta_json)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8, $9)
|
||||
ON CONFLICT (usuario_id, modulo_numero, ejercicio_id)
|
||||
DO UPDATE SET completado = $5, puntuacion = $6, intentos = $7, ultima_vez = $8, respuesta_json = $9
|
||||
`
|
||||
|
||||
moduloNumero, err := r.getModuloByEjercicio(ctx, ejercicioID)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
|
||||
existing, _ := r.GetByEjercicio(ctx, usuarioID, ejercicioID)
|
||||
var intentos int
|
||||
if existing != nil {
|
||||
intentos = existing.Intentos + 1
|
||||
} else {
|
||||
intentos = 1
|
||||
}
|
||||
|
||||
_, err = r.db.Exec(ctx, query,
|
||||
uuid.New(), usuarioID, moduloNumero, ejercicioID,
|
||||
update.Completado, update.Puntuacion, intentos, time.Now(), update.RespuestaJSON)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *ProgresoRepository) getModuloByEjercicio(ctx context.Context, ejercicioID int) (int, error) {
|
||||
var moduloNumero int
|
||||
err := r.db.QueryRow(ctx, "SELECT modulo_numero FROM ejercicios WHERE id = $1", ejercicioID).Scan(&moduloNumero)
|
||||
return moduloNumero, err
|
||||
}
|
||||
|
||||
func (r *ProgresoRepository) GetResumen(ctx context.Context, usuarioID uuid.UUID) (*models.ProgresoResumen, error) {
|
||||
query := `
|
||||
SELECT
|
||||
COUNT(DISTINCT ejercicio_id) as total,
|
||||
COUNT(CASE WHEN completado THEN 1 END) as completados,
|
||||
COALESCE(AVG(CASE WHEN completado THEN puntuacion END), 0)::int as promedio,
|
||||
COUNT(DISTINCT CASE WHEN completado THEN modulo_numero END) as modulos
|
||||
FROM progreso_usuario WHERE usuario_id = $1
|
||||
`
|
||||
var resumen models.ProgresoResumen
|
||||
err := r.db.QueryRow(ctx, query, usuarioID).Scan(
|
||||
&resumen.TotalEjercicios, &resumen.EjerciciosCompletados,
|
||||
&resumen.PromedioPuntuacion, &resumen.ModulosCompletados)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &resumen, nil
|
||||
}
|
||||
|
||||
func (r *ProgresoRepository) GetByUsuarioID(ctx context.Context, usuarioID uuid.UUID) ([]models.Progreso, error) {
|
||||
return r.GetByUsuario(ctx, usuarioID)
|
||||
}
|
||||
128
backend/internal/repository/user.go
Normal file
128
backend/internal/repository/user.go
Normal file
@@ -0,0 +1,128 @@
|
||||
package repository
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
"github.com/ren/econ/backend/internal/models"
|
||||
)
|
||||
|
||||
type UserRepository struct {
|
||||
db *pgxpool.Pool
|
||||
}
|
||||
|
||||
func NewUserRepository(db *pgxpool.Pool) *UserRepository {
|
||||
return &UserRepository{db: db}
|
||||
}
|
||||
|
||||
func (r *UserRepository) Create(ctx context.Context, user *models.Usuario) error {
|
||||
user.ID = uuid.New()
|
||||
user.CreadoEn = time.Now()
|
||||
user.Activo = true
|
||||
if user.Rol == "" {
|
||||
user.Rol = "estudiante"
|
||||
}
|
||||
|
||||
query := `
|
||||
INSERT INTO usuarios (id, email, username, password_hash, nombre, rol, creado_en, activo)
|
||||
VALUES ($1, $2, $3, $4, $5, $6, $7, $8)
|
||||
`
|
||||
_, err := r.db.Exec(ctx, query,
|
||||
user.ID, user.Email, user.Username, user.PasswordHash, user.Nombre, user.Rol, user.CreadoEn, user.Activo)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByID(ctx context.Context, id uuid.UUID) (*models.Usuario, error) {
|
||||
query := `
|
||||
SELECT id, email, username, password_hash, nombre, rol, creado_en, ultimo_login, activo
|
||||
FROM usuarios WHERE id = $1
|
||||
`
|
||||
var user models.Usuario
|
||||
err := r.db.QueryRow(ctx, query, id).Scan(
|
||||
&user.ID, &user.Email, &user.Username, &user.PasswordHash, &user.Nombre,
|
||||
&user.Rol, &user.CreadoEn, &user.UltimoLogin, &user.Activo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByEmail(ctx context.Context, email string) (*models.Usuario, error) {
|
||||
query := `
|
||||
SELECT id, email, username, password_hash, nombre, rol, creado_en, ultimo_login, activo
|
||||
FROM usuarios WHERE email = $1
|
||||
`
|
||||
var user models.Usuario
|
||||
err := r.db.QueryRow(ctx, query, email).Scan(
|
||||
&user.ID, &user.Email, &user.Username, &user.PasswordHash, &user.Nombre,
|
||||
&user.Rol, &user.CreadoEn, &user.UltimoLogin, &user.Activo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) GetByUsername(ctx context.Context, username string) (*models.Usuario, error) {
|
||||
query := `
|
||||
SELECT id, email, username, password_hash, nombre, rol, creado_en, ultimo_login, activo
|
||||
FROM usuarios WHERE username = $1
|
||||
`
|
||||
var user models.Usuario
|
||||
err := r.db.QueryRow(ctx, query, username).Scan(
|
||||
&user.ID, &user.Email, &user.Username, &user.PasswordHash, &user.Nombre,
|
||||
&user.Rol, &user.CreadoEn, &user.UltimoLogin, &user.Activo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &user, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) List(ctx context.Context) ([]models.Usuario, error) {
|
||||
query := `
|
||||
SELECT id, email, username, password_hash, nombre, rol, creado_en, ultimo_login, activo
|
||||
FROM usuarios ORDER BY creado_en DESC
|
||||
`
|
||||
rows, err := r.db.Query(ctx, query)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
defer rows.Close()
|
||||
|
||||
var users []models.Usuario
|
||||
for rows.Next() {
|
||||
var user models.Usuario
|
||||
err := rows.Scan(
|
||||
&user.ID, &user.Email, &user.Username, &user.PasswordHash, &user.Nombre,
|
||||
&user.Rol, &user.CreadoEn, &user.UltimoLogin, &user.Activo)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
users = append(users, user)
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
func (r *UserRepository) Update(ctx context.Context, user *models.Usuario) error {
|
||||
query := `
|
||||
UPDATE usuarios SET email = $2, nombre = $3, rol = $4, activo = $5
|
||||
WHERE id = $1
|
||||
`
|
||||
_, err := r.db.Exec(ctx, query,
|
||||
user.ID, user.Email, user.Nombre, user.Rol, user.Activo)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *UserRepository) Delete(ctx context.Context, id uuid.UUID) error {
|
||||
// Soft delete - set activo to false
|
||||
query := `UPDATE usuarios SET activo = false WHERE id = $1`
|
||||
_, err := r.db.Exec(ctx, query, id)
|
||||
return err
|
||||
}
|
||||
|
||||
func (r *UserRepository) UpdateLastLogin(ctx context.Context, id uuid.UUID) error {
|
||||
query := `UPDATE usuarios SET ultimo_login = $2 WHERE id = $1`
|
||||
_, err := r.db.Exec(ctx, query, id, time.Now())
|
||||
return err
|
||||
}
|
||||
195
backend/internal/services/auth.go
Normal file
195
backend/internal/services/auth.go
Normal file
@@ -0,0 +1,195 @@
|
||||
package services
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v5"
|
||||
"github.com/google/uuid"
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
|
||||
"github.com/ren/econ/backend/internal/config"
|
||||
"github.com/ren/econ/backend/internal/models"
|
||||
"github.com/ren/econ/backend/internal/repository"
|
||||
)
|
||||
|
||||
var (
|
||||
ErrInvalidCredentials = errors.New("credenciales inválidas")
|
||||
ErrUserNotFound = errors.New("usuario no encontrado")
|
||||
ErrUserInactive = errors.New("usuario inactivo")
|
||||
ErrInvalidToken = errors.New("token inválido")
|
||||
ErrTokenExpired = errors.New("token expirado")
|
||||
)
|
||||
|
||||
type AuthService struct {
|
||||
config *config.Config
|
||||
userRepo *repository.UserRepository
|
||||
}
|
||||
|
||||
func NewAuthService(cfg *config.Config, userRepo *repository.UserRepository) *AuthService {
|
||||
return &AuthService{
|
||||
config: cfg,
|
||||
userRepo: userRepo,
|
||||
}
|
||||
}
|
||||
|
||||
type Claims struct {
|
||||
UserID uuid.UUID `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
Rol string `json:"rol"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func (s *AuthService) Login(ctx context.Context, req *models.LoginRequest) (*models.LoginResponse, error) {
|
||||
var user *models.Usuario
|
||||
var err error
|
||||
|
||||
// Buscar por email o username
|
||||
if req.Username != "" {
|
||||
user, err = s.userRepo.GetByUsername(ctx, req.Username)
|
||||
} else if req.Email != "" {
|
||||
user, err = s.userRepo.GetByEmail(ctx, req.Email)
|
||||
} else {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
if !user.Activo {
|
||||
return nil, ErrUserInactive
|
||||
}
|
||||
|
||||
if err := bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(req.Password)); err != nil {
|
||||
return nil, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
// Update last login
|
||||
s.userRepo.UpdateLastLogin(ctx, user.ID)
|
||||
|
||||
// Generate tokens
|
||||
accessToken, err := s.generateAccessToken(user)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error generando access token: %w", err)
|
||||
}
|
||||
|
||||
refreshToken, err := s.generateRefreshToken(user)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error generando refresh token: %w", err)
|
||||
}
|
||||
|
||||
return &models.LoginResponse{
|
||||
AccessToken: accessToken,
|
||||
RefreshToken: refreshToken,
|
||||
ExpiresIn: s.config.JWTExpirationHours * 60,
|
||||
User: user,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) RefreshToken(ctx context.Context, refreshToken string) (*models.LoginResponse, error) {
|
||||
claims, err := s.validateToken(refreshToken)
|
||||
if err != nil {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
user, err := s.userRepo.GetByID(ctx, claims.UserID)
|
||||
if err != nil {
|
||||
return nil, ErrUserNotFound
|
||||
}
|
||||
|
||||
if !user.Activo {
|
||||
return nil, ErrUserInactive
|
||||
}
|
||||
|
||||
accessToken, err := s.generateAccessToken(user)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error generando access token: %w", err)
|
||||
}
|
||||
|
||||
newRefreshToken, err := s.generateRefreshToken(user)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("error generando refresh token: %w", err)
|
||||
}
|
||||
|
||||
return &models.LoginResponse{
|
||||
AccessToken: accessToken,
|
||||
RefreshToken: newRefreshToken,
|
||||
ExpiresIn: s.config.JWTExpirationHours * 60,
|
||||
User: user,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) Logout(ctx context.Context, userID uuid.UUID) error {
|
||||
// In a more complete implementation, we would blacklist the tokens
|
||||
// For now, just return success
|
||||
return nil
|
||||
}
|
||||
|
||||
func (s *AuthService) HashPassword(password string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), bcrypt.DefaultCost)
|
||||
return string(hash), err
|
||||
}
|
||||
|
||||
func (s *AuthService) generateAccessToken(user *models.Usuario) (string, error) {
|
||||
claims := Claims{
|
||||
UserID: user.ID,
|
||||
Email: user.Email,
|
||||
Rol: user.Rol,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(s.config.JWTExpirationHours) * time.Minute)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
NotBefore: jwt.NewNumericDate(time.Now()),
|
||||
Subject: user.ID.String(),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(s.config.JWTSecret))
|
||||
}
|
||||
|
||||
func (s *AuthService) generateRefreshToken(user *models.Usuario) (string, error) {
|
||||
claims := Claims{
|
||||
UserID: user.ID,
|
||||
Email: user.Email,
|
||||
Rol: user.Rol,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(s.config.RefreshExpDays) * 24 * time.Hour)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
NotBefore: jwt.NewNumericDate(time.Now()),
|
||||
Subject: user.ID.String(),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
return token.SignedString([]byte(s.config.JWTSecret))
|
||||
}
|
||||
|
||||
func (s *AuthService) validateToken(tokenString string) (*Claims, error) {
|
||||
token, err := jwt.ParseWithClaims(tokenString, &Claims{}, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(s.config.JWTSecret), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
if errors.Is(err, jwt.ErrTokenExpired) {
|
||||
return nil, ErrTokenExpired
|
||||
}
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
claims, ok := token.Claims.(*Claims)
|
||||
if !ok || !token.Valid {
|
||||
return nil, ErrInvalidToken
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
||||
func (s *AuthService) ValidateToken(tokenString string) (*Claims, error) {
|
||||
return s.validateToken(tokenString)
|
||||
}
|
||||
Reference in New Issue
Block a user