package api import ( "net/http" "git.pengzhan.dev/noteplace-server/internal/store" "github.com/gin-gonic/gin" ) // AuthMiddleware is a Gin middleware for authentication. func AuthMiddleware(s *store.Store) gin.HandlerFunc { return func(c *gin.Context) { authHeader := c.GetHeader("Authorization") if authHeader == "" { c.JSON(http.StatusUnauthorized, gin.H{"error": "Authorization header required"}) c.Abort() return } sessionToken := authHeader // Assuming the token is directly the session token, not "Bearer " // If it's "Bearer ", you'd need to parse it: // parts := strings.Split(authHeader, " ") // if len(parts) != 2 || parts[0] != "Bearer" { // c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid Authorization header format"}) // c.Abort() // return // } // sessionToken = parts[1] session, found := s.GetSessionBySessionID(sessionToken) if !found { c.JSON(http.StatusUnauthorized, gin.H{"error": "Invalid or expired session token"}) c.Abort() return } user, found := s.GetUserByID(session.UserID) if !found { c.JSON(http.StatusUnauthorized, gin.H{"error": "User not found"}) c.Abort() return } c.Set("user", user) c.Next() } }