refactor!: Update JWT logic

- Change algo from ed25519 to rsa256
- Use gin-jwt lib for JWT middleware
This commit is contained in:
2025-11-04 13:46:19 +03:00
parent 7bc4ce8c96
commit 7be0c7c6d3
6 changed files with 62 additions and 29 deletions

View File

@@ -1,24 +1,24 @@
package jwt
import (
"crypto/ed25519"
"crypto/rsa"
"net/http"
"os"
"strings"
"time"
"git.ostiwe.com/ostiwe-com/status/model"
"git.ostiwe.com/ostiwe-com/status/settings"
"github.com/go-chi/jwtauth/v5"
ginJwt "github.com/appleboy/gin-jwt/v3"
"github.com/golang-jwt/jwt/v5"
"github.com/lestrrat-go/jwx/v2/jwa"
)
var (
signKey *ed25519.PrivateKey
publicSignKey *ed25519.PublicKey
signMethod jwt.SigningMethod
signKey *rsa.PrivateKey
publicSignKey *rsa.PublicKey
signMethod jwt.SigningMethod = jwt.SigningMethodRS256
TokenAuth *jwtauth.JWTAuth
AuthMiddleware *ginJwt.GinJWTMiddleware
)
func init() {
@@ -32,6 +32,8 @@ func init() {
jwtPrivateKeyPath = settings.WorkingDir + "/" + jwtPrivateKeyPath
}
var err error
publicFile, err := os.ReadFile(jwtPublicKeyPath)
if err != nil {
panic(err)
@@ -42,31 +44,31 @@ func init() {
panic(err)
}
privateKey, err := jwt.ParseEdPrivateKeyFromPEM(privateFile)
signKey, err = jwt.ParseRSAPrivateKeyFromPEM(privateFile)
if err != nil {
panic(err)
}
publicKey, err := jwt.ParseEdPublicKeyFromPEM(publicFile)
publicSignKey, err = jwt.ParseRSAPublicKeyFromPEM(publicFile)
if err != nil {
panic(err)
}
pk, ok := privateKey.(ed25519.PrivateKey)
if !ok {
panic("invalid ed25519 private key")
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,
}
k, ok := publicKey.(ed25519.PublicKey)
if !ok {
panic("invalid ed25519 public key")
if err = AuthMiddleware.MiddlewareInit(); err != nil {
panic(err)
}
signKey = &pk
publicSignKey = &k
signMethod = jwt.SigningMethodEdDSA
TokenAuth = jwtauth.New(string(jwa.EdDSA), signKey, publicSignKey)
}
func CreateByUser(user *model.User) (string, error) {