package handler import ( "fmt" "net/http" "sirlab.de/go/knyt/user" ) func (authMux *AuthMux) PrivateHandleFunc(pattern string, handlerFunc HandlerFunc) { authMux.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { if authMux.isAuthenticated(r) { handlerFunc(w, r) return } authMux.accessDenied(w, r) }) } func (authMux *AuthMux) PrivateHandle(pattern string, handler http.Handler) { authMux.PrivateHandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { handler.ServeHTTP(w, r) }) } func (authMux *AuthMux) accessDenied(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusForbidden) fmt.Fprintf(w, "Forbidden") } func (authMux *AuthMux) isAuthenticated(r *http.Request) bool { _, err := authMux.getUserFromSession(r) if err != nil { return false } return true } func (authMux *AuthMux) getUserFromSession(r *http.Request) (*user.User, error) { authCookie, err := r.Cookie("knyt-auth") if err != nil { fmt.Printf("%v\n", err) return nil, fmt.Errorf("invalid cookie") } usr, usrErr := authMux.app.GetUserById(authCookie.Value) if usrErr != nil { return nil, fmt.Errorf("invalid cookie") } return usr, nil }