feat(portal): agregar flujo de recuperación de contraseña
This commit is contained in:
@@ -71,6 +71,8 @@ func main() {
|
||||
// Partner
|
||||
&models.PartnerRecurso{},
|
||||
&models.PartnerComunicado{},
|
||||
// Portal: recuperación de contraseña
|
||||
&models.PortalPasswordResetToken{},
|
||||
)
|
||||
// Seed automático (idempotente) de módulos del sistema
|
||||
migrations.SeedRenovaciones()
|
||||
|
||||
@@ -1,7 +1,10 @@
|
||||
package models
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"time"
|
||||
|
||||
"github.com/sujit-baniya/fiber-boilerplate/app"
|
||||
"gorm.io/gorm"
|
||||
@@ -196,6 +199,58 @@ func GetClienteIDsForPortalUser(u *PortalUser) []uint {
|
||||
return []uint{}
|
||||
}
|
||||
|
||||
// ─── PortalPasswordResetToken ────────────────────────────────────────────────
|
||||
|
||||
type PortalPasswordResetToken struct {
|
||||
ID uint `gorm:"primaryKey;autoIncrement"`
|
||||
PortalUserID uint `gorm:"column:portal_user_id;index;not null"`
|
||||
Token string `gorm:"column:token;uniqueIndex;not null"`
|
||||
ExpiresAt time.Time `gorm:"column:expires_at;not null"`
|
||||
Used bool `gorm:"column:used;default:false"`
|
||||
CreatedAt time.Time
|
||||
}
|
||||
|
||||
func (PortalPasswordResetToken) TableName() string { return "portal_password_reset_tokens" }
|
||||
|
||||
// CreatePortalResetToken genera un token aleatorio seguro de 32 bytes, lo persiste y lo retorna.
|
||||
func CreatePortalResetToken(portalUserID uint) (string, error) {
|
||||
b := make([]byte, 32)
|
||||
if _, err := rand.Read(b); err != nil {
|
||||
return "", err
|
||||
}
|
||||
token := hex.EncodeToString(b)
|
||||
record := &PortalPasswordResetToken{
|
||||
PortalUserID: portalUserID,
|
||||
Token: token,
|
||||
ExpiresAt: time.Now().Add(1 * time.Hour),
|
||||
}
|
||||
if err := app.Http.Database.DB.Create(record).Error; err != nil {
|
||||
return "", err
|
||||
}
|
||||
return token, nil
|
||||
}
|
||||
|
||||
// GetValidPortalResetToken busca el token, verifica que no esté usado ni vencido.
|
||||
func GetValidPortalResetToken(token string) (*PortalPasswordResetToken, error) {
|
||||
var record PortalPasswordResetToken
|
||||
err := app.Http.Database.DB.Where("token = ?", token).First(&record).Error
|
||||
if err != nil {
|
||||
return nil, errors.New("token inválido")
|
||||
}
|
||||
if record.Used {
|
||||
return nil, errors.New("este enlace ya fue utilizado")
|
||||
}
|
||||
if time.Now().After(record.ExpiresAt) {
|
||||
return nil, errors.New("el enlace ha expirado, solicita uno nuevo")
|
||||
}
|
||||
return &record, nil
|
||||
}
|
||||
|
||||
// MarkPortalResetTokenUsed marca el token como utilizado.
|
||||
func MarkPortalResetTokenUsed(id uint) error {
|
||||
return app.Http.Database.DB.Model(&PortalPasswordResetToken{}).Where("id = ?", id).Update("used", true).Error
|
||||
}
|
||||
|
||||
// CheckPortalLogin valida credenciales y retorna el portal user.
|
||||
func CheckPortalLogin(email, password string) (*PortalUser, error) {
|
||||
u, err := GetPortalUserByEmail(email)
|
||||
|
||||
@@ -78,6 +78,31 @@ func GeneratePasswordResetURL(email string, baseURL string) string {
|
||||
return uri
|
||||
}
|
||||
|
||||
// SendPortalPasswordResetEmail envía al usuario del portal un enlace para restablecer su contraseña.
|
||||
func SendPortalPasswordResetEmail(email, nombre, resetLink string) {
|
||||
htmlBody := fmt.Sprintf(`<!DOCTYPE html>
|
||||
<html><body style="font-family:Inter,sans-serif;background:#f1f5f9;padding:32px">
|
||||
<div style="max-width:480px;margin:0 auto;background:#fff;border-radius:16px;padding:32px;border:1px solid #e2e8f0">
|
||||
<div style="text-align:center;margin-bottom:24px">
|
||||
<div style="width:48px;height:48px;border-radius:50%%;background:#8eb02f;display:inline-flex;align-items:center;justify-content:center;color:#fff;font-weight:700;font-size:20px">U</div>
|
||||
<h2 style="margin:12px 0 4px;color:#1e293b">Restablecer contraseña</h2>
|
||||
<p style="color:#64748b;font-size:14px;margin:0">Portal de Clientes · U-site</p>
|
||||
</div>
|
||||
<p style="color:#334155;font-size:15px">Hola <strong>%s</strong>,</p>
|
||||
<p style="color:#334155;font-size:14px">Recibimos una solicitud para restablecer la contraseña de tu cuenta. Haz clic en el siguiente botón para continuar:</p>
|
||||
<a href="%s" style="display:block;text-align:center;background:#8eb02f;color:#fff;padding:12px 24px;border-radius:10px;font-weight:600;text-decoration:none;font-size:15px;margin:24px 0">Restablecer contraseña</a>
|
||||
<p style="color:#64748b;font-size:13px">Este enlace es válido por <strong>1 hora</strong>. Si no solicitaste este cambio, puedes ignorar este mensaje.</p>
|
||||
<p style="font-size:12px;color:#94a3b8;margin-top:24px;text-align:center">© 2025 U-site — Todos los derechos reservados</p>
|
||||
</div>
|
||||
</body></html>`, nombre, resetLink)
|
||||
|
||||
go func() {
|
||||
if err := app.Http.Mail.Send(email, "Restablece tu contraseña - Portal U-site", htmlBody, ""); err != nil {
|
||||
log.Printf("[Portal] Error enviando correo de reseteo a %s: %v", email, err)
|
||||
}
|
||||
}()
|
||||
}
|
||||
|
||||
// SendPortalCredentialsEmail envía al usuario del portal su URL de acceso y contraseña inicial.
|
||||
func SendPortalCredentialsEmail(email, nombre, password string) {
|
||||
loginURL := absAppURL("/portal/login")
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
<!-- Portal: Recuperar contraseña -->
|
||||
<div class="w-full max-w-md mx-auto">
|
||||
<div class="text-center mb-8">
|
||||
<span class="w-14 h-14 rounded-2xl flex items-center justify-center text-white text-2xl font-bold mx-auto mb-4" style="background:#8eb02f">U</span>
|
||||
<h1 class="text-2xl font-bold text-slate-800">¿Olvidaste tu contraseña?</h1>
|
||||
<p class="text-slate-500 text-sm mt-1">Te enviaremos un enlace para restablecerla</p>
|
||||
</div>
|
||||
|
||||
{{ if .error }}
|
||||
<div class="bg-red-50 border border-red-200 text-red-700 rounded-xl px-4 py-3 mb-4 text-sm">
|
||||
{{ .error }}
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
{{ if .success }}
|
||||
<div class="bg-green-50 border border-green-200 text-green-700 rounded-xl px-4 py-3 mb-4 text-sm">
|
||||
{{ .success }}
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
<div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-8">
|
||||
<form method="POST" action="/portal/forgot-password">
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">Correo electrónico</label>
|
||||
<input type="email" name="email" required autofocus
|
||||
class="w-full border border-slate-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-[#8eb02f] transition-colors"
|
||||
placeholder="tu@email.com">
|
||||
</div>
|
||||
<button type="submit"
|
||||
class="w-full py-3 rounded-xl font-semibold text-white text-sm transition-colors"
|
||||
style="background:#8eb02f"
|
||||
onmouseover="this.style.background='#6d8c24'"
|
||||
onmouseout="this.style.background='#8eb02f'">
|
||||
Enviar enlace de recuperación
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
|
||||
<p class="text-center text-sm text-slate-400 mt-6">
|
||||
<a href="/portal/login" class="hover:text-slate-600 transition-colors">← Volver al inicio de sesión</a>
|
||||
</p>
|
||||
|
||||
<p class="text-center text-xs text-slate-400 mt-3">
|
||||
© 2025 U-site — Todos los derechos reservados
|
||||
</p>
|
||||
</div>
|
||||
@@ -12,6 +12,12 @@
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
{{ if .success }}
|
||||
<div class="bg-green-50 border border-green-200 text-green-700 rounded-xl px-4 py-3 mb-4 text-sm">
|
||||
{{ .success }}
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
<div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-8">
|
||||
<form method="POST" action="/portal/login">
|
||||
<div class="space-y-4">
|
||||
@@ -35,6 +41,11 @@
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
<div class="text-center mt-4">
|
||||
<a href="/portal/forgot-password" class="text-xs text-slate-400 hover:text-[#8eb02f] transition-colors">
|
||||
¿Olvidaste tu contraseña?
|
||||
</a>
|
||||
</div>
|
||||
</div>
|
||||
|
||||
<p class="text-center text-xs text-slate-400 mt-6">
|
||||
|
||||
@@ -0,0 +1,87 @@
|
||||
<!-- Portal: Nueva contraseña -->
|
||||
<div class="w-full max-w-md mx-auto">
|
||||
<div class="text-center mb-8">
|
||||
<span class="w-14 h-14 rounded-2xl flex items-center justify-center text-white text-2xl font-bold mx-auto mb-4" style="background:#8eb02f">U</span>
|
||||
<h1 class="text-2xl font-bold text-slate-800">Nueva contraseña</h1>
|
||||
<p class="text-slate-500 text-sm mt-1">Elige una contraseña segura para tu cuenta</p>
|
||||
</div>
|
||||
|
||||
{{ if .error }}
|
||||
<div class="bg-red-50 border border-red-200 text-red-700 rounded-xl px-4 py-3 mb-4 text-sm">
|
||||
{{ .error }}
|
||||
{{ if not .token }}
|
||||
<div class="mt-2">
|
||||
<a href="/portal/forgot-password" class="font-semibold underline">Solicitar un nuevo enlace</a>
|
||||
</div>
|
||||
{{ end }}
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
{{ if .token }}
|
||||
<div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-8">
|
||||
<form method="POST" action="/portal/reset-password" id="resetForm">
|
||||
<input type="hidden" name="token" value="{{ .token }}">
|
||||
<div class="space-y-4">
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">Nueva contraseña</label>
|
||||
<input type="password" name="password" id="password" required autofocus minlength="8"
|
||||
class="w-full border border-slate-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-[#8eb02f] transition-colors"
|
||||
placeholder="Mínimo 8 caracteres">
|
||||
</div>
|
||||
<div>
|
||||
<label class="block text-xs font-semibold text-slate-500 uppercase tracking-wide mb-1">Confirmar contraseña</label>
|
||||
<input type="password" name="confirm" id="confirm" required minlength="8"
|
||||
class="w-full border border-slate-200 rounded-xl px-4 py-3 text-sm outline-none focus:border-[#8eb02f] transition-colors"
|
||||
placeholder="Repite la contraseña">
|
||||
<p id="matchMsg" class="text-xs mt-1 hidden text-red-500">Las contraseñas no coinciden</p>
|
||||
</div>
|
||||
<button type="submit" id="submitBtn"
|
||||
class="w-full py-3 rounded-xl font-semibold text-white text-sm transition-colors"
|
||||
style="background:#8eb02f"
|
||||
onmouseover="this.style.background='#6d8c24'"
|
||||
onmouseout="this.style.background='#8eb02f'">
|
||||
Guardar nueva contraseña
|
||||
</button>
|
||||
</div>
|
||||
</form>
|
||||
</div>
|
||||
{{ else }}
|
||||
<div class="bg-white rounded-2xl shadow-lg border border-slate-200 p-8 text-center">
|
||||
<p class="text-slate-500 text-sm">Este enlace no es válido o ya fue utilizado.</p>
|
||||
<a href="/portal/forgot-password"
|
||||
class="inline-block mt-4 py-2 px-6 rounded-xl font-semibold text-white text-sm"
|
||||
style="background:#8eb02f">
|
||||
Solicitar nuevo enlace
|
||||
</a>
|
||||
</div>
|
||||
{{ end }}
|
||||
|
||||
<p class="text-center text-sm text-slate-400 mt-6">
|
||||
<a href="/portal/login" class="hover:text-slate-600 transition-colors">← Volver al inicio de sesión</a>
|
||||
</p>
|
||||
|
||||
<p class="text-center text-xs text-slate-400 mt-3">
|
||||
© 2025 U-site — Todos los derechos reservados
|
||||
</p>
|
||||
</div>
|
||||
|
||||
<script>
|
||||
const pw = document.getElementById('password');
|
||||
const cf = document.getElementById('confirm');
|
||||
const msg = document.getElementById('matchMsg');
|
||||
const btn = document.getElementById('submitBtn');
|
||||
|
||||
function checkMatch() {
|
||||
if (!cf || !pw) return;
|
||||
const match = pw.value === cf.value;
|
||||
if (cf.value.length > 0) {
|
||||
msg.classList.toggle('hidden', match);
|
||||
} else {
|
||||
msg.classList.add('hidden');
|
||||
}
|
||||
if (btn) btn.disabled = !match;
|
||||
}
|
||||
|
||||
if (pw) pw.addEventListener('input', checkMatch);
|
||||
if (cf) cf.addEventListener('input', checkMatch);
|
||||
</script>
|
||||
@@ -25,7 +25,8 @@ func PortalLoginPage(c *fiber.Ctx) error {
|
||||
return c.Redirect("/portal/dashboard")
|
||||
}
|
||||
return c.Render("portal/login", fiber.Map{
|
||||
"error": c.Query("error"),
|
||||
"error": c.Query("error"),
|
||||
"success": c.Query("success"),
|
||||
}, "layouts/portal_public")
|
||||
}
|
||||
|
||||
@@ -47,6 +48,92 @@ func PortalLogout(c *fiber.Ctx) error {
|
||||
return c.Redirect("/portal/login")
|
||||
}
|
||||
|
||||
// ─── Recuperar contraseña ────────────────────────────────────────────────────
|
||||
|
||||
func PortalForgotPasswordPage(c *fiber.Ctx) error {
|
||||
return c.Render("portal/forgot_password", fiber.Map{
|
||||
"success": c.Query("success"),
|
||||
"error": c.Query("error"),
|
||||
}, "layouts/portal_public")
|
||||
}
|
||||
|
||||
func PortalForgotPasswordPost(c *fiber.Ctx) error {
|
||||
email := strings.TrimSpace(c.FormValue("email"))
|
||||
|
||||
// Respuesta genérica siempre para no revelar si el email existe
|
||||
successMsg := "Si el correo está registrado, recibirás un enlace para restablecer tu contraseña."
|
||||
|
||||
u, err := models.GetPortalUserByEmail(email)
|
||||
if err == nil && u != nil && u.Activo {
|
||||
token, err := models.CreatePortalResetToken(u.ID)
|
||||
if err == nil {
|
||||
resetLink := services.GetPublicURL() + "/portal/reset-password?t=" + token
|
||||
services.SendPortalPasswordResetEmail(u.Email, u.Nombre, resetLink)
|
||||
} else {
|
||||
log.Printf("[Portal] Error creando token de reseteo para %s: %v", email, err)
|
||||
}
|
||||
}
|
||||
|
||||
return c.Redirect("/portal/forgot-password?success=" + url.QueryEscape(successMsg))
|
||||
}
|
||||
|
||||
func PortalResetPasswordPage(c *fiber.Ctx) error {
|
||||
token := c.Query("t")
|
||||
if token == "" {
|
||||
return c.Redirect("/portal/login")
|
||||
}
|
||||
_, err := models.GetValidPortalResetToken(token)
|
||||
if err != nil {
|
||||
return c.Render("portal/reset_password", fiber.Map{
|
||||
"error": err.Error(),
|
||||
"token": "",
|
||||
}, "layouts/portal_public")
|
||||
}
|
||||
return c.Render("portal/reset_password", fiber.Map{
|
||||
"token": token,
|
||||
"error": "",
|
||||
}, "layouts/portal_public")
|
||||
}
|
||||
|
||||
func PortalResetPasswordPost(c *fiber.Ctx) error {
|
||||
token := c.FormValue("token")
|
||||
password := c.FormValue("password")
|
||||
confirm := c.FormValue("confirm")
|
||||
|
||||
renderError := func(msg string) error {
|
||||
return c.Render("portal/reset_password", fiber.Map{
|
||||
"token": token,
|
||||
"error": msg,
|
||||
}, "layouts/portal_public")
|
||||
}
|
||||
|
||||
if token == "" || password == "" || confirm == "" {
|
||||
return renderError("Todos los campos son obligatorios.")
|
||||
}
|
||||
if password != confirm {
|
||||
return renderError("Las contraseñas no coinciden.")
|
||||
}
|
||||
if len(password) < 8 {
|
||||
return renderError("La contraseña debe tener al menos 8 caracteres.")
|
||||
}
|
||||
|
||||
record, err := models.GetValidPortalResetToken(token)
|
||||
if err != nil {
|
||||
return renderError(err.Error())
|
||||
}
|
||||
|
||||
hashed, err := app.Http.Hash.Create(password)
|
||||
if err != nil {
|
||||
return renderError("Error al procesar la contraseña. Intenta de nuevo.")
|
||||
}
|
||||
if err := models.UpdatePortalUserPassword(record.PortalUserID, hashed); err != nil {
|
||||
return renderError("Error al actualizar la contraseña. Intenta de nuevo.")
|
||||
}
|
||||
_ = models.MarkPortalResetTokenUsed(record.ID)
|
||||
|
||||
return c.Redirect("/portal/login?success=" + url.QueryEscape("Contraseña actualizada. Ya puedes ingresar."))
|
||||
}
|
||||
|
||||
// ─── Dashboard ────────────────────────────────────────────────────────────────
|
||||
|
||||
func PortalDashboard(c *fiber.Ctx) error {
|
||||
|
||||
@@ -11,6 +11,10 @@ func PortalRoutes(app fiber.Router) {
|
||||
app.Get("/portal/login", controllers.PortalLoginPage)
|
||||
app.Post("/portal/login", controllers.PortalLoginPost)
|
||||
app.Get("/portal/logout", controllers.PortalLogout)
|
||||
app.Get("/portal/forgot-password", controllers.PortalForgotPasswordPage)
|
||||
app.Post("/portal/forgot-password", controllers.PortalForgotPasswordPost)
|
||||
app.Get("/portal/reset-password", controllers.PortalResetPasswordPage)
|
||||
app.Post("/portal/reset-password", controllers.PortalResetPasswordPost)
|
||||
|
||||
// ─── Rutas protegidas ──────────────────────────────────────────────────────
|
||||
portal := app.Group("/portal").Use(middlewares.PortalAuth())
|
||||
|
||||
Reference in New Issue
Block a user