f1909da1ad
Go CI / build (push) Failing after 2m42s
feat: create basic server to manage google oauth, account, sessions, places, attributes and ratings.
49 lines
1.2 KiB
Go
49 lines
1.2 KiB
Go
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 <token>"
|
|
// If it's "Bearer <token>", 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()
|
|
}
|
|
}
|