credential_auth.go
977 字节
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
package domain
import (
"fmt"
"math/rand"
"strconv"
"time"
)
var (
errorCredentialIsEmpty = fmt.Errorf("credential is empty")
errorCredentialExpired = fmt.Errorf("credential has expired")
)
const (
defaultCredExpireDuration = 3600 * time.Second
)
// 凭证认证
type CredentialAuth struct {
// 设备类型 0:ios 1:android 2:web
DeviceType int `json:"deviceType"`
// 凭证信息
Credential string `json:"credential"`
// 过期时间
Expire int64 `json:"expire"`
}
func (auth *CredentialAuth) Check() error {
if len(auth.Credential) == 0 {
return errorCredentialIsEmpty
}
if auth.Expire == 0 || auth.Expire < time.Now().Unix() {
return errorCredentialExpired
}
return nil
}
func NewCredentialAuth(deviceType int, cred string) *CredentialAuth {
if cred == "" {
cred = "cred:" + strconv.Itoa(rand.Int())
}
return &CredentialAuth{
DeviceType: deviceType,
Credential: cred,
Expire: time.Now().Add(defaultCredExpireDuration).Unix(),
}
}