/
access.go
119 lines (106 loc) · 2.25 KB
/
access.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
package account
import (
"sync"
"github.com/andygeiss/faasify/pkg/resource"
"golang.org/x/crypto/bcrypt"
)
type Access interface {
Error() error
ChangeSecret(id, current, next string)
CreateAccount(id, secret string)
GetAccount(id string) *Account
GetAccounts() []Account
VerifyAccount(id, secret string) bool
}
type fileAccess struct {
err error
path string
accounts []Account
mutex sync.Mutex
}
func (a *fileAccess) Error() error {
return a.err
}
func (a *fileAccess) ChangeSecret(id, current, next string) {
if a.err != nil {
return
}
a.loadAccounts()
for _, account := range a.accounts {
if account.Id == id {
if err := bcrypt.CompareHashAndPassword(account.Hash, []byte(current)); err == nil {
hash, _ := bcrypt.GenerateFromPassword([]byte(next), 14)
account.Hash = hash
}
}
}
a.saveAccounts()
}
func (a *fileAccess) CreateAccount(id, secret string) {
if a.err != nil {
return
}
a.loadAccounts()
exists := false
for _, account := range a.accounts {
if account.Id == id {
exists = true
break
}
}
if !exists {
hash, _ := bcrypt.GenerateFromPassword([]byte(secret), 14)
a.accounts = append(a.accounts, Account{Id: id, Hash: hash})
}
a.saveAccounts()
}
func (a *fileAccess) GetAccount(id string) *Account {
a.loadAccounts()
for _, account := range a.accounts {
if account.Id == id {
return &account
}
}
return nil
}
func (a *fileAccess) GetAccounts() []Account {
a.loadAccounts()
return a.accounts
}
func (a *fileAccess) VerifyAccount(id, secret string) bool {
a.loadAccounts()
for _, account := range a.accounts {
if account.Id == id {
if err := bcrypt.CompareHashAndPassword(account.Hash, []byte(secret)); err == nil {
return true
}
}
}
return false
}
func NewFileAccess(path string) Access {
return &fileAccess{path: path}
}
func (a *fileAccess) loadAccounts() {
if a.err != nil {
return
}
a.mutex.Lock()
defer a.mutex.Unlock()
accounts, err := resource.ReadJsonFromPath[[]Account](a.path)
if err != nil {
a.err = err
return
}
a.accounts = accounts
}
func (a *fileAccess) saveAccounts() {
if a.err != nil {
return
}
a.mutex.Lock()
defer a.mutex.Unlock()
if err := resource.WriteJsonToPath[[]Account](a.accounts, a.path); err != nil {
a.err = err
}
}