-
Notifications
You must be signed in to change notification settings - Fork 29
/
recovery_code.go
50 lines (39 loc) · 1.06 KB
/
recovery_code.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
package secretcode
import (
"fmt"
"github.com/authgear/authgear-server/pkg/util/base32"
"github.com/authgear/authgear-server/pkg/util/rand"
)
var RecoveryCode = RecoveryCodeType{}
type RecoveryCodeType struct{}
func (RecoveryCodeType) Generate() string {
code := rand.StringWithAlphabet(10, base32.Alphabet, rand.SecureRand)
return code
}
func (RecoveryCodeType) FormatForHuman(code string) (formatted string) {
halfLength := len(code) / 2
formatted = fmt.Sprintf("%s-%s", code[:halfLength], code[halfLength:])
return
}
func (RecoveryCodeType) FormatForComparison(code string) (formatted string, err error) {
formatted, err = base32.Normalize(code)
if err != nil {
return
}
return
}
func (t RecoveryCodeType) CheckFormat(value interface{}) error {
str, ok := value.(string)
if !ok {
return nil
}
formatted, err := t.FormatForComparison(str)
if err != nil {
return fmt.Errorf("invalid recovery code: %w", err)
}
codeLength := len(formatted)
if codeLength != 10 {
return fmt.Errorf("unexpected recovery code length: %v", codeLength)
}
return nil
}