feat(portal): agregar flujo de recuperación de contraseña
- Nuevo modelo PortalPasswordResetToken con token seguro (32 bytes, 1h vigencia) - AutoMigrate del nuevo modelo en main.go - SendPortalPasswordResetEmail con diseño consistente al app - Handlers: PortalForgotPasswordPage/Post y PortalResetPasswordPost/Page - Rutas públicas GET/POST /portal/forgot-password y /portal/reset-password - Vistas forgot_password.html y reset_password.html con validación JS - Enlace ¿Olvidaste tu contraseña? en login.html + soporte mensaje success Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
This commit is contained in:
co-authored by
Copilot
parent
b5e6a9285f
commit
6e27032ac6
@@ -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")
|
||||
|
||||
Reference in New Issue
Block a user