Merge pull request #38 from BugHerd/var-errors

Move errors to variables so they can be matched against
This commit is contained in:
Dave Grijalva 2014-11-03 13:11:22 -08:00
commit 47b263f020
3 changed files with 18 additions and 11 deletions

View File

@ -18,6 +18,7 @@ var (
SigningMethodHS256 *SigningMethodHMAC
SigningMethodHS384 *SigningMethodHMAC
SigningMethodHS512 *SigningMethodHMAC
ErrSignatureInvalid = errors.New("signature is invalid")
)
func init() {
@ -57,7 +58,7 @@ func (m *SigningMethodHMAC) Verify(signingString, signature string, key interfac
hasher.Write([]byte(signingString))
if !bytes.Equal(sig, hasher.Sum(nil)) {
err = errors.New("signature is invalid")
err = ErrSignatureInvalid
}
}
return err

5
jwt.go
View File

@ -22,8 +22,9 @@ type Keyfunc func(*Token) (interface{}, error)
// Error constants
var (
ErrInvalidKey = errors.New("key is invalid or of invalid type.")
ErrInvalidKey = errors.New("key is invalid or of invalid type")
ErrHashUnavailable = errors.New("the requested hash function is unavailable")
ErrNoTokenInRequest = errors.New("no token present in request")
)
// A JWT Token. Different fields will be used depending on whether you're
@ -217,7 +218,7 @@ func ParseFromRequest(req *http.Request, keyFunc Keyfunc) (token *Token, err err
return Parse(tokStr, keyFunc)
}
return nil, errors.New("no token present in request.")
return nil, ErrNoTokenInRequest
}

View File

@ -7,6 +7,11 @@ import (
"errors"
)
var (
ErrKeyMustBePEMEncoded = errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
ErrNotRSAPrivateKey = errors.New("Key is not a valid RSA private key")
)
// Parse PEM encoded PKCS1 or PKCS8 private key
func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
var err error
@ -14,7 +19,7 @@ func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
return nil, ErrKeyMustBePEMEncoded
}
var parsedKey interface{}
@ -27,7 +32,7 @@ func ParseRSAPrivateKeyFromPEM(key []byte) (*rsa.PrivateKey, error) {
var pkey *rsa.PrivateKey
var ok bool
if pkey, ok = parsedKey.(*rsa.PrivateKey); !ok {
return nil, errors.New("Key is not a valid RSA private key")
return nil, ErrNotRSAPrivateKey
}
return pkey, nil
@ -40,7 +45,7 @@ func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
// Parse PEM block
var block *pem.Block
if block, _ = pem.Decode(key); block == nil {
return nil, errors.New("Invalid Key: Key must be PEM encoded PKCS1 or PKCS8 private key")
return nil, ErrKeyMustBePEMEncoded
}
// Parse the key
@ -56,7 +61,7 @@ func ParseRSAPublicKeyFromPEM(key []byte) (*rsa.PublicKey, error) {
var pkey *rsa.PublicKey
var ok bool
if pkey, ok = parsedKey.(*rsa.PublicKey); !ok {
return nil, errors.New("Key is not a valid RSA public key")
return nil, ErrNotRSAPrivateKey
}
return pkey, nil