38 lines
853 B
Go
38 lines
853 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()
|
|
}
|
|
}
|
|
|
|
func CurrentUserID(c *gin.Context) (uint, bool) {
|
|
value, ok := c.Get(CurrentUserIDKey)
|
|
if !ok {
|
|
return 0, false
|
|
}
|
|
userID, ok := value.(uint)
|
|
return userID, ok && userID > 0
|
|
}
|