-
Notifications
You must be signed in to change notification settings - Fork 27
/
oob_otp.go
56 lines (42 loc) · 1.15 KB
/
oob_otp.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
package secretcode
import (
"crypto/subtle"
"fmt"
"strings"
"github.com/authgear/authgear-server/pkg/util/rand"
)
const oobOTPLength = 6
var OOBOTPSecretCode = OOBOTPSecretCodeType{}
type OOBOTPSecretCodeType struct{}
func (OOBOTPSecretCodeType) Length() int {
return oobOTPLength
}
func (OOBOTPSecretCodeType) Generate() string {
code := rand.StringWithAlphabet(oobOTPLength, "0123456789", rand.SecureRand)
return code
}
func (OOBOTPSecretCodeType) GenerateFixed(fixedCode string) string {
return fixedCode
}
func (OOBOTPSecretCodeType) Compare(a, b string) bool {
formattedCode := strings.TrimSpace(a)
targetCode := strings.TrimSpace(b)
return subtle.ConstantTimeCompare([]byte(formattedCode), []byte(targetCode)) == 1
}
func (OOBOTPSecretCodeType) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
str = strings.TrimSpace(str)
codeLength := len(str)
if codeLength != 6 {
return fmt.Errorf("unexpected OOB OTP code length: %v", codeLength)
}
for i, r := range str {
if r < '0' || r > '9' {
return fmt.Errorf("unexpected OOB OTP code character at index %v: %#v", i, string(r))
}
}
return nil
}