package handler import ( "fmt" "net/http" "sirlab.de/go/knowyt/user" "strings" ) func (authMux *AuthMux) PrivateHandleFunc(pattern string, handlerFunc PrivateHandlerFunc) { authMux.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { usr, err := authMux.getUserFromSession(r) if err != nil { authMux.accessDenied(w, r) return } handlerFunc(usr, w, r) }) } func (authMux *AuthMux) accessDenied(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusForbidden) fmt.Fprintf(w, "Forbidden") } func (authMux *AuthMux) getUserFromSession(r *http.Request) (*user.User, error) { authCookie, err := r.Cookie("knowyt-auth") if err != nil { return nil, fmt.Errorf("invalid cookie") } vals := strings.SplitN(authCookie.Value, ":", 2) usr, usrErr := authMux.app.GetUserById(vals[0]) if usrErr != nil { return nil, fmt.Errorf("invalid cookie") } if usr.GetAuthCode() != vals[1] { return nil, fmt.Errorf("invalid cookie") } if usr.IsAdmin() { if cookieCameo, err := r.Cookie("knowyt-auth-cameo"); err == nil { if usrNew, err := authMux.app.GetUserById(cookieCameo.Value); err == nil { usrNew.SetCameo(usr) return usrNew, nil } } } return usr, nil }