-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathusers.go
60 lines (51 loc) · 1.22 KB
/
users.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
package main
import (
"errors"
"github.com/google/uuid"
"net/http"
"strings"
)
type User struct {
Id string
Name string
HashedPassword string
Jwt string
CsrfToken string
}
var UserNotFoundError = errors.New("user_not_found")
var UserExistsError = errors.New("user_exists")
var users = map[string]User{}
func createUser(writer http.ResponseWriter, username, password string) (User, error) {
if userExists(username) {
return User{}, UserExistsError
}
newUuid, err := uuid.NewV7()
if err != nil {
log.Warningf("Failed to generate UUID: %v\n", err)
http.Error(writer, "Failed to register user", http.StatusInternalServerError)
return User{}, err
}
userId := "PAR~" + strings.ReplaceAll(newUuid.String(), "-", "")
hashedPassword, _ := hashPassword(password)
user := User{
Id: userId,
HashedPassword: hashedPassword,
Name: username,
}
users[userId] = user
return user, nil
}
func userExists(name string) bool {
if _, err := fetchUser(name); err != nil {
return false
}
return true
}
func fetchUser(name string) (User, error) {
for _, user := range users {
if user.Name == name {
return user, nil
}
}
return User{}, UserNotFoundError
}