package server import ( "context" "log" "net/http" "git.nefrace.ru/nefrace/nashboard/storage" ) type CtxValue string func (s Server) UserInContext(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { ctx := r.Context() user, isAuthorized := s.authorizedByHeader(r) if isAuthorized { ctx = context.WithValue(ctx, CtxValue("user"), user) } next.ServeHTTP(w, r.WithContext(ctx)) }) } func (s Server) AuthorizedOnly(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { _, ok := r.Context().Value(CtxValue("user")).(*storage.User) if !ok { w.WriteHeader(http.StatusUnauthorized) return } next.ServeHTTP(w, r) }) } func (s Server) authorizedByHeader(r *http.Request) (*storage.User, bool) { sessionHeader := r.Header.Get("SessionID") session, err := s.Db.GetSessionByToken(sessionHeader) if err != nil { return nil, false } user, err := s.Db.GetUserByID(session.UserID) if err != nil { return nil, false } return user, true } func (s Server) Logger(next http.Handler) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { log.Print("HTTP ", r.URL) next.ServeHTTP(w, r) }) }