Skip to content
Snippets Groups Projects
auth.go 1.5 KiB
Newer Older
package auth

import (
	"context"
gbe's avatar
gbe committed
	"fmt"
	"log"
	"net/http"
)

type contextKey string

type Provider interface {
	// Returns true if pass is a valid password for the given user
gbe's avatar
gbe committed
	Valid(ctx context.Context, user, pass string) (bool, error)
}

// Require wraps hdlr so that it requires authentication to use. Requests handled by hdlr will have the user
// name attached to their context. Use the User function to retrieve it.
func Require(hdlr http.HandlerFunc, provider Provider) http.HandlerFunc {
	return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		user, pass, ok := r.BasicAuth()
		if !ok {
			w.Header().Add("WWW-Authenticate", `Basic realm="In Vino Veritas"`)
			w.WriteHeader(http.StatusUnauthorized)

			return
		}

gbe's avatar
gbe committed
		valid, err := provider.Valid(r.Context(), user, pass)
		if err != nil {
			log.Printf("can't authenticate %s %s from %s: %s", r.Method, r.URL, r.RemoteAddr, err)

			w.WriteHeader(http.StatusInternalServerError)

			fmt.Fprintln(w, "can't confirm your authentication")

			return
		}

		if !valid {
			w.Header().Add("WWW-Authenticate", `Basic realm="In Vino Veritas"`)
			w.WriteHeader(http.StatusUnauthorized)

			return
		}

		key := contextKey("user")
		ctx := context.WithValue(r.Context(), key, user)

		hdlr(w, r.WithContext(ctx))
	})
}

// User returns the user from r's context. If r has no user in its context, the empty string will be returned.
func User(r *http.Request) string {
	val := r.Context().Value(contextKey("user"))
	if val == nil {
		return ""
	}

	return val.(string)
}