// SetPost sets the post with the id in the url in the context and template data.
func (m *Middleware) SetPost(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		postID, err := strconv.ParseInt(vars["postID"], 10, 64)
		if err != nil {
			httperror.HandleError(w, httperror.StatusError{http.StatusBadRequest, err})
			return
		}

		pm := models.NewPostModel(m.App.DB)
		topic := context.Topic(r)
		post, err := pm.FindOne(nil, squirrel.Eq{"posts.id": postID, "posts.topic_id": topic.ID})
		if err != nil {
			httperror.HandleError(w, errors.Wrap(err, "find one error"))
			return
		}
		context.SetPost(r, post)

		templateData := context.TemplateData(r)
		templateData["Post"] = post

		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}
// MustLogin ensures the next handler is only accessible by users that are logged in.
func (m *Middleware) MustLogin(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		if _, ok := context.SessionUser(r); !ok {
			httperror.HandleError(w, httperror.StatusError{http.StatusForbidden, nil})
			return
		}

		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}
// MustBeAdminOrPostCreator ensures the next handler is only accessible by an admin or the post creator.
func (m *Middleware) MustBeAdminOrPostCreator(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		if !m.isPostCreator(r) && !m.isAdmin(r) {
			httperror.HandleError(w, httperror.StatusError{http.StatusForbidden, nil})
			return
		}

		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}
// SetTopic sets the topic with the name in the url in the context and template data.
func (m *Middleware) SetTopic(next http.Handler) http.Handler {
	fn := func(w http.ResponseWriter, r *http.Request) {
		vars := mux.Vars(r)
		topicName := strings.ToLower(vars["topicName"])
		tm := models.NewTopicModel(m.App.DB)
		topic, err := tm.FindOne(nil, squirrel.Eq{"topics.name": topicName})
		if err != nil {
			httperror.HandleError(w, errors.Wrap(err, "find one error"))
			return
		}

		context.SetTopic(r, topic)

		templateData := context.TemplateData(r)
		templateData["Topic"] = topic
		next.ServeHTTP(w, r)
	}

	return http.HandlerFunc(fn)
}
Beispiel #5
0
// ServeHTTP allows Handler to satisfy the http.Handler interface.
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
	err := h.H(h.App, w, r)
	httperror.HandleError(w, err)
}