Files
golib/hwsauth/model.go
Haelnorr 1b25e2f0a5 Refactor database interface to use *sql.DB directly
Simplified the database layer by removing custom interface wrappers
and using standard library *sql.DB and *sql.Tx types directly.

Changes:
- Removed DBConnection and DBTransaction interfaces from database.go
- Removed NewDBConnection() wrapper function
- Updated TokenGenerator to use *sql.DB instead of DBConnection
- Updated all validation and revocation methods to accept *sql.Tx
- Updated TableManager to work with *sql.DB directly
- Updated all tests to use db.Begin() instead of custom wrappers
- Fixed GeneratorConfig.DB field (was DBConn)
- Updated documentation in doc.go with correct API usage

Benefits:
- Simpler API with fewer abstractions
- Works directly with database/sql standard library
- Compatible with GORM (via gormDB.DB()) and Bun (share same *sql.DB)
- Easier to understand and maintain
- No unnecessary wrapper layers

Breaking changes:
- GeneratorConfig.DBConn renamed to GeneratorConfig.DB
- Removed NewDBConnection() function - pass *sql.DB directly
- ValidateAccess/ValidateRefresh now accept *sql.Tx instead of DBTransaction
- Token.Revoke/CheckNotRevoked now accept *sql.Tx instead of DBTransaction

🤖 Generated with [Claude Code](https://claude.com/claude-code)

Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
2026-01-11 17:39:30 +11:00

59 lines
1.3 KiB
Go

package hwsauth
import (
"context"
)
type authenticatedModel[T Model] struct {
model T
fresh int64
}
func getNil[T Model]() T {
var result T
return result
}
type Model interface {
ID() int
}
type ContextLoader[T Model] func(ctx context.Context) T
type LoadFunc[T Model] func(tx DBTransaction, id int) (T, error)
// Return a new context with the user added in
func setAuthenticatedModel[T Model](ctx context.Context, m authenticatedModel[T]) context.Context {
return context.WithValue(ctx, "hwsauth context key authenticated-model", m)
}
// Retrieve a user from the given context. Returns nil if not set
func getAuthorizedModel[T Model](ctx context.Context) (model authenticatedModel[T], ok bool) {
defer func() {
if r := recover(); r != nil {
// panic happened, return ok = false
ok = false
model = authenticatedModel[T]{}
}
}()
model, cok := ctx.Value("hwsauth context key authenticated-model").(authenticatedModel[T])
if !cok {
return authenticatedModel[T]{}, false
}
return model, true
}
func (auth *Authenticator[T]) CurrentModel(ctx context.Context) T {
auth.logger.Debug().Any("context", ctx).Msg("")
if ctx == nil {
return getNil[T]()
}
model, ok := getAuthorizedModel[T](ctx)
if !ok {
result := getNil[T]()
auth.logger.Debug().Any("model", result).Msg("")
return result
}
return model.model
}