package app import ( "context" "fmt" "emperror.dev/errors" "git.sleepycat.moe/sam/mercury/internal/database" "github.com/golang-jwt/jwt/v4" ) func (app *App) TokenToJWT(token database.Token) (string, error) { t := jwt.NewWithClaims(jwt.SigningMethodHS256, token.ToClaims()) return t.SignedString(app.tokenKey) } func (app *App) ParseToken(ctx context.Context, token string) (t database.Token, err error) { parsed, err := jwt.ParseWithClaims(token, &database.TokenClaims{}, func(t *jwt.Token) (interface{}, error) { if _, ok := t.Method.(*jwt.SigningMethodHMAC); !ok { return nil, fmt.Errorf(`unexpected signing method "%v"`, t.Header["alg"]) } return app.tokenKey, nil }) if err != nil { return t, errors.Wrap(err, "parsing token") } c, ok := parsed.Claims.(*database.TokenClaims) if !ok || !parsed.Valid { return t, fmt.Errorf("unknown claims type %T", parsed.Claims) } t, err = app.Token().Get(ctx, c.TokenID) if err != nil { return t, errors.Wrap(err, "getting token from database") } return t, nil }