forked from tangled.org/core
Monorepo for Tangled — https://tangled.org
1package middleware 2 3import ( 4 "fmt" 5 "net/http" 6 "net/url" 7 8 "tangled.org/core/appview/oauth" 9 "tangled.org/core/appview/session" 10 "tangled.org/core/log" 11) 12 13// WithSession resumes atp session from cookie, ensure it's not malformed and 14// pass the session through context 15func WithSession(o *oauth.OAuth) middlewareFunc { 16 return func(next http.Handler) http.Handler { 17 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 18 atSess, err := o.ResumeSession(r) 19 if err != nil { 20 next.ServeHTTP(w, r) 21 return 22 } 23 24 sess := session.New(atSess) 25 26 ctx := session.IntoContext(r.Context(), sess) 27 next.ServeHTTP(w, r.WithContext(ctx)) 28 }) 29 } 30} 31 32// AuthMiddleware ensures the request is authorized and redirect to login page 33// when unauthorized 34func AuthMiddleware() middlewareFunc { 35 return func(next http.Handler) http.Handler { 36 return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { 37 ctx := r.Context() 38 l := log.FromContext(ctx) 39 40 returnURL := "/" 41 if u, err := url.Parse(r.Header.Get("Referer")); err == nil { 42 returnURL = u.RequestURI() 43 } 44 45 loginURL := fmt.Sprintf("/login?return_url=%s", url.QueryEscape(returnURL)) 46 47 redirectFunc := func(w http.ResponseWriter, r *http.Request) { 48 http.Redirect(w, r, loginURL, http.StatusTemporaryRedirect) 49 } 50 if r.Header.Get("HX-Request") == "true" { 51 redirectFunc = func(w http.ResponseWriter, _ *http.Request) { 52 w.Header().Set("HX-Redirect", loginURL) 53 w.WriteHeader(http.StatusOK) 54 } 55 } 56 57 sess := session.FromContext(ctx) 58 if sess == nil { 59 l.Debug("no session, redirecting...") 60 redirectFunc(w, r) 61 return 62 } 63 64 next.ServeHTTP(w, r) 65 }) 66 } 67}