56 lines
1.3 KiB
Go
56 lines
1.3 KiB
Go
|
package auth
|
||
|
|
||
|
import (
|
||
|
"SimpleTutorialHosting/internal/models"
|
||
|
"context"
|
||
|
"errors"
|
||
|
"net/http"
|
||
|
)
|
||
|
|
||
|
type DevAuthenticator struct {
|
||
|
users map[string]models.User
|
||
|
}
|
||
|
|
||
|
func NewDevAuthenticator(cfg *models.DevAuthConfig) (*DevAuthenticator, error) {
|
||
|
if cfg == nil {
|
||
|
return nil, errors.New("no dev auth config")
|
||
|
}
|
||
|
|
||
|
userMap := make(map[string]models.User)
|
||
|
for _, user := range cfg.Users {
|
||
|
userMap[user.Username] = user
|
||
|
}
|
||
|
return &DevAuthenticator{
|
||
|
users: userMap,
|
||
|
}, nil
|
||
|
}
|
||
|
|
||
|
func (a *DevAuthenticator) Authenticate(next http.Handler) http.Handler {
|
||
|
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||
|
username, password, ok := r.BasicAuth()
|
||
|
if !ok {
|
||
|
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
|
||
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
user, exists := a.users[username]
|
||
|
if !exists || password != "devpass" {
|
||
|
http.Error(w, "Unauthorized", http.StatusUnauthorized)
|
||
|
return
|
||
|
}
|
||
|
|
||
|
ctx := context.WithValue(r.Context(), UserContextKey, &user)
|
||
|
next.ServeHTTP(w, r.WithContext(ctx))
|
||
|
})
|
||
|
}
|
||
|
|
||
|
func (a *DevAuthenticator) GetUser(r *http.Request) (*models.User, error) {
|
||
|
user, ok := r.Context().Value(UserContextKey).(*models.User)
|
||
|
if !ok {
|
||
|
return nil, errors.New("no user in context")
|
||
|
}
|
||
|
|
||
|
return user, nil
|
||
|
}
|