This repository has been archived on 2025-08-09. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
web-app-template/handler/auth.go

88 lines
2.9 KiB
Go

package handler
import (
"me-fit/service"
"me-fit/utils"
"time"
"database/sql"
"net/http"
)
type HandlerAuth interface {
handle(router *http.ServeMux)
}
type HandlerAuthImpl struct {
db *sql.DB
service service.ServiceAuth
}
func NewHandlerAuth(db *sql.DB, service service.ServiceAuth) HandlerAuth {
return HandlerAuthImpl{
db: db,
service: service,
}
}
func (handler HandlerAuthImpl) handle(router *http.ServeMux) {
// Don't use auth middleware for these routes, as it makes redirecting very difficult, if the mail is not yet verified
router.Handle("/auth/signin", service.HandleSignInPage(handler.db))
router.Handle("/auth/signup", service.HandleSignUpPage(handler.db))
router.Handle("/auth/verify", service.HandleSignUpVerifyPage(handler.db)) // Hint for the user to verify their email
router.Handle("/auth/delete-account", service.HandleDeleteAccountPage(handler.db))
router.Handle("/auth/verify-email", service.HandleSignUpVerifyResponsePage(handler.db)) // The link contained in the email
router.Handle("/auth/change-password", service.HandleChangePasswordPage(handler.db))
router.Handle("/auth/reset-password", service.HandleResetPasswordPage(handler.db))
router.Handle("/api/auth/signup", service.HandleSignUpComp(handler.db))
router.Handle("/api/auth/signin", handler.handleSignIn())
router.Handle("/api/auth/signout", service.HandleSignOutComp(handler.db))
router.Handle("/api/auth/delete-account", service.HandleDeleteAccountComp(handler.db))
router.Handle("/api/auth/verify-resend", service.HandleVerifyResendComp(handler.db))
router.Handle("/api/auth/change-password", service.HandleChangePasswordComp(handler.db))
router.Handle("/api/auth/reset-password", service.HandleResetPasswordComp(handler.db))
router.Handle("/api/auth/reset-password-actual", service.HandleActualResetPasswordComp(handler.db))
}
var (
securityWaitDuration = 250 * time.Millisecond
)
func (handler HandlerAuthImpl) handleSignIn() http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, err := utils.WaitMinimumTime(securityWaitDuration, func() (*service.User, error) {
var email = r.FormValue("email")
var password = r.FormValue("password")
user, err := handler.service.SignIn(email, password)
if err != nil {
return nil, err
}
err = service.TryCreateSessionAndSetCookie(r, w, handler.db, user.Id)
if err != nil {
return nil, err
}
return user, nil
})
if err != nil {
if err == service.ErrInvaidCredentials {
utils.TriggerToast(w, r, "error", "Invalid email or password")
http.Error(w, "Invalid email or password", http.StatusUnauthorized)
} else {
utils.LogError("Error signing in", err)
http.Error(w, "An error occurred", http.StatusInternalServerError)
}
return
}
if user.EmailVerified {
utils.DoRedirect(w, r, "/")
} else {
utils.DoRedirect(w, r, "/auth/verify")
}
}
}