80 lines
1.8 KiB
Go
80 lines
1.8 KiB
Go
package jwt
|
|
|
|
import (
|
|
"crypto/rsa"
|
|
"net/http"
|
|
"os"
|
|
"strings"
|
|
"time"
|
|
|
|
"git.ostiwe.com/ostiwe-com/status/model"
|
|
"git.ostiwe.com/ostiwe-com/status/settings"
|
|
ginJwt "github.com/appleboy/gin-jwt/v3"
|
|
"github.com/golang-jwt/jwt/v5"
|
|
)
|
|
|
|
var (
|
|
signKey *rsa.PrivateKey
|
|
signMethod jwt.SigningMethod = jwt.SigningMethodRS256
|
|
|
|
AuthMiddleware *ginJwt.GinJWTMiddleware
|
|
)
|
|
|
|
func Init() {
|
|
jwtPublicKeyPath := os.Getenv("JWT_SIGN_PUBLIC_KEY_PATH")
|
|
if !strings.HasPrefix(jwtPublicKeyPath, "/") {
|
|
jwtPublicKeyPath = settings.WorkingDir + "/" + jwtPublicKeyPath
|
|
}
|
|
|
|
jwtPrivateKeyPath := os.Getenv("JWT_SIGN_PRIVATE_KEY_PATH")
|
|
if !strings.HasPrefix(jwtPrivateKeyPath, "/") {
|
|
jwtPrivateKeyPath = settings.WorkingDir + "/" + jwtPrivateKeyPath
|
|
}
|
|
|
|
var err error
|
|
|
|
publicFile, err := os.ReadFile(jwtPublicKeyPath)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
privateFile, err := os.ReadFile(jwtPrivateKeyPath)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
signKey, err = jwt.ParseRSAPrivateKeyFromPEM(privateFile)
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
|
|
AuthMiddleware = &ginJwt.GinJWTMiddleware{
|
|
SigningAlgorithm: signMethod.Alg(),
|
|
PrivKeyBytes: privateFile,
|
|
PubKeyBytes: publicFile,
|
|
Timeout: time.Hour * 6,
|
|
MaxRefresh: time.Hour * 24 * 7,
|
|
SecureCookie: true,
|
|
CookieHTTPOnly: true,
|
|
CookieSameSite: http.SameSiteStrictMode,
|
|
SendCookie: true,
|
|
}
|
|
|
|
if err = AuthMiddleware.MiddlewareInit(); err != nil {
|
|
panic(err)
|
|
}
|
|
}
|
|
|
|
func CreateByUser(user *model.User) (string, error) {
|
|
claims := NewClaims()
|
|
claims.Subject = user.Login
|
|
claims.UserID = user.ID
|
|
|
|
claims.IssuedAt = jwt.NewNumericDate(time.Now())
|
|
claims.ExpiresAt = jwt.NewNumericDate(time.Now().Add(time.Hour * 24 * 2))
|
|
|
|
token := jwt.NewWithClaims(signMethod, claims)
|
|
|
|
return token.SignedString(signKey)
|
|
}
|