-
Notifications
You must be signed in to change notification settings - Fork 0
/
credential.go
83 lines (63 loc) · 1.29 KB
/
credential.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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
// SPDX-FileCopyrightText: 2023 Steffen Vogel <[email protected]>
// SPDX-License-Identifier: Apache-2.0
package ykoath
import (
"fmt"
"regexp"
"strconv"
"strings"
"time"
)
var credRegex = regexp.MustCompile(`^((?P<timestep>\d+)/)?((?P<issuer>[^:]+):)?(?P<name>.+)$`)
type credential struct {
TimeStep time.Duration
Name string
Issuer string
}
func (c credential) String() string {
return fmt.Sprintf("%s: %s", c.Issuer, c.Name)
}
func (c credential) Marshal() []byte {
s := ""
if c.TimeStep != DefaultTimeStep {
s += fmt.Sprintf("%d/", c.TimeStep/time.Second)
}
if c.Issuer != "" {
s += c.Issuer + ":"
}
s += c.Name
return []byte(s)
}
func (c *credential) Unmarshal(b []byte, t Type) error {
s := string(b)
if t == Hotp {
if parts := strings.SplitN(s, ":", 2); len(parts) > 1 {
c.Issuer = parts[0]
c.Name = parts[1]
} else {
c.Issuer = ""
c.Name = parts[0]
}
c.TimeStep = 0
return nil
}
m := credRegex.FindStringSubmatch(s)
if m != nil {
if m[2] != "" {
ts, err := strconv.Atoi(m[2])
if err != nil {
return err
}
c.TimeStep = time.Second * time.Duration(ts)
} else {
c.TimeStep = DefaultTimeStep
}
c.Issuer = m[4]
c.Name = m[5]
return nil
}
c.Issuer = ""
c.Name = s
c.TimeStep = DefaultTimeStep
return nil
}