package auth
import (
"context"
"net/http"
)
type User struct {
ID int64
Name string
Email string
Admin bool
}
type contextKey string
const userContextKey contextKey = "user"
type AuthenticateFunc func(r *http.Request) (*User, error)
func RequireAuth(authFunc AuthenticateFunc) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
user, err := authFunc(r)
if err != nil || user == nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), userContextKey, user)
r = r.WithContext(ctx)
}
}
func GetUserFromContext(ctx context.Context) *User {
user, ok := ctx.Value(userContextKey).(*User)
if !ok {
return nil
}
return user
}
func MockAuthenticate(r *http.Request) (*User, error) {
return &User{
ID: 1,
Name: "admin",
Email: "admin@example.com",
Admin: true,
}, nil
}
func AuthenticateUser(userStore *UserStore, username, password string) (*User, error) {
user, exists := userStore.GetUserByName(username)
if !exists {
return nil, nil
}
if !CheckPassword(password, user.Password) {
return nil, nil
}
return user, nil
}