Skip to content

Commit 26942f2

Browse files
authored
Merge pull request #24 from Nelwhix/extra-padding-fix
fix: correctly generates otp code from token with extra padding
2 parents ddaa090 + c1904ca commit 26942f2

File tree

2 files changed

+39
-0
lines changed

2 files changed

+39
-0
lines changed

helper/totp.go

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,9 @@ func GenerateOTPCode(token string, when time.Time) (string, error) {
3333
// It should be uppercase always
3434
token = strings.ToUpper(token)
3535

36+
// Remove all the extra "=" padding at the end
37+
token = strings.TrimRight(token, "=")
38+
3639
secretBytes, err := base32.StdEncoding.WithPadding(base32.NoPadding).DecodeString(token)
3740
if err != nil {
3841
return "", fmt.Errorf("Decoding token string: %w", err)

helper/totp_test.go

Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
package helper
2+
3+
import (
4+
"testing"
5+
"time"
6+
)
7+
8+
var testCases = []struct {
9+
description string
10+
token string
11+
expectErr bool
12+
}{
13+
{"generates otpcode from token with padding", "PGWXXL7B66MMSRBAWSKEKIYD3P675KRJ===", false},
14+
{"generates otpcode from token without padding", "JBSWY3DPEHPK3PXPJBSWY3DPEHPK3PXP", false},
15+
{"invalid token format", "INVALIDTOKEN123", true},
16+
}
17+
18+
func TestGenerateOTPCode(t *testing.T) {
19+
for _, tc := range testCases {
20+
t.Run(tc.description, func(t *testing.T) {
21+
code, err := GenerateOTPCode(tc.token, time.Now())
22+
23+
if tc.expectErr {
24+
if err == nil {
25+
t.Errorf("Expected error for input '%s', but got none", tc.token)
26+
}
27+
} else {
28+
if err != nil {
29+
t.Errorf("GenerateOTPCode returned an error: %s", err.Error())
30+
} else if len(code) != 6 {
31+
t.Errorf("Expected 6-digit OTP, got: %s", code)
32+
}
33+
}
34+
})
35+
}
36+
}

0 commit comments

Comments
 (0)