Skip to content

Commit

Permalink
Set default digit value for hotp.GenerateCodeCustom() (#77)
Browse files Browse the repository at this point in the history
* Add unit test for hotp

* Set default digit value for hotp.GenerateCodeCustom()
  • Loading branch information
svbnbyrk authored Oct 12, 2022
1 parent c62dc58 commit 45fc76e
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
4 changes: 4 additions & 0 deletions hotp/hotp.go
Original file line number Diff line number Diff line change
Expand Up @@ -71,6 +71,10 @@ func GenerateCode(secret string, counter uint64) (string, error) {
// GenerateCodeCustom uses a counter and secret value and options struct to
// create a passcode.
func GenerateCodeCustom(secret string, counter uint64, opts ValidateOpts) (passcode string, err error) {
//Set default value
if opts.Digits == 0 {
opts.Digits = otp.DigitsSix
}
// As noted in issue #10 and #17 this adds support for TOTP secrets that are
// missing their padding.
secret = strings.TrimSpace(secret)
Expand Down
15 changes: 14 additions & 1 deletion hotp/hotp_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -78,14 +78,27 @@ func TestGenerateRFCMatrix(t *testing.T) {
}
}

func TestGenerateCodeCustom(t *testing.T){
secSha1 := base32.StdEncoding.EncodeToString([]byte("12345678901234567890"))

code, err := GenerateCodeCustom("foo",1,ValidateOpts{})
print(code)
require.Equal(t, otp.ErrValidateSecretInvalidBase32, err, "Decoding of secret as base32 failed.")
require.Equal(t, "", code, "Code should be empty string when we have an error.")

code, err = GenerateCodeCustom(secSha1,1,ValidateOpts{})
require.Equal(t, 6, len(code), "Code should be 6 digits when we have not an error.")
require.NoError(t, err, "Expected no error.")
}

func TestValidateInvalid(t *testing.T) {
secSha1 := base32.StdEncoding.EncodeToString([]byte("12345678901234567890"))

valid, err := ValidateCustom("foo", 11, secSha1,
ValidateOpts{
Digits: otp.DigitsSix,
Algorithm: otp.AlgorithmSHA1,
})
})
require.Equal(t, otp.ErrValidateInputInvalidLength, err, "Expected Invalid length error.")
require.Equal(t, false, valid, "Valid should be false when we have an error.")

Expand Down

0 comments on commit 45fc76e

Please sign in to comment.