2024-01-06 17:56:32 +00:00
|
|
|
package security
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2024-02-18 07:51:27 +00:00
|
|
|
"github.com/gofiber/fiber/v2"
|
2024-01-06 17:56:32 +00:00
|
|
|
"time"
|
|
|
|
|
|
|
|
"github.com/golang-jwt/jwt/v5"
|
|
|
|
"github.com/spf13/viper"
|
|
|
|
)
|
|
|
|
|
2024-04-13 05:48:19 +00:00
|
|
|
var CookieAccessKey = "passport_auth_key"
|
|
|
|
var CookieRefreshKey = "passport_refresh_key"
|
2024-02-18 07:51:27 +00:00
|
|
|
|
2024-01-06 17:56:32 +00:00
|
|
|
type PayloadClaims struct {
|
|
|
|
jwt.RegisteredClaims
|
|
|
|
|
2024-01-30 15:07:30 +00:00
|
|
|
SessionID string `json:"sed"`
|
|
|
|
Type string `json:"typ"`
|
2024-01-06 17:56:32 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
JwtAccessType = "access"
|
|
|
|
JwtRefreshType = "refresh"
|
|
|
|
)
|
|
|
|
|
2024-01-30 15:07:30 +00:00
|
|
|
func EncodeJwt(id string, typ, sub, sed string, aud []string, exp time.Time) (string, error) {
|
2024-01-06 17:56:32 +00:00
|
|
|
tk := jwt.NewWithClaims(jwt.SigningMethodHS512, PayloadClaims{
|
|
|
|
jwt.RegisteredClaims{
|
|
|
|
Subject: sub,
|
|
|
|
Audience: aud,
|
2024-01-30 13:24:54 +00:00
|
|
|
Issuer: fmt.Sprintf("https://%s", viper.GetString("domain")),
|
2024-01-06 17:56:32 +00:00
|
|
|
ExpiresAt: jwt.NewNumericDate(exp),
|
|
|
|
NotBefore: jwt.NewNumericDate(time.Now()),
|
|
|
|
IssuedAt: jwt.NewNumericDate(time.Now()),
|
|
|
|
ID: id,
|
|
|
|
},
|
2024-01-30 15:07:30 +00:00
|
|
|
sed,
|
2024-01-06 17:56:32 +00:00
|
|
|
typ,
|
|
|
|
})
|
|
|
|
|
|
|
|
return tk.SignedString([]byte(viper.GetString("secret")))
|
|
|
|
}
|
|
|
|
|
|
|
|
func DecodeJwt(str string) (PayloadClaims, error) {
|
|
|
|
var claims PayloadClaims
|
|
|
|
tk, err := jwt.ParseWithClaims(str, &claims, func(token *jwt.Token) (interface{}, error) {
|
|
|
|
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
|
|
|
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
|
|
|
}
|
|
|
|
return []byte(viper.GetString("secret")), nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return claims, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if data, ok := tk.Claims.(*PayloadClaims); ok {
|
|
|
|
return *data, nil
|
|
|
|
} else {
|
|
|
|
return claims, fmt.Errorf("unexpected token payload: not payload claims type")
|
|
|
|
}
|
|
|
|
}
|
2024-02-18 07:51:27 +00:00
|
|
|
|
|
|
|
func SetJwtCookieSet(c *fiber.Ctx, access, refresh string) {
|
|
|
|
c.Cookie(&fiber.Cookie{
|
|
|
|
Name: CookieAccessKey,
|
|
|
|
Value: access,
|
|
|
|
Domain: viper.GetString("security.cookie_domain"),
|
|
|
|
SameSite: viper.GetString("security.cookie_samesite"),
|
|
|
|
Expires: time.Now().Add(60 * time.Minute),
|
|
|
|
Path: "/",
|
|
|
|
})
|
|
|
|
c.Cookie(&fiber.Cookie{
|
|
|
|
Name: CookieRefreshKey,
|
|
|
|
Value: refresh,
|
|
|
|
Domain: viper.GetString("security.cookie_domain"),
|
|
|
|
SameSite: viper.GetString("security.cookie_samesite"),
|
|
|
|
Expires: time.Now().Add(24 * 30 * time.Hour),
|
|
|
|
Path: "/",
|
|
|
|
})
|
|
|
|
}
|