/
config.go
87 lines (71 loc) · 2.44 KB
/
config.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
package service
import (
"errors"
"github.com/ImageWare/TLSential/auth"
"github.com/ImageWare/TLSential/config"
"github.com/ImageWare/TLSential/model"
"github.com/ImageWare/TLSential/user"
)
// ErrSuperAdminExists means a new SA cannot be created.
var ErrSuperAdminExists = errors.New("super admin already exists")
// configService is our app implementation of config.Service
type configService struct {
repo config.Repository
userService user.Service
}
// NewConfigService returns a new instance of a configService initialized with the
// given repository.
func NewConfigService(repo config.Repository, us user.Service) config.Service {
return &configService{repo, us}
}
// JWTSecret provides the current JSON Web Token signing secret in use in the config.
func (s *configService) JWTSecret() (*auth.JWTSecret, error) {
return s.repo.JWTSecret()
}
// SuperAdmin provides the current SuperAdmin account username set in the config.
func (s *configService) SuperAdmin() (string, error) {
return s.repo.SuperAdmin()
}
// SetJWTSecret will first make sure the provided secret is valid and then set
// it to the config.
func (s *configService) SetJWTSecret(secret []byte) error {
// TODO: Make sure secret is valid here.
return s.repo.SetJWTSecret(secret)
}
// CreateSuperAdmin will take a username, generate a new password, and save this
// user with SuperAdmin permissions.
// TODO: Refactor so we don't return a full user and pass?
func (s *configService) CreateSuperAdmin(name string) (*model.User, string, error) {
sa, err := s.repo.SuperAdmin()
if err != nil {
return nil, "", err
}
if sa != "" {
return nil, "", ErrSuperAdminExists
}
p := auth.NewPassword()
u, err := model.NewUser(name, p, auth.RoleSuperAdmin)
if err != nil {
return nil, "", err
}
err = s.userService.SaveUser(u)
if err != nil {
return nil, "", err
}
// TODO: If SetSA fails, User will still exist.
err = s.repo.SetSuperAdmin(name)
return u, p, err
}
// ResetSuperAdmin will delete the currently stored username for Super Admin,
// which allows a new Super Admin to be initialized.
func (s *configService) ResetSuperAdmin() error {
return s.repo.SetSuperAdmin("")
}
// SessionKey returns the stored session key for use in gorilla sessions.
func (s *configService) SessionKey() ([]byte, error) {
return s.repo.SessionKey()
}
// SetSessionKey stores the gorilla sessions key.
func (s *configService) SetSessionKey(key []byte) error {
return s.repo.SetSessionKey(key)
}