package hwsauth import ( "context" "database/sql" ) 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 *sql.Tx, 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) *authenticatedModel[T] { model, ok := ctx.Value("hwsauth context key authenticated-model").(*authenticatedModel[T]) if !ok { return nil } return model } func (auth *Authenticator[T]) CurrentModel(ctx context.Context) T { model := getAuthorizedModel[T](ctx) if model == nil { return getNil[T]() } return model.model }