package handler import ( "fmt" "net/http" "sirlab.de/go/knowyt/user" ) func (authMux *AuthMux) PrivateOrPublicHandleFunc(pattern string, privateHandlerFunc PrivateHandlerFunc, publicHandlerFunc HandlerFunc) { authMux.mux.HandleFunc(pattern, func(w http.ResponseWriter, r *http.Request) { usr, err := authMux.getUserFromSession(r) if err != nil { // could not authenticate publicHandlerFunc(w, r) } else { privateHandlerFunc(usr, w, r) } }) } func (authMux *AuthMux) PrivateHandleFunc(pattern string, handlerFunc PrivateHandlerFunc) { authMux.PrivateOrPublicHandleFunc(pattern, handlerFunc, authMux.accessDenied) } 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) { usr, err := authMux.validateSessionAndGetUser(r) if err != nil { return nil, fmt.Errorf("invalid cookie") } if usr.IsAdmin() { if cookieCameo, err := r.Cookie("knowyt-auth-cameo"); err == nil { if usrCameo, err := authMux.app.GetUserById(cookieCameo.Value); err == nil { usrNew := usrCameo.DeepCloneUserObj() usrNew.SetCameo(usr) return usrNew, nil } } return usr, nil } // check if game is active gm, err := authMux.app.GetGameById(usr.GetGameId()) if err != nil { return nil, err } if !gm.IsActive() { return nil, fmt.Errorf("game %s disabled for user %s (%s)", gm.GetId(), usr.GetId(), usr.GetName()) } return usr, nil }