65 lines
1.3 KiB
Go
65 lines
1.3 KiB
Go
package middlewares
|
|
|
|
import (
|
|
"net/http"
|
|
"strings"
|
|
"system-trace/core/app/constants"
|
|
"system-trace/core/auth"
|
|
"system-trace/core/utils"
|
|
|
|
"github.com/gofiber/fiber/v2"
|
|
)
|
|
|
|
func ValidateSession(c *fiber.Ctx) error {
|
|
p := new(auth.PairTokens)
|
|
if err := c.CookieParser(p); err != nil {
|
|
return c.Status(http.StatusBadRequest).JSON(fiber.Map{
|
|
"error": err.Error(),
|
|
})
|
|
}
|
|
if !validatePair(c, p) {
|
|
return c.Status(http.StatusForbidden).JSON(fiber.Map{
|
|
"error": constants.UNAUTHORIZED,
|
|
})
|
|
}
|
|
|
|
return c.Next()
|
|
}
|
|
|
|
func validatePair(c *fiber.Ctx, p *auth.PairTokens) bool {
|
|
if len(p.AccessToken) <= 0 || len(p.RefreshToken) <= 0 {
|
|
return false
|
|
}
|
|
|
|
var userID int32
|
|
claims, err := utils.ValidateJWT(p.AccessToken)
|
|
if (err != nil && strings.Contains(err.Error(), "token is expired")) || claims["iss"] != constants.JWT_APP_ISS {
|
|
rclaims, rerr := utils.ValidateJWT(p.RefreshToken)
|
|
if rerr != nil || (rerr != nil && strings.Contains(rerr.Error(), "token is expired")) || rclaims["sub"] != p.AccessToken {
|
|
return false
|
|
}
|
|
|
|
pt, err := auth.GetPair(p)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
err = auth.RevokePair(p)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
err = auth.GeneratePairAndSetCookie(c, pt.UserID)
|
|
if err != nil {
|
|
return false
|
|
}
|
|
|
|
userID = pt.UserID
|
|
}
|
|
|
|
userID = claims["sub"].(int32)
|
|
c.Locals("userID", userID)
|
|
|
|
return true
|
|
}
|