refac: authenticated user can list all articles, including offline ones, while the public list only shows online ones
This commit is contained in:
1 parent
6a2ca07b66
commit
790d4e6da6
5 files changed
+345
-7
No files matched your search
@@ -13,6 +13,7 @@ import (
|
||||
"strconv"
|
||||
|
||||
"github.com/go-chi/chi/v5"
|
||||
"github.com/go-chi/jwtauth/v5"
|
||||
)
|
||||
|
||||
type Handler struct {
|
||||
@@ -101,8 +102,19 @@ func (h *Handler) PostArticle(w http.ResponseWriter, r *http.Request) {
|
||||
}
|
||||
}
|
||||
|
||||
func (h *Handler) ListArticles(w http.ResponseWriter, _ *http.Request) {
|
||||
articles, err := h.ListUseCase.ListOnlineArticles()
|
||||
func requestHasValidJwt(r *http.Request) bool {
|
||||
token, _, err := jwtauth.FromContext(r.Context())
|
||||
return token != nil && err == nil
|
||||
}
|
||||
|
||||
func (h *Handler) ListArticles(w http.ResponseWriter, r *http.Request) {
|
||||
var articles []domain.Article
|
||||
var err error
|
||||
if requestHasValidJwt(r) {
|
||||
articles, err = h.ListUseCase.ListAllArticles()
|
||||
} else {
|
||||
articles, err = h.ListUseCase.ListOnlineArticles()
|
||||
}
|
||||
if err != nil {
|
||||
http.Error(w, "Failed to retrieve articles", http.StatusInternalServerError)
|
||||
return
|
||||
|
||||
+9
-5
@@ -33,10 +33,15 @@ func NewArticleRouter(container *UseCases) http.Handler {
|
||||
|
||||
articleHandler := article.NewHandler(container.CreateArticleUseCase, container.GetArticleUseCase, container.ListArticlesUseCase, container.DeleteArticleUseCase)
|
||||
|
||||
r.Get("/{id}", articleHandler.GetArticle)
|
||||
r.Post("/", articleHandler.PostArticle)
|
||||
r.Get("/", articleHandler.ListArticles)
|
||||
r.Delete("/{id}", articleHandler.DeleteArticle)
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Get("/", articleHandler.ListArticles)
|
||||
})
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Get("/{id}", articleHandler.GetArticle)
|
||||
r.Post("/", articleHandler.PostArticle)
|
||||
r.Delete("/{id}", articleHandler.DeleteArticle)
|
||||
})
|
||||
return r
|
||||
}
|
||||
|
||||
@@ -61,7 +66,6 @@ func InitBackendRoutes(container *UseCases) *chi.Mux {
|
||||
r.Get("/", GetHelloWorld)
|
||||
r.Group(func(r chi.Router) {
|
||||
r.Use(jwtauth.Verifier(container.Token))
|
||||
r.Use(jwtauth.Authenticator(container.Token))
|
||||
r.Mount("/article", NewArticleRouter(container))
|
||||
})
|
||||
r.Mount("/auth", NewAuthRouter(container))
|
||||
|
||||
Reference in new issue
Block a user