middleware.go

 1package auth
 2
 3import (
 4	"net/http"
 5
 6	"github.com/git-bug/git-bug/entity"
 7)
 8
 9// Middleware injects a fixed identity into every request context.
10// Used in local single-user mode where auth is implicit (identity comes from
11// git config at server startup rather than per-request login).
12func Middleware(fixedUserId entity.Id) func(http.Handler) http.Handler {
13	return func(next http.Handler) http.Handler {
14		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
15			ctx := CtxWithUser(r.Context(), fixedUserId)
16			next.ServeHTTP(w, r.WithContext(ctx))
17		})
18	}
19}
20
21// SessionMiddleware reads the session cookie on every request and, when a
22// valid session exists, injects the corresponding identity ID into the context.
23//
24// Requests without a valid session are served as unauthenticated rather than
25// rejected: GraphQL's userIdentity field returns null and mutations fail with
26// ErrNotAuthenticated. This allows the frontend to gracefully degrade rather
27// than receiving hard HTTP errors for every unauthenticated page load.
28func SessionMiddleware(store *SessionStore) func(http.Handler) http.Handler {
29	return func(next http.Handler) http.Handler {
30		return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
31			if cookie, err := r.Cookie(SessionCookie); err == nil {
32				if id, ok := store.Get(cookie.Value); ok {
33					r = r.WithContext(CtxWithUser(r.Context(), id))
34				}
35			}
36			next.ServeHTTP(w, r)
37		})
38	}
39}