Check empty secret in other spots
All checks were successful
continuous-integration/drone/push Build is passing
continuous-integration/drone/pr Build is passing

This commit is contained in:
Jan Bader 2022-03-01 18:37:07 +00:00
parent 09a227d08d
commit 3696bbde43
2 changed files with 16 additions and 9 deletions

View File

@ -11,18 +11,18 @@ import (
) )
// TokenVerifier verifies Tokens. // TokenVerifier verifies Tokens.
type tokenVerifier struct { type TokenVerifier struct {
secret string secret string
} }
var ErrEmptySecret = fmt.Errorf("secret is required") var ErrEmptySecret = fmt.Errorf("secret is required")
func NewTokenVerifier(secret string) (*tokenVerifier, error) { func NewTokenVerifier(secret string) (*TokenVerifier, error) {
if secret == "" { if secret == "" {
return nil, ErrEmptySecret return nil, ErrEmptySecret
} }
return &tokenVerifier{ return &TokenVerifier{
secret: secret, secret: secret,
}, nil }, nil
} }
@ -40,7 +40,11 @@ const (
) )
// CreateToken creates a new token from username and name. // CreateToken creates a new token from username and name.
func (tv *tokenVerifier) CreateToken(user *postgres.User) (string, error) { func (tv *TokenVerifier) CreateToken(user *postgres.User) (string, error) {
if tv.secret == "" {
return "", ErrEmptySecret
}
token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{ token := jwt.NewWithClaims(jwt.SigningMethodHS256, jwt.MapClaims{
"usr": user.Email, "usr": user.Email,
"name": user.Name, "name": user.Name,
@ -64,7 +68,11 @@ var (
) )
// VerifyToken verifys a given string-token. // VerifyToken verifys a given string-token.
func (tv *tokenVerifier) VerifyToken(tokenString string) (budgeteer.Token, error) { //nolint:ireturn func (tv *TokenVerifier) VerifyToken(tokenString string) (budgeteer.Token, error) { //nolint:ireturn
if tv.secret == "" {
return nil, ErrEmptySecret
}
token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) { token, err := jwt.Parse(tokenString, func(token *jwt.Token) (interface{}, error) {
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok { if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
return nil, fmt.Errorf("method '%v': %w", token.Header["alg"], ErrUnexpectedSigningMethod) return nil, fmt.Errorf("method '%v': %w", token.Header["alg"], ErrUnexpectedSigningMethod)

View File

@ -28,11 +28,10 @@ func TestRegisterUser(t *testing.T) { //nolint:funlen
return return
} }
tokenVerifier, _ := jwt.NewTokenVerifier("this_is_my_demo_secret_for_unit_tests")
h := Handler{ h := Handler{
Service: database, Service: database,
TokenVerifier: &jwt.TokenVerifier{ TokenVerifier: tokenVerifier,
Secret: "this_is_my_demo_secret_for_unit_tests",
},
CredentialsVerifier: &bcrypt.Verifier{}, CredentialsVerifier: &bcrypt.Verifier{},
} }