64 lines
1.4 KiB
Go
64 lines
1.4 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) {
|
|
//get auth header
|
|
header := c.GetHeader("Authorization")
|
|
if header == "" {
|
|
return AuthorizationScopeNone, ""
|
|
}
|
|
|
|
//check if user is authorized
|
|
headerSpl := strings.Split(header, " ")
|
|
if len(headerSpl) != 2 {
|
|
return AuthorizationScopeNone, ""
|
|
}
|
|
prefix := headerSpl[0]
|
|
token := strings.ToLower(headerSpl[1])
|
|
if prefix == "Bot" {
|
|
//attempt to authorize as bot
|
|
if found, _ := storage.BotTokenFromToken(token); found {
|
|
return AuthorizationScopeBot, token
|
|
}
|
|
}
|
|
if prefix == "Bearer" {
|
|
//attempt to authorize as user
|
|
userAgentString := c.GetHeader("User-Agent")
|
|
if userAgentString == "" {
|
|
return AuthorizationScopeNone, ""
|
|
}
|
|
ua := storage.ParseUA(userAgentString)
|
|
|
|
if storage.CheckLoginToken(token, c.ClientIP(), ua) {
|
|
return AuthorizationScopeUser, 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)
|
|
}
|
|
} |