Files
discord-retokenizer/endpoints/authorization.go
2022-12-09 23:26:38 -06:00

53 lines
1.1 KiB
Go

package endpoints
import (
"strings"
"git.zomo.dev/zomo/discord-retokenizer/storage"
"github.com/gin-gonic/gin"
)
type AuthorizationScope int
const (
AuthorizationScopeNone AuthorizationScope = iota
AuthorizationScopeUser
AuthorizationScopeBot
)
func getAuthorization(c *gin.Context) (AuthorizationScope, string) {
header := c.GetHeader("Authorization")
if header == "" {
return AuthorizationScopeNone, ""
}
headerSpl := strings.Split(header, " ")
if len(headerSpl) != 2 {
return AuthorizationScopeNone, ""
}
prefix := headerSpl[0]
token := strings.ToLower(headerSpl[1])
if prefix == "Bearer" {
if storage.CheckLoginToken(token, c.ClientIP()) {
return AuthorizationScopeUser, token
}
}
if prefix == "Bot" {
if found, _ := storage.BotTokenFromToken(token); found {
return AuthorizationScopeBot, token
}
}
return AuthorizationScopeNone, ""
}
func isUserAuthorized(c *gin.Context) bool {
scope, _ := getAuthorization(c)
return scope == AuthorizationScopeUser
}
func userIsAuthorized(c *gin.Context) {
if isUserAuthorized(c) {
c.Next()
} else {
c.AbortWithStatus(401)
}
}