feat: add private auth foundation
This commit is contained in:
28
backend/internal/auth/middleware.go
Normal file
28
backend/internal/auth/middleware.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package auth
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const CurrentUserIDKey = "currentUserID"
|
||||
|
||||
func RequireUser(tokenVerifier func(string) (uint, error)) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
header := c.GetHeader("Authorization")
|
||||
token := strings.TrimPrefix(header, "Bearer ")
|
||||
if token == "" || token == header {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "missing bearer token"})
|
||||
return
|
||||
}
|
||||
userID, err := tokenVerifier(token)
|
||||
if err != nil {
|
||||
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "invalid bearer token"})
|
||||
return
|
||||
}
|
||||
c.Set(CurrentUserIDKey, userID)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user