-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
model.go
230 lines (195 loc) · 6.19 KB
/
model.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
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
// Copyright (c) 2022 Isaque Veras
// Use of this source code is governed by a MIT style
// license that can be found in the LICENSE file.
package auth
import (
"strings"
"time"
"github.com/google/uuid"
"github.com/isaqueveras/powersso/config"
"github.com/isaqueveras/powersso/utils"
"golang.org/x/crypto/bcrypt"
)
// Flag set the data type to flag the user
type Flag int
const (
// FlagEnabledAccount defines that the user has already activated his account
FlagEnabledAccount Flag = iota + 1
// FlagOTPEnable defines that the user has OTP enabled
FlagOTPEnable
// FlagOTPSetup defines that the user has OTP configured
FlagOTPSetup
)
// Level set data type to user level
type Level string
const (
// UserLevel is the user role
UserLevel Level = "user"
// AdminLevel is the admin role
AdminLevel Level = "admin"
// IntegrationLevel is the integration role
IntegrationLevel Level = "integration"
)
const (
// CostHashPasswordProduction is the cost of hashing password in production
CostHashPasswordProduction int = 14
// CostHashPasswordDevelopment is the cost of hashing the password in development mode
CostHashPasswordDevelopment int = 1
)
// CreateAccount models the data to create an account
type CreateAccount struct {
FirstName *string `sql:"first_name" json:"first_name"`
LastName *string `sql:"last_name" json:"last_name"`
Email *string `sql:"email" json:"email"`
Password *string `sql:"password" json:"password"`
Key *string `sql:"key" json:"-"`
Level *Level `sql:"level" json:"-"`
}
// Prepare prepare data for registration
func (rr *CreateAccount) Prepare() (err error) {
rr.Email = utils.Pointer(strings.ToLower(strings.TrimSpace(*rr.Email)))
if err = rr.GeneratePassword(); err != nil {
return err
}
return
}
// RefreshTokenKey generates and sets new random token key.
// >> invalidate previously issued tokens
func (rr *CreateAccount) RefreshTokenKey() {
rr.Key = new(string)
rr.Key = utils.Pointer(utils.RandomString(50))
}
// GeneratePassword hash user password with bcrypt
func (rr *CreateAccount) GeneratePassword() error {
rr.Password = utils.Pointer(strings.TrimSpace(*rr.Password))
rr.RefreshTokenKey()
cost := CostHashPasswordDevelopment
if config.Get().Server.IsModeProduction() {
cost = CostHashPasswordProduction
}
hashedPassword, err := bcrypt.GenerateFromPassword([]byte(*rr.Key+*rr.Password), cost)
if err != nil {
return err
}
rr.Password = utils.Pointer(string(hashedPassword))
return nil
}
// SanitizePassword sanitize user password
func (rr *CreateAccount) SanitizePassword() {
rr.Password = nil
}
// ActivateAccount model the data to activate user account
type ActivateAccount struct {
ID *uuid.UUID `sql:"id"`
UserID *uuid.UUID `sql:"user_id"`
Used *bool `sql:"used"`
Valid *bool
ExpiresAt *time.Time `sql:"expires_at"`
CreatedAt *time.Time `sql:"created_at"`
}
// IsValid check if the token is valid
func (a *ActivateAccount) IsValid() bool {
return (a.Used != nil && !*a.Used) && (a.Valid != nil && *a.Valid)
}
// Steps contains login steps
type Steps struct {
Name *string
OTP *bool
}
type User struct {
ID *uuid.UUID
Email *string
Password *string `json:"-"`
FirstName *string
LastName *string
Flag *Flag
Level *Level
Blocked *bool
Key *string
Active *bool
OTPToken *string
OTPEnable *bool
OTPSetUp *bool
CreatedBy *uuid.UUID
CreatedAt *time.Time
LastLogin *time.Time
}
// HasFlag return 'true' if has flag
func (u *User) HasFlag(flag Flag) bool {
return u.Flag != nil && *u.Flag&flag != 0
}
// IsActive check if the user has their account activated
func (u *User) IsActive() bool {
return u.Active != nil && *u.Active
}
// IsBlocked check if the user has the account temporarily blocked
func (u *User) IsBlocked() bool {
return u.Blocked != nil && *u.Blocked
}
// OTPConfigured checks if the user has the OTP token configured
func (u *User) OTPConfigured() bool {
enabled := u.Flag != nil && *u.Flag&FlagOTPEnable != 0
setup := u.Flag != nil && *u.Flag&FlagOTPSetup != 0
return enabled && setup
}
// GetUserLevel returns the authentication token and duration by user level
func (u *User) GetUserLevel(s *config.Secrets) string {
keys := map[Level]string{
UserLevel: s.User,
AdminLevel: s.Admin,
IntegrationLevel: s.Integration,
}
return keys[*u.Level]
}
// Login models the data for the user to log in with their account
type Login struct {
Email *string `json:"email" binding:"required,lte=60,email"`
Password *string `json:"password" binding:"required,gte=6"`
OTP *string `json:"otp,omitempty"`
ClientIP *string `json:"-"`
UserAgent *string `json:"-"`
}
type ChangePassword struct {
UserID *uuid.UUID `json:"user_id"`
Password *string `json:"password"`
ConfirmPassword *string `json:"confirm_password"`
CodeOTP *string `json:"code_otp"`
Key *string `json:"-"`
}
// ValidatePassword validate passwords for change password
func (c *ChangePassword) ValidatePassword() bool {
return strings.TrimSpace(*c.Password) == strings.TrimSpace(*c.ConfirmPassword)
}
// ComparePasswords compare user password and payload
func (l *Login) ComparePasswords(passw, key *string) error {
if err := bcrypt.CompareHashAndPassword([]byte(*passw), []byte(*key+*l.Password)); err != nil {
return ErrEmailOrPasswordIsNotValid()
}
l.SanitizePassword()
return nil
}
// SanitizePassword sanitize user password
func (l *Login) SanitizePassword() {
l.Password = nil
}
// Validate prepare data for login
func (l *Login) Validate() {
if l.ClientIP != nil && *l.ClientIP == "" {
l.ClientIP = utils.Pointer("0.0.0.0")
}
if l.UserAgent != nil && *l.UserAgent == "" {
l.UserAgent = utils.Pointer("Unknown")
}
}
// Session models the data of a user session
type Session struct {
SessionID *uuid.UUID `json:"session_id,omitempty"`
UserID *uuid.UUID `json:"user_id,omitempty"`
Email *string `json:"email,omitempty"`
FirstName *string `json:"first_name,omitempty"`
LastName *string `json:"last_name,omitempty"`
Level *Level `json:"level,omitempty"`
Token *string `json:"token,omitempty"`
CreatedAt *time.Time `json:"created_at,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}