Skip to content

Commit e577bb5

Browse files
add optional middleware and use it on post summary
1 parent 7678ba8 commit e577bb5

File tree

2 files changed

+23
-1
lines changed

2 files changed

+23
-1
lines changed

internal/handlers/server.go

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -128,7 +128,7 @@ func (s *Server) setupRoutes() {
128128

129129
api.GET("/posts/:id/likes", postHandler.ListLikesByPostID)
130130
api.GET("/posts", postHandler.ListAllPosts)
131-
api.GET("/clubs/:id/posts/summaries", postHandler.ListPostSummaries)
131+
api.GET("/clubs/:id/posts/summaries", middleware.OptionalAuthMiddleware(s.config), postHandler.ListPostSummaries)
132132
api.GET("/posts/:id", postHandler.GetPostByID)
133133

134134
api.GET("/posts/:id/comments", commentHandler.ListCommentsByPostID)

internal/middleware/auth.go

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -263,3 +263,25 @@ func RequireClubMembershipWithRoles(clubRepo repository.ClubRepository, allowedR
263263
c.Abort()
264264
}
265265
}
266+
267+
func OptionalAuthMiddleware(cfg *config.Config) gin.HandlerFunc {
268+
return func(c *gin.Context) {
269+
authHeader := c.GetHeader("Authorization")
270+
if authHeader == "" {
271+
c.Next()
272+
return
273+
}
274+
275+
tokenString := strings.Replace(authHeader, "Bearer ", "", 1)
276+
claims, err := utils.ValidateJWT(tokenString, cfg.JWT.Secret)
277+
if err != nil {
278+
c.Next()
279+
return
280+
}
281+
282+
c.Set("user_id", claims.UserID)
283+
c.Set("user_email", claims.Email)
284+
c.Set("user_role", claims.Role)
285+
c.Next()
286+
}
287+
}

0 commit comments

Comments
 (0)