29 lines
670 B
Go
29 lines
670 B
Go
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()
|
|
}
|
|
}
|