/
models_api.go
115 lines (89 loc) · 2.01 KB
/
models_api.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
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
package marketplace
import (
"errors"
"time"
"qxklmrhx7qkzais6.onion/Tochka/tochka-free-market/modules/util"
)
/*
Models
*/
type APISession struct {
Token string `json:"token" gorm:"index"`
UserUuid string `json:"-"`
ExpiryDate time.Time `json:"end_date"`
IsTwoFactorSession bool `json:"is_2fa_session"`
IsSecondFactorCompleted bool `json:"is_2fa_completed"`
SecondFactorSecretText string `json:"-"`
User User `json:"-"`
}
/*
Model Methods
*/
func (as APISession) IsActive() bool {
return as.ExpiryDate.Before(time.Now())
}
func (as APISession) Complete2FA() error {
as.IsSecondFactorCompleted = true
return as.Save()
}
/*
Model Interface Implementation
*/
func (as APISession) Validate() error {
if as.Token == "" {
return errors.New("Empty UUID")
}
if as.UserUuid == "" {
return errors.New("Empty User UUID")
}
return nil
}
func (as APISession) Remove() error {
return database.Delete(&as).Error
}
func (as APISession) Save() error {
err := as.Validate()
if err != nil {
return err
}
if existing, _ := FindAPISessionByToken(as.Token); existing != nil {
return database.Save(as).Error
} else {
return database.Create(as).Error
}
}
/*
Queries
*/
func FindAPISessionByToken(sessionToken string) (*APISession, error) {
var as APISession
err := database.
Preload("User").
First(&as, "token = ?", sessionToken).
Error
if err != nil {
return nil, err
}
return &as, nil
}
func FindAPISessionByUserUuid(userUuid string) (*APISession, error) {
var as APISession
err := database.
Order("expiry_date desc").
First(&as, "user_uuid = ?", userUuid).
Error
if err != nil {
return nil, err
}
return &as, nil
}
func CreateAPISession(user User) (*APISession, error) {
d, _ := time.ParseDuration("1d")
as := APISession{
Token: util.GenerateUuid(),
UserUuid: user.Uuid,
ExpiryDate: time.Now().Add(d),
IsTwoFactorSession: user.TwoFactorAuthentication,
}
return &as, as.Save()
}