modularised webserver and auth systems

This commit is contained in:
2026-01-04 01:14:06 +11:00
parent 4a21ba3821
commit 28b7ba34f0
36 changed files with 451 additions and 774 deletions

View File

@@ -4,16 +4,16 @@ import (
"context"
"database/sql"
"net/http"
"strings"
"time"
"projectreshoot/internal/config"
"git.haelnorr.com/h/golib/hws"
"git.haelnorr.com/h/golib/hwsauth"
"projectreshoot/internal/models"
"projectreshoot/internal/view/component/form"
"projectreshoot/internal/view/page"
"git.haelnorr.com/h/golib/cookies"
"git.haelnorr.com/h/golib/hlog"
"git.haelnorr.com/h/golib/jwt"
"github.com/pkg/errors"
)
@@ -32,6 +32,9 @@ func validateLogin(
err = user.CheckPassword(tx, formPassword)
if err != nil {
if !strings.Contains(err.Error(), "Username or password incorrect") {
return nil, errors.Wrap(err, "user.CheckPassword")
}
return nil, errors.New("Username or password incorrect")
}
return user, nil
@@ -51,10 +54,9 @@ func checkRememberMe(r *http.Request) bool {
// and on fail will return the login form again, passing the error to the
// template for user feedback
func LoginRequest(
config *config.Config,
logger *hlog.Logger,
server *hws.Server,
auth *hwsauth.Authenticator[*models.User],
conn *sql.DB,
tokenGen *jwt.TokenGenerator,
) http.Handler {
return http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
@@ -64,8 +66,7 @@ func LoginRequest(
// Start the transaction
tx, err := conn.BeginTx(ctx, nil)
if err != nil {
logger.Warn().Err(err).Msg("Failed to set token cookies")
w.WriteHeader(http.StatusServiceUnavailable)
server.ThrowWarn(w, hws.NewError(http.StatusServiceUnavailable, "Login failed", err))
return
}
r.ParseForm()
@@ -73,8 +74,7 @@ func LoginRequest(
if err != nil {
tx.Rollback()
if err.Error() != "Username or password incorrect" {
logger.Warn().Caller().Err(err).Msg("Login request failed")
w.WriteHeader(http.StatusInternalServerError)
server.ThrowWarn(w, hws.NewError(http.StatusInternalServerError, "Login failed", err))
} else {
form.LoginForm(err.Error()).Render(r.Context(), w)
}
@@ -82,11 +82,10 @@ func LoginRequest(
}
rememberMe := checkRememberMe(r)
err = jwt.SetTokenCookies(w, r, tokenGen, user.ID, true, rememberMe, config.SSL)
err = auth.Login(w, r, user, rememberMe)
if err != nil {
tx.Rollback()
w.WriteHeader(http.StatusInternalServerError)
logger.Warn().Caller().Err(err).Msg("Failed to set token cookies")
server.ThrowWarn(w, hws.NewError(http.StatusInternalServerError, "Login failed", err))
return
}