You've already forked golang-saas-starter-kit
mirror of
https://github.com/raseels-repos/golang-saas-starter-kit.git
synced 2025-06-15 00:15:15 +02:00
fixed internal package unittests
This commit is contained in:
@ -2,6 +2,8 @@ package user
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/rsa"
|
||||
"github.com/dgrijalva/jwt-go"
|
||||
"time"
|
||||
|
||||
"geeks-accelerator/oss/saas-starter-kit/example-project/internal/platform/auth"
|
||||
@ -224,3 +226,68 @@ func generateToken(ctx context.Context, dbConn *sqlx.DB, tknGen TokenGenerator,
|
||||
|
||||
return Token{Token: tkn, claims: claims}, nil
|
||||
}
|
||||
|
||||
|
||||
// mockTokenGenerator is used for testing that Authenticate calls its provided
|
||||
// token generator in a specific way.
|
||||
type MockTokenGenerator struct {
|
||||
// Private key generated by GenerateToken that is need for ParseClaims
|
||||
key *rsa.PrivateKey
|
||||
// algorithm is the method used to generate the private key.
|
||||
algorithm string
|
||||
}
|
||||
|
||||
// GenerateToken implements the TokenGenerator interface. It returns a "token"
|
||||
// that includes some information about the claims it was passed.
|
||||
func (g *MockTokenGenerator) GenerateToken(claims auth.Claims) (string, error) {
|
||||
privateKey, err := auth.KeyGen()
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
g.key, err = jwt.ParseRSAPrivateKeyFromPEM(privateKey)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
g.algorithm = "RS256"
|
||||
method := jwt.GetSigningMethod(g.algorithm)
|
||||
|
||||
tkn := jwt.NewWithClaims(method, claims)
|
||||
tkn.Header["kid"] = "1"
|
||||
|
||||
str, err := tkn.SignedString(g.key)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return str, nil
|
||||
}
|
||||
|
||||
// ParseClaims recreates the Claims that were used to generate a token. It
|
||||
// verifies that the token was signed using our key.
|
||||
func (g *MockTokenGenerator) ParseClaims(tknStr string) (auth.Claims, error) {
|
||||
parser := jwt.Parser{
|
||||
ValidMethods: []string{g.algorithm},
|
||||
}
|
||||
|
||||
if g.key == nil {
|
||||
return auth.Claims{}, errors.New("Private key is empty.")
|
||||
}
|
||||
|
||||
f := func(t *jwt.Token) (interface{}, error) {
|
||||
return g.key.Public().(*rsa.PublicKey), nil
|
||||
}
|
||||
|
||||
var claims auth.Claims
|
||||
tkn, err := parser.ParseWithClaims(tknStr, &claims, f)
|
||||
if err != nil {
|
||||
return auth.Claims{}, errors.Wrap(err, "parsing token")
|
||||
}
|
||||
|
||||
if !tkn.Valid {
|
||||
return auth.Claims{}, errors.New("Invalid token")
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user