Private
Public Access
102 lines
2.4 KiB
Go
102 lines
2.4 KiB
Go
package auth
|
|
|
|
import (
|
|
"net/http"
|
|
|
|
"repuestera_back/dto"
|
|
dto_directors "repuestera_back/dto/Builders/Directors"
|
|
r "repuestera_back/repositorios"
|
|
"repuestera_back/services"
|
|
"repuestera_back/utils"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
)
|
|
|
|
func Me(c *gin.Context) {
|
|
userID, ok := c.Get("userID")
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "usuario no autenticado"})
|
|
return
|
|
}
|
|
|
|
id, ok := userID.(uint)
|
|
if !ok {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": "token inválido"})
|
|
return
|
|
}
|
|
|
|
empresaID := utils.EmpresaID(c)
|
|
sesion, err := services.ConstruirSesion(id, empresaID)
|
|
if err != nil {
|
|
c.JSON(http.StatusUnauthorized, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
respuesta, err := dto_directors.NewMeDirector().DesdeSesion(sesion)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, respuesta)
|
|
}
|
|
|
|
// ObtenerMisEmpresas devuelve las empresas donde el usuario es miembro.
|
|
func ObtenerMisEmpresas(c *gin.Context) {
|
|
userID, _ := c.Get("userID")
|
|
id, _ := userID.(uint)
|
|
|
|
empresas, err := services.ListarEmpresasDeUsuario(id)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, dto.EmpresasResponse{Empresas: empresas})
|
|
}
|
|
|
|
// CambiarEmpresa emite una sesión nueva para otra empresa del usuario.
|
|
func CambiarEmpresa(c *gin.Context) {
|
|
var req struct {
|
|
EmpresaID uint `json:"empresa_id" binding:"required"`
|
|
}
|
|
if err := c.ShouldBindJSON(&req); err != nil {
|
|
c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
userID, _ := c.Get("userID")
|
|
id, _ := userID.(uint)
|
|
|
|
respuesta, err := services.ConstruirSesion(id, req.EmpresaID)
|
|
if err != nil {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, respuesta)
|
|
}
|
|
|
|
// ObtenerEmpresaActual devuelve los datos de la empresa activa.
|
|
func ObtenerEmpresaActual(c *gin.Context) {
|
|
userID, _ := c.Get("userID")
|
|
id, _ := userID.(uint)
|
|
empresaID := utils.EmpresaID(c)
|
|
|
|
empresa, rol, err := services.EmpresaDeUsuario(id, empresaID)
|
|
if err != nil {
|
|
c.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
miembros, _ := r.ObtenerRepositorios().Empresa.ContarMiembros(empresa.ID)
|
|
|
|
respuesta, err := dto_directors.NewEmpresaActualDirector().DesdeEmpresa(empresa, rol, miembros)
|
|
if err != nil {
|
|
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
|
|
return
|
|
}
|
|
|
|
c.JSON(http.StatusOK, respuesta)
|
|
}
|