This repository has been archived by the owner on Jun 29, 2019. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 2
/
admin.go
66 lines (58 loc) · 1.69 KB
/
admin.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
package service
import (
"errors"
"github.com/MegaShow/goagenda/lib/hash"
"github.com/MegaShow/goagenda/lib/log"
"github.com/MegaShow/goagenda/model"
)
type AdminService interface {
GetCurrentUserName() string
Login(name, password string) error
Register(name, password, email, telephone string) error
SetCurrentUserName(name string) error
}
func (s *Service) Register(name, password, email, telephone string) error {
log.Verbose("check if username exists")
user := s.DB.User().GetUserByName(name)
if user.Name != "" {
return errors.New("user name already exists")
}
log.Verbose("add new user into database")
password, salt := hash.Encrypt(password)
s.DB.User().AddUser(model.User{
Name: name,
Email: email,
Telephone: telephone,
Password: password,
Salt: salt,
})
return nil
}
func (s *Service) Login(name, password string) error {
log.Verbose("check if username and password is correct")
user := s.DB.User().GetUserByName(name)
if user.Name == "" {
return errors.New("invalid username or password")
}
checkPassword := hash.EncryptWithSalt(password, user.Salt)
if checkPassword != user.Password {
return errors.New("invalid user name or password")
}
return nil
}
// Don't call this method in other service's methods!!!
func (s *Service) GetCurrentUserName() string {
return s.DB.Status().GetStatus().Name
}
// Don't call this method in other service's methods!!!
func (s *Service) SetCurrentUserName(name string) error {
user := s.DB.User().GetUserByName(name)
if name != "" && user.Name == "" {
return errors.New("no such user")
}
s.DB.Status().SetStatus(model.Status{Name: name})
return nil
}
func (s *Manager) Admin() AdminService {
return s.GetService()
}