]> code.octet-stream.net Git - broadcaster/blob - broadcaster-server/user.go
Add licence, etc.
[broadcaster] / broadcaster-server / user.go
1 package main
2
3 import (
4 "errors"
5 "golang.org/x/crypto/bcrypt"
6 )
7
8 var users Users
9
10 type Users struct{}
11
12 func (u *Users) GetUserForSession(token string) (User, error) {
13 username, err := db.GetUserNameForSession(token)
14 if err != nil {
15 return User{}, err
16 }
17 user, err := db.GetUser(username)
18 if err != nil {
19 return User{}, err
20 }
21 return user, nil
22 }
23
24 func (u *Users) Authenticate(username string, clearPassword string) (User, error) {
25 user, err := db.GetUser(username)
26 if err != nil {
27 return User{}, err
28 }
29 err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(clearPassword))
30 if err != nil {
31 return User{}, err
32 }
33 return user, nil
34 }
35
36 func (u *Users) CreateUser(username string, clearPassword string, isAdmin bool) error {
37 if clearPassword == "" {
38 return errors.New("password cannot be empty")
39 }
40 hashed, err := bcrypt.GenerateFromPassword([]byte(clearPassword), bcrypt.DefaultCost)
41 if err != nil {
42 return err
43 }
44 return db.CreateUser(User{
45 Id: 0,
46 Username: username,
47 PasswordHash: string(hashed),
48 IsAdmin: isAdmin,
49 })
50 }
51
52 func (u *Users) DeleteUser(username string) {
53 db.DeleteUser(username)
54 }
55
56 func (u *Users) UpdatePassword(username string, oldClearPassword string, newClearPassword string) error {
57 user, err := db.GetUser(username)
58 if err != nil {
59 return err
60 }
61 err = bcrypt.CompareHashAndPassword([]byte(user.PasswordHash), []byte(oldClearPassword))
62 if err != nil {
63 return errors.New("old password is incorrect")
64 }
65 if newClearPassword == "" {
66 return errors.New("password cannot be empty")
67 }
68 hashed, err := bcrypt.GenerateFromPassword([]byte(newClearPassword), bcrypt.DefaultCost)
69 if err != nil {
70 return err
71 }
72 db.SetUserPassword(username, string(hashed))
73 return nil
74 }
75
76 func (u *Users) UpdateIsAdmin(username string, isAdmin bool) {
77 db.SetUserIsAdmin(username, isAdmin)
78 }
79
80 func (u *Users) Users() []User {
81 return db.GetUsers()
82 }