389 lines
9.8 KiB
Go
389 lines
9.8 KiB
Go
package handlers
|
|
|
|
import (
|
|
"database/sql"
|
|
"fmt"
|
|
"strings"
|
|
|
|
"github.com/go-playground/validator/v10"
|
|
"github.com/labstack/echo/v4"
|
|
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/context"
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/form"
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/log"
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/middleware"
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/models/sqlc"
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/msg"
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/page"
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/redirect"
|
|
"git.grosinger.net/tgrosinger/saasitone/pkg/services"
|
|
"git.grosinger.net/tgrosinger/saasitone/templ/layouts"
|
|
"git.grosinger.net/tgrosinger/saasitone/templ/pages"
|
|
)
|
|
|
|
const (
|
|
routeNameForgotPassword = "forgot_password"
|
|
routeNameForgotPasswordSubmit = "forgot_password.submit"
|
|
routeNameLogin = "login"
|
|
routeNameLoginSubmit = "login.submit"
|
|
routeNameLogout = "logout"
|
|
routeNameRegister = "register"
|
|
routeNameRegisterSubmit = "register.submit"
|
|
routeNameResetPassword = "reset_password"
|
|
routeNameResetPasswordSubmit = "reset_password.submit"
|
|
routeNameVerifyEmail = "verify_email"
|
|
)
|
|
|
|
type (
|
|
Auth struct {
|
|
auth *services.AuthClient
|
|
mail *services.MailClient
|
|
db *services.DBClient
|
|
*services.TemplateRenderer
|
|
}
|
|
)
|
|
|
|
func init() {
|
|
Register(new(Auth))
|
|
}
|
|
|
|
func (h *Auth) Init(c *services.Container) error {
|
|
h.TemplateRenderer = c.TemplateRenderer
|
|
h.db = c.DB
|
|
h.auth = c.Auth
|
|
h.mail = c.Mail
|
|
return nil
|
|
}
|
|
|
|
func (h *Auth) Routes(g *echo.Group) {
|
|
g.GET("/logout", h.Logout, middleware.RequireAuthentication()).Name = routeNameLogout
|
|
g.GET("/email/verify/:token", h.VerifyEmail).Name = routeNameVerifyEmail
|
|
|
|
noAuth := g.Group("/user", middleware.RequireNoAuthentication())
|
|
noAuth.GET("/login", h.LoginPage).Name = routeNameLogin
|
|
noAuth.POST("/login", h.LoginSubmit).Name = routeNameLoginSubmit
|
|
noAuth.GET("/register", h.RegisterPage).Name = routeNameRegister
|
|
noAuth.POST("/register", h.RegisterSubmit).Name = routeNameRegisterSubmit
|
|
noAuth.GET("/password", h.ForgotPasswordPage).Name = routeNameForgotPassword
|
|
noAuth.POST("/password", h.ForgotPasswordSubmit).Name = routeNameForgotPasswordSubmit
|
|
|
|
resetGroup := noAuth.Group("/password/reset",
|
|
middleware.LoadUser(h.db),
|
|
middleware.LoadValidPasswordToken(h.auth),
|
|
)
|
|
resetGroup.GET("/token/:user/:password_token/:token", h.ResetPasswordPage).Name = routeNameResetPassword
|
|
resetGroup.POST("/token/:user/:password_token/:token", h.ResetPasswordSubmit).Name = routeNameResetPasswordSubmit
|
|
}
|
|
|
|
func (h *Auth) ForgotPasswordPage(ctx echo.Context) error {
|
|
p := page.New(ctx)
|
|
p.Title = "Forgot password"
|
|
p.LayoutComponent = layouts.Auth
|
|
|
|
f := form.Get[pages.ForgotPasswordForm](ctx)
|
|
component := pages.ForgotPassword(p, f)
|
|
|
|
return h.RenderPageTempl(ctx, p, component)
|
|
}
|
|
|
|
func (h *Auth) ForgotPasswordSubmit(ctx echo.Context) error {
|
|
var input pages.ForgotPasswordForm
|
|
|
|
succeed := func() error {
|
|
form.Clear(ctx)
|
|
msg.Success(ctx, "An email containing a link to reset your password will be sent to this address if it exists in our system.")
|
|
return h.ForgotPasswordPage(ctx)
|
|
}
|
|
|
|
err := form.Submit(ctx, &input)
|
|
|
|
switch err.(type) {
|
|
case nil:
|
|
case validator.ValidationErrors:
|
|
return h.ForgotPasswordPage(ctx)
|
|
default:
|
|
return err
|
|
}
|
|
|
|
// Attempt to load the user
|
|
u, err := h.db.C.GetUserByEmail(ctx.Request().Context(), strings.ToLower(input.Email))
|
|
if err == sql.ErrNoRows {
|
|
return succeed()
|
|
} else if err != nil {
|
|
return fail(err, "error querying user during forgot password")
|
|
}
|
|
|
|
// Generate the token
|
|
token, pt, err := h.auth.GeneratePasswordResetToken(ctx, u.ID)
|
|
if err != nil {
|
|
return fail(err, "error generating password reset token")
|
|
}
|
|
|
|
log.Ctx(ctx).Info("generated password reset token",
|
|
"user_id", u.ID,
|
|
)
|
|
|
|
// Email the user
|
|
url := ctx.Echo().Reverse(routeNameResetPassword, u.ID, pt.ID, token)
|
|
err = h.mail.
|
|
Compose().
|
|
To(u.Email).
|
|
Subject("Reset your password").
|
|
Body(fmt.Sprintf("Go here to reset your password: %s", url)).
|
|
Send(ctx)
|
|
if err != nil {
|
|
return fail(err, "error sending password reset email")
|
|
}
|
|
|
|
return succeed()
|
|
}
|
|
|
|
func (h *Auth) LoginPage(ctx echo.Context) error {
|
|
p := page.New(ctx)
|
|
p.Title = "Log in"
|
|
p.LayoutComponent = layouts.Auth
|
|
|
|
f := form.Get[pages.LoginForm](ctx)
|
|
component := pages.Login(p, f)
|
|
|
|
return h.RenderPageTempl(ctx, p, component)
|
|
}
|
|
|
|
func (h *Auth) LoginSubmit(ctx echo.Context) error {
|
|
var input pages.LoginForm
|
|
|
|
authFailed := func() error {
|
|
input.SetFieldError("Email", "")
|
|
input.SetFieldError("Password", "")
|
|
msg.Danger(ctx, "Invalid credentials. Please try again.")
|
|
return h.LoginPage(ctx)
|
|
}
|
|
|
|
err := form.Submit(ctx, &input)
|
|
|
|
switch err.(type) {
|
|
case nil:
|
|
case validator.ValidationErrors:
|
|
return h.LoginPage(ctx)
|
|
default:
|
|
return err
|
|
}
|
|
|
|
// Attempt to load the user
|
|
u, err := h.db.C.GetUserByEmail(ctx.Request().Context(), strings.ToLower(input.Email))
|
|
if err == sql.ErrNoRows {
|
|
return authFailed()
|
|
} else if err != nil {
|
|
return fail(err, "error querying user during login")
|
|
}
|
|
|
|
// Check if the password is correct
|
|
err = h.auth.CheckPassword(input.Password, u.Password)
|
|
if err != nil {
|
|
return authFailed()
|
|
}
|
|
|
|
// Log the user in
|
|
err = h.auth.Login(ctx, u.ID)
|
|
if err != nil {
|
|
return fail(err, "unable to log in user")
|
|
}
|
|
|
|
msg.Success(ctx, fmt.Sprintf("Welcome back, <strong>%s</strong>. You are now logged in.", u.Name))
|
|
|
|
return redirect.New(ctx).
|
|
Route(routeNameHome).
|
|
Go()
|
|
}
|
|
|
|
func (h *Auth) Logout(ctx echo.Context) error {
|
|
if err := h.auth.Logout(ctx); err == nil {
|
|
msg.Success(ctx, "You have been logged out successfully.")
|
|
} else {
|
|
msg.Danger(ctx, "An error occurred. Please try again.")
|
|
}
|
|
return redirect.New(ctx).
|
|
Route(routeNameHome).
|
|
Go()
|
|
}
|
|
|
|
func (h *Auth) RegisterPage(ctx echo.Context) error {
|
|
p := page.New(ctx)
|
|
p.Title = "Register"
|
|
p.LayoutComponent = layouts.Auth
|
|
|
|
f := form.Get[pages.RegisterForm](ctx)
|
|
component := pages.Register(p, f)
|
|
|
|
return h.RenderPageTempl(ctx, p, component)
|
|
}
|
|
|
|
func (h *Auth) RegisterSubmit(ctx echo.Context) error {
|
|
var input pages.RegisterForm
|
|
|
|
err := form.Submit(ctx, &input)
|
|
|
|
switch err.(type) {
|
|
case nil:
|
|
case validator.ValidationErrors:
|
|
return h.RegisterPage(ctx)
|
|
default:
|
|
return err
|
|
}
|
|
|
|
// Hash the password
|
|
pwHash, err := h.auth.HashPassword(input.Password)
|
|
if err != nil {
|
|
return fail(err, "unable to hash password")
|
|
}
|
|
|
|
// Attempt creating the user
|
|
u, err := h.db.C.CreateUser(ctx.Request().Context(), sqlc.CreateUserParams{
|
|
Name: input.Name,
|
|
Email: input.Email,
|
|
Password: pwHash,
|
|
})
|
|
if err != nil {
|
|
if strings.HasPrefix(err.Error(), "UNIQUE constraint failed") {
|
|
msg.Warning(ctx, "A user with this email address already exists. Please log in.")
|
|
return redirect.New(ctx).
|
|
Route(routeNameLogin).
|
|
Go()
|
|
}
|
|
|
|
return fail(err, "unable to create user")
|
|
}
|
|
|
|
log.Ctx(ctx).Info("user created",
|
|
"user_name", u.Name,
|
|
"user_id", u.ID,
|
|
)
|
|
|
|
// Log the user in
|
|
err = h.auth.Login(ctx, u.ID)
|
|
if err != nil {
|
|
log.Ctx(ctx).Error("unable to log user in",
|
|
"error", err,
|
|
"user_id", u.ID,
|
|
)
|
|
msg.Info(ctx, "Your account has been created.")
|
|
return redirect.New(ctx).
|
|
Route(routeNameLogin).
|
|
Go()
|
|
}
|
|
|
|
msg.Success(ctx, "Your account has been created. You are now logged in.")
|
|
|
|
// Send the verification email
|
|
h.sendVerificationEmail(ctx, u)
|
|
|
|
return redirect.New(ctx).
|
|
Route(routeNameHome).
|
|
Go()
|
|
}
|
|
|
|
func (h *Auth) sendVerificationEmail(ctx echo.Context, usr sqlc.User) {
|
|
// Generate a token
|
|
token, err := h.auth.GenerateEmailVerificationToken(usr.Email)
|
|
if err != nil {
|
|
log.Ctx(ctx).Error("unable to generate email verification token",
|
|
"user_id", usr.ID,
|
|
"error", err,
|
|
)
|
|
return
|
|
}
|
|
|
|
// Send the email
|
|
url := ctx.Echo().Reverse(routeNameVerifyEmail, token)
|
|
err = h.mail.
|
|
Compose().
|
|
To(usr.Email).
|
|
Subject("Confirm your email address").
|
|
Body(fmt.Sprintf("Click here to confirm your email address: %s", url)).
|
|
Send(ctx)
|
|
if err != nil {
|
|
log.Ctx(ctx).Error("unable to send email verification link",
|
|
"user_id", usr.ID,
|
|
"error", err,
|
|
)
|
|
return
|
|
}
|
|
|
|
msg.Info(ctx, "An email was sent to you to verify your email address.")
|
|
}
|
|
|
|
func (h *Auth) ResetPasswordPage(ctx echo.Context) error {
|
|
p := page.New(ctx)
|
|
p.Title = "Reset password"
|
|
p.LayoutComponent = layouts.Auth
|
|
|
|
f := form.Get[pages.ResetPasswordForm](ctx)
|
|
component := pages.ResetPassword(p, f)
|
|
|
|
return h.RenderPageTempl(ctx, p, component)
|
|
}
|
|
|
|
func (h *Auth) ResetPasswordSubmit(ctx echo.Context) error {
|
|
var input pages.ResetPasswordForm
|
|
|
|
err := form.Submit(ctx, &input)
|
|
|
|
switch err.(type) {
|
|
case nil:
|
|
case validator.ValidationErrors:
|
|
return h.ResetPasswordPage(ctx)
|
|
default:
|
|
return err
|
|
}
|
|
|
|
// Hash the new password
|
|
hash, err := h.auth.HashPassword(input.Password)
|
|
if err != nil {
|
|
return fail(err, "unable to hash password")
|
|
}
|
|
|
|
// Get the requesting user
|
|
usr := ctx.Get(context.UserKey).(*sqlc.User)
|
|
|
|
// Update the user
|
|
err = h.db.C.UpdateUserPassword(ctx.Request().Context(), sqlc.UpdateUserPasswordParams{
|
|
Password: hash,
|
|
ID: usr.ID,
|
|
})
|
|
if err != nil {
|
|
return fail(err, "unable to update password")
|
|
}
|
|
|
|
// Delete all password tokens for this user
|
|
err = h.auth.DeletePasswordTokens(ctx, usr.ID)
|
|
if err != nil {
|
|
return fail(err, "unable to delete password tokens")
|
|
}
|
|
|
|
msg.Success(ctx, "Your password has been updated.")
|
|
return redirect.New(ctx).
|
|
Route(routeNameLogin).
|
|
Go()
|
|
}
|
|
|
|
func (h *Auth) VerifyEmail(ctx echo.Context) error {
|
|
token := ctx.Param("token")
|
|
email, err := h.auth.ValidateEmailVerificationToken(token)
|
|
if err != nil {
|
|
msg.Warning(ctx, "The link is either invalid or has expired.")
|
|
return redirect.New(ctx).
|
|
Route(routeNameHome).
|
|
Go()
|
|
}
|
|
|
|
err = h.db.C.UpdateUserSetVerified(ctx.Request().Context(), email)
|
|
if err != nil {
|
|
return fail(err, "failed to set user as verified")
|
|
}
|
|
|
|
msg.Success(ctx, "Your email has been successfully verified.")
|
|
return redirect.New(ctx).
|
|
Route(routeNameHome).
|
|
Go()
|
|
}
|