2022-01-22 19:54:41 +00:00
|
|
|
package token
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
|
|
|
|
"github.com/authorizerdev/authorizer/server/constants"
|
|
|
|
"github.com/authorizerdev/authorizer/server/cookie"
|
2022-02-28 15:56:49 +00:00
|
|
|
"github.com/authorizerdev/authorizer/server/crypto"
|
2022-01-22 19:54:41 +00:00
|
|
|
"github.com/authorizerdev/authorizer/server/envstore"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
|
|
"golang.org/x/crypto/bcrypt"
|
|
|
|
)
|
|
|
|
|
|
|
|
// CreateAdminAuthToken creates the admin token based on secret key
|
|
|
|
func CreateAdminAuthToken(tokenType string, c *gin.Context) (string, error) {
|
2022-02-28 15:56:49 +00:00
|
|
|
return crypto.EncryptPassword(envstore.EnvStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAdminSecret))
|
2022-01-22 19:54:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
// GetAdminAuthToken helps in getting the admin token from the request cookie
|
|
|
|
func GetAdminAuthToken(gc *gin.Context) (string, error) {
|
|
|
|
token, err := cookie.GetAdminCookie(gc)
|
|
|
|
if err != nil || token == "" {
|
|
|
|
return "", fmt.Errorf("unauthorized")
|
|
|
|
}
|
|
|
|
|
2022-02-28 02:25:01 +00:00
|
|
|
err = bcrypt.CompareHashAndPassword([]byte(token), []byte(envstore.EnvStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAdminSecret)))
|
2022-01-31 06:05:24 +00:00
|
|
|
|
2022-01-22 19:54:41 +00:00
|
|
|
if err != nil {
|
|
|
|
return "", fmt.Errorf(`unauthorized`)
|
|
|
|
}
|
|
|
|
|
|
|
|
return token, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// IsSuperAdmin checks if user is super admin
|
|
|
|
func IsSuperAdmin(gc *gin.Context) bool {
|
|
|
|
token, err := GetAdminAuthToken(gc)
|
|
|
|
if err != nil {
|
|
|
|
secret := gc.Request.Header.Get("x-authorizer-admin-secret")
|
|
|
|
if secret == "" {
|
|
|
|
return false
|
|
|
|
}
|
|
|
|
|
2022-02-28 02:25:01 +00:00
|
|
|
return secret == envstore.EnvStoreObj.GetStringStoreEnvVariable(constants.EnvKeyAdminSecret)
|
2022-01-22 19:54:41 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
return token != ""
|
|
|
|
}
|