feat(06-01): grow router verbs, factories, and guard registry

- Add Post/Put/Patch/Delete on pact.Router and surf Router/Group
- Resolve name:param middleware via RegisterMiddlewareFactory
- Add bouncer.Registry with Guard, CredentialGuard, UnauthorizedWriter
- Re-express jwt as NewJWTGuard without changing Middleware bodies
This commit is contained in:
Jakub Zych
2026-09-19 18:59:12 +02:00
parent ecab09c37a
commit d376b1be2d
9 changed files with 678 additions and 14 deletions

View File

@@ -63,6 +63,53 @@ func Middleware(secret string, users UserProvider) func(http.Handler) http.Handl
}
}
type jwtGuard struct {
secret string
users UserProvider
}
var (
_ Guard = (*jwtGuard)(nil)
_ UnauthorizedWriter = (*jwtGuard)(nil)
)
// NewJWTGuard adapts the existing bearerToken -> Verify -> users.FindByID
// chain (identical to Middleware's body) into a Guard + UnauthorizedWriter,
// so Registry.Middleware("jwt") is byte-identical to bouncer.Middleware.
func NewJWTGuard(secret string, users UserProvider) Guard {
return &jwtGuard{secret: secret, users: users}
}
func (g *jwtGuard) Authenticate(r *http.Request) (*Principal, error) {
raw, err := bearerToken(r)
if err != nil {
return nil, err
}
sub, err := Verify(raw, g.secret)
if err != nil {
return nil, err
}
id, err := strconv.ParseUint(sub, 10, 64)
if err != nil || id == 0 {
return nil, errors.New(msgUserNotFound)
}
if g.users == nil {
return nil, errors.New(msgUserNotFound)
}
user, err := g.users.FindByID(r.Context(), uint(id))
if err != nil {
return nil, errors.New("Authentication error")
}
if user == nil {
return nil, errors.New(msgUserNotFound)
}
return user, nil
}
func (g *jwtGuard) WriteUnauthorized(w http.ResponseWriter, err error) {
write401(w, err.Error())
}
// Verify parses a token with HS256 pinned and a required exp and sub.
func Verify(tokenString, secret string) (string, error) {
if strings.TrimSpace(secret) == "" {