refactor to improve database operability in hwsauth

This commit is contained in:
2026-01-11 23:00:50 +11:00
parent ae4094d426
commit 4c5af63ea2
17 changed files with 582 additions and 96 deletions

View File

@@ -8,11 +8,18 @@ import (
"time"
)
func (auth *Authenticator[T]) Authenticate() hws.Middleware {
// Authenticate returns the main authentication middleware.
// This middleware validates JWT tokens, refreshes expired tokens, and adds
// the authenticated user to the request context.
//
// Example:
//
// server.AddMiddleware(auth.Authenticate())
func (auth *Authenticator[T, TX]) Authenticate() hws.Middleware {
return auth.server.NewMiddleware(auth.authenticate())
}
func (auth *Authenticator[T]) authenticate() hws.MiddlewareFunc {
func (auth *Authenticator[T, TX]) authenticate() hws.MiddlewareFunc {
return func(w http.ResponseWriter, r *http.Request) (*http.Request, *hws.HWSError) {
if slices.Contains(auth.ignoredPaths, r.URL.Path) {
return r, nil
@@ -21,11 +28,16 @@ func (auth *Authenticator[T]) authenticate() hws.MiddlewareFunc {
defer cancel()
// Start the transaction
tx, err := auth.conn.BeginTx(ctx, nil)
tx, err := auth.beginTx(ctx)
if err != nil {
return nil, &hws.HWSError{Message: "Unable to start transaction", StatusCode: http.StatusServiceUnavailable, Error: err}
}
model, err := auth.getAuthenticatedUser(tx, w, r)
// Type assert to TX - safe because user's beginTx should return their TX type
txTyped, ok := tx.(TX)
if !ok {
return nil, &hws.HWSError{Message: "Transaction type mismatch", StatusCode: http.StatusInternalServerError, Error: err}
}
model, err := auth.getAuthenticatedUser(txTyped, w, r)
if err != nil {
tx.Rollback()
auth.logger.Debug().