/
auth_token.go
70 lines (62 loc) · 2.06 KB
/
auth_token.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
package chatable
import "time"
const (
maxDuration = time.Hour * time.Duration(24*30)
)
type AuthToken struct {
ID int `db:"id"`
AccessKeyID string `db:"access_key_id"`
SecretAccessKey string `db:"secret_access_key"`
RefreshToken string `db:"refresh_token"`
CreatedAt time.Time `db:"created_at"`
ExpiresAt time.Time `db:"expires_at"`
ModifiedAt time.Time `db:"modified_at"`
UserID int `db:"user_id"`
ClientID int `db:"client_id"`
IsActive bool `db:"is_active"`
IsRefreshable bool `db:"is_refreshable"`
Scope StringSlice `db:"scope"`
}
func (at *AuthToken) IsGood() bool {
return at.IsActive && at.ExpiresAt.After(time.Now().UTC())
}
func (at *AuthToken) ToPublicToken() *PublicToken {
return &PublicToken{
AccessKeyID: at.AccessKeyID,
SecretAccessKey: at.SecretAccessKey,
RefreshToken: at.RefreshToken,
CreatedAt: at.CreatedAt,
ExpiresAt: at.ExpiresAt,
ModifiedAt: at.ModifiedAt,
IsRefreshable: at.IsRefreshable,
}
}
type AuthTokenService interface {
GetByAccessKeyID(key string) (*AuthToken, error)
Create(at *AuthToken) error
Update(at *AuthToken) (int64, error)
}
func NewAuthToken(uid int, cid int, scope StringSlice) *AuthToken {
return &AuthToken{
AccessKeyID: GenerateRandomKey(),
SecretAccessKey: GenerateRandomKey(),
RefreshToken: GenerateRandomKey(),
CreatedAt: time.Now().UTC(),
ExpiresAt: time.Now().UTC().Add(maxDuration),
ModifiedAt: time.Now().UTC(),
UserID: uid,
ClientID: cid,
IsActive: true,
IsRefreshable: true,
Scope: scope,
}
}
type PublicToken struct {
AccessKeyID string `json:"access_key_id"`
SecretAccessKey string `json:"secret_access_key"`
RefreshToken string `json:"refresh_token"`
CreatedAt time.Time `json:"created_at"`
ExpiresAt time.Time `json:"expires_at"`
ModifiedAt time.Time `json:"modified_at"`
IsRefreshable bool `json:"is_refreshable"`
}