created hwsauth module
This commit is contained in:
42
hwsauth/middleware.go
Normal file
42
hwsauth/middleware.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package hwsauth
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"projectreshoot/pkg/hws"
|
||||
"slices"
|
||||
"time"
|
||||
)
|
||||
|
||||
func (auth *Authenticator[T]) Authenticate() hws.Middleware {
|
||||
return auth.server.NewMiddleware(auth.authenticate())
|
||||
}
|
||||
|
||||
func (auth *Authenticator[T]) 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
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 10*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Start the transaction
|
||||
tx, err := auth.conn.BeginTx(ctx, nil)
|
||||
if err != nil {
|
||||
return nil, hws.NewError(http.StatusServiceUnavailable, "Unable to start transaction", err)
|
||||
}
|
||||
model, err := auth.getAuthenticatedUser(tx, w, r)
|
||||
if err != nil {
|
||||
tx.Rollback()
|
||||
auth.logger.Debug().
|
||||
Str("remote_addr", r.RemoteAddr).
|
||||
Err(err).
|
||||
Msg("Failed to authenticate user")
|
||||
return r, nil
|
||||
}
|
||||
tx.Commit()
|
||||
authContext := setAuthenticatedModel(r.Context(), model)
|
||||
newReq := r.WithContext(authContext)
|
||||
return newReq, nil
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user