67 lines
1.5 KiB
Go
67 lines
1.5 KiB
Go
package middlewares
|
|
|
|
import (
|
|
"api/config"
|
|
"api/models"
|
|
"api/services"
|
|
"encoding/base64"
|
|
"strings"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
var usr models.User
|
|
|
|
func Authenticate(c *fiber.Ctx) error {
|
|
|
|
apik, _ := base64.StdEncoding.DecodeString(c.Get("X-API-KEY"))
|
|
|
|
apikdata := strings.Split(string(apik), ":")
|
|
|
|
if len(apikdata) == 2 {
|
|
usr = services.GetUser(apikdata[0])
|
|
if usr.ID == 0 {
|
|
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: Inexistent user")
|
|
}
|
|
c.Locals("user", usr)
|
|
return c.Next()
|
|
}
|
|
|
|
tk := c.Get("Authorization")
|
|
|
|
if tk == "" {
|
|
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: No token provided")
|
|
}
|
|
|
|
tokenstr := strings.Split(tk, " ")[1]
|
|
|
|
token, err := jwt.Parse(tokenstr, func(token *jwt.Token) (interface{}, error) {
|
|
return []byte(config.Conf.ApiSecret), nil
|
|
})
|
|
|
|
if err != nil {
|
|
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: "+strings.Replace(err.Error(), "token has invalid claims: ", "", -1))
|
|
}
|
|
|
|
if token.Valid {
|
|
if claims, ok := token.Claims.(jwt.MapClaims); ok && token.Valid {
|
|
usr = services.GetUser(claims["iss"].(string))
|
|
|
|
if usr.Blocked == "S" {
|
|
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: User blocked")
|
|
}
|
|
|
|
if usr.Cancelled == "S" {
|
|
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: User cancelled")
|
|
}
|
|
|
|
c.Locals("user", usr)
|
|
|
|
return c.Next()
|
|
}
|
|
}
|
|
|
|
return fiber.NewError(fiber.StatusUnauthorized, "Unauthorized: Invalid token")
|
|
}
|