69 lines
1.6 KiB
Go
69 lines
1.6 KiB
Go
package auth
|
|
|
|
import (
|
|
"errors"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/sujit-baniya/fiber-boilerplate/app"
|
|
"github.com/sujit-baniya/fiber-boilerplate/pkg/models"
|
|
)
|
|
|
|
const portalSessionKey = "portal_user_id"
|
|
|
|
// PortalUser obtiene el usuario portal de la sesión actual.
|
|
func PortalUser(c *fiber.Ctx) (*models.PortalUser, error) {
|
|
store := app.Http.Session.Get(c)
|
|
raw := store.Get(portalSessionKey)
|
|
if raw == nil {
|
|
return nil, errors.New("no portal session")
|
|
}
|
|
var id uint
|
|
switch v := raw.(type) {
|
|
case uint:
|
|
id = v
|
|
case uint64:
|
|
id = uint(v)
|
|
case uint32:
|
|
id = uint(v)
|
|
case int64:
|
|
id = uint(v)
|
|
case float64:
|
|
id = uint(v)
|
|
default:
|
|
return nil, errors.New("invalid portal session")
|
|
}
|
|
u, err := models.GetPortalUserByID(id)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
if !u.Activo {
|
|
return nil, errors.New("portal user inactive")
|
|
}
|
|
// Precargar accesos del portal user para que GetClienteIDsForPortalUser funcione
|
|
return u, nil
|
|
}
|
|
|
|
// SetPortalSession guarda el portal_user_id en la sesión.
|
|
// Regenera el ID de sesión para prevenir session fixation.
|
|
func SetPortalSession(c *fiber.Ctx, userID uint) error {
|
|
store := app.Http.Session.Get(c)
|
|
store.Set(portalSessionKey, userID)
|
|
if err := store.Regenerate(); err != nil {
|
|
return err
|
|
}
|
|
return store.Save()
|
|
}
|
|
|
|
// DestroyPortalSession elimina la sesión del portal.
|
|
func DestroyPortalSession(c *fiber.Ctx) error {
|
|
store := app.Http.Session.Get(c)
|
|
store.Delete(portalSessionKey)
|
|
return store.Save()
|
|
}
|
|
|
|
// IsPortalLoggedIn verifica si hay sesión de portal activa.
|
|
func IsPortalLoggedIn(c *fiber.Ctx) bool {
|
|
store := app.Http.Session.Get(c)
|
|
return store.Get(portalSessionKey) != nil
|
|
}
|