-
Notifications
You must be signed in to change notification settings - Fork 42
/
user.go
executable file
·369 lines (322 loc) · 8.97 KB
/
user.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
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
package model
import (
"context"
"crypto/rand"
"crypto/subtle"
"database/sql"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"sort"
"strings"
"time"
"golang.org/x/crypto/argon2"
"gorm.io/gorm"
)
const (
AdminType = 1
LecturerType = 2
GenericType = 3
StudentType = 4
maxUsernameLength = 80
)
var (
ErrUsernameTooLong = errors.New("username is too long")
ErrUsernameNoText = errors.New("username has no text")
)
type User struct {
gorm.Model
Name string `gorm:"type:varchar(80); not null" json:"name"`
LastName *string `json:"-"`
Email sql.NullString `gorm:"type:varchar(256); uniqueIndex; default:null" json:"-"`
MatriculationNumber string `gorm:"type:varchar(256); uniqueIndex; default:null" json:"-"`
LrzID string `json:"-"`
Role uint `gorm:"default:4" json:"-"` // AdminType = 1, LecturerType = 2, GenericType = 3, StudentType = 4
Password string `gorm:"default:null" json:"-"`
Courses []Course `gorm:"many2many:course_users" json:"-"` // courses a lecturer invited this user to
AdministeredCourses []Course `gorm:"many2many:course_admins"` // courses this user is an admin of
PinnedCourses []Course `gorm:"many2many:pinned_courses"`
Settings []UserSetting `gorm:"foreignkey:UserID"`
Bookmarks []Bookmark `gorm:"foreignkey:UserID" json:"-"`
}
type UserSettingType int
const (
PreferredName UserSettingType = iota + 1
Greeting
CustomPlaybackSpeeds
UserDefinedSpeeds
)
type UserSetting struct {
gorm.Model
UserID uint `gorm:"not null"`
Type UserSettingType `gorm:"not null"`
Value string `gorm:"not null"` //json encoded setting
}
// GetPreferredName returns the preferred name of the user if set, otherwise the firstName from TUMOnline
func (u User) GetPreferredName() string {
for _, setting := range u.Settings {
if setting.Type == PreferredName {
return setting.Value
}
}
return u.Name
}
type PlaybackSpeedSetting struct {
Speed float32 `json:"speed"`
Enabled bool `json:"enabled"`
}
type CustomSpeeds []float32
type PlaybackSpeedSettings []PlaybackSpeedSetting
func (s PlaybackSpeedSettings) GetEnabled() (res []float32) {
for _, setting := range s {
if setting.Enabled {
res = append(res, setting.Speed)
}
}
return res
}
func (u *User) GetEnabledPlaybackSpeeds() (res []float32) {
if u == nil {
return []float32{1}
}
for _, setting := range u.GetPlaybackSpeeds().GetEnabled() {
res = append(res, setting)
}
for _, setting := range u.GetCustomSpeeds() {
res = append(res, setting)
}
sort.SliceStable(res, func(i, j int) bool {
return res[i] < res[j]
})
return res
}
var defaultPlaybackSpeeds = PlaybackSpeedSettings{
{0.25, false},
{0.5, true},
{0.75, true},
{1, true},
{1.25, true},
{1.5, true},
{1.75, true},
{2, true},
{2.5, false},
{3, false},
{3.5, false},
}
func (u *User) GetPlaybackSpeeds() (speeds PlaybackSpeedSettings) {
if u == nil {
return defaultPlaybackSpeeds
}
for _, setting := range u.Settings {
if setting.Type == CustomPlaybackSpeeds {
err := json.Unmarshal([]byte(setting.Value), &speeds)
if err != nil {
break
}
return speeds
}
}
return defaultPlaybackSpeeds
}
func (u *User) GetCustomSpeeds() (speeds CustomSpeeds) {
if u == nil {
return []float32{}
}
for _, setting := range u.Settings {
if setting.Type == UserDefinedSpeeds {
err := json.Unmarshal([]byte(setting.Value), &speeds)
if err != nil {
break
}
return speeds
}
}
return []float32{}
}
// GetPreferredGreeting returns the preferred greeting of the user if set, otherwise Moin
func (u User) GetPreferredGreeting() string {
for _, setting := range u.Settings {
if setting.Type == Greeting {
return setting.Value
}
}
return "Moin"
}
// PreferredNameChangeAllowed returns false if the user has set a preferred name within the last 3 months, otherwise true
func (u User) PreferredNameChangeAllowed() bool {
for _, setting := range u.Settings {
if setting.Type == PreferredName && time.Since(setting.UpdatedAt) < time.Hour*24*30*3 {
return false
}
}
return true
}
type argonParams struct {
memory uint32
iterations uint32
parallelism uint8
saltLength uint32
keyLength uint32
}
// IsAdminOfCourse checks if the user is an admin of the course
func (u *User) IsAdminOfCourse(course Course) bool {
if u == nil {
return false
}
for _, c := range u.AdministeredCourses {
if c.ID == course.ID {
return true
}
}
return u.Role == AdminType || course.UserID == u.ID
}
func (u *User) IsEligibleToWatchCourse(course Course) bool {
if course.Visibility == "loggedin" || course.Visibility == "public" {
return true
}
for _, invCourse := range u.Courses {
if invCourse.ID == course.ID {
return true
}
}
return u.IsAdminOfCourse(course)
}
func (u *User) CoursesForSemester(year int, term string, context context.Context) []Course {
var cMap = make(map[uint]Course)
for _, c := range u.Courses {
if c.Year == year && c.TeachingTerm == term {
cMap[c.ID] = c
}
}
for _, c := range u.AdministeredCourses {
if c.Year == year && c.TeachingTerm == term {
cMap[c.ID] = c
}
}
var cRes []Course
for _, c := range cMap {
cRes = append(cRes, c)
}
return cRes
}
var (
ErrInvalidHash = errors.New("the encoded hash is not in the correct format")
ErrIncompatibleVersion = errors.New("incompatible version of argon2")
p = argonParams{
memory: 64 * 1024,
iterations: 3,
parallelism: 2,
saltLength: 16,
keyLength: 32,
}
)
func (u *User) SetPassword(password string) (err error) {
if len(password) < 8 {
return errors.New("password length insufficient")
}
encodedHash, err := GenerateFromPassword(password)
if err != nil {
return err
}
u.Password = encodedHash
return nil
}
func (u *User) ComparePasswordAndHash(password string) (match bool, err error) {
if u.Password == "" {
return false, nil
}
// Extract the parameters, salt and derived key from the encoded password
// hash.
salt, hash, err := decodeHash(u.Password)
if err != nil {
return false, err
}
// Derive the key from the other password using the same parameters.
otherHash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength)
// Check that the contents of the hashed passwords are identical. Note
// that we are using the subtle.ConstantTimeCompare() function for this
// to help prevent timing attacks.
if subtle.ConstantTimeCompare(hash, otherHash) == 1 {
return true, nil
}
return false, nil
}
func decodeHash(encodedHash string) (salt, hash []byte, err error) {
vals := strings.Split(encodedHash, "$")
if len(vals) != 6 {
return nil, nil, ErrInvalidHash
}
var version int
_, err = fmt.Sscanf(vals[2], "v=%d", &version)
if err != nil {
return nil, nil, err
}
if version != argon2.Version {
return nil, nil, ErrIncompatibleVersion
}
_, err = fmt.Sscanf(vals[3], "m=%d,t=%d,p=%d", &p.memory, &p.iterations, &p.parallelism)
if err != nil {
return nil, nil, err
}
salt, err = base64.RawStdEncoding.DecodeString(vals[4])
if err != nil {
return nil, nil, err
}
p.saltLength = uint32(len(salt))
hash, err = base64.RawStdEncoding.DecodeString(vals[5])
if err != nil {
return nil, nil, err
}
p.keyLength = uint32(len(hash))
return salt, hash, nil
}
func GenerateFromPassword(password string) (encodedHash string, err error) {
// Generate a cryptographically secure random salt.
salt, err := generateRandomBytes(p.saltLength)
if err != nil {
return "", err
}
// Pass the plaintext password, salt and parameters to the argon2.IDKey
// function. This will generate a hash of the password using the Argon2id
// variant.
hash := argon2.IDKey([]byte(password), salt, p.iterations, p.memory, p.parallelism, p.keyLength)
// Base64 encode the salt and hashed password.
b64Salt := base64.RawStdEncoding.EncodeToString(salt)
b64Hash := base64.RawStdEncoding.EncodeToString(hash)
// Return a string using the standard encoded hash representation.
encodedHash = fmt.Sprintf("$argon2id$v=%d$m=%d,t=%d,p=%d$%s$%s", argon2.Version, p.memory, p.iterations, p.parallelism, b64Salt, b64Hash)
return encodedHash, nil
}
func generateRandomBytes(n uint32) ([]byte, error) {
b := make([]byte, n)
_, err := rand.Read(b)
if err != nil {
return nil, err
}
return b, nil
}
// GetLoginString returns the email if it is set, otherwise the lrzID
func (u *User) GetLoginString() string {
if u == nil {
return "- System -"
}
if u.Email.String != "" {
return u.Email.String
}
return u.LrzID
}
// BeforeCreate is a GORM hook that is called before a new user is created.
// Users won't be saved if any of these apply:
// - username is empty (after trimming)
// - username is too long (>maxUsernameLength)
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
u.Name = strings.TrimSpace(u.Name)
if len(u.Name) > maxUsernameLength {
return ErrUsernameTooLong
}
if len(u.Name) == 0 {
return ErrUsernameNoText
}
return nil
}