-
Notifications
You must be signed in to change notification settings - Fork 0
/
user.go
70 lines (57 loc) · 1.45 KB
/
user.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
// SPDX-FileCopyrightText: 2023 M. Shulhan <[email protected]>
// SPDX-License-Identifier: GPL-3.0-or-later
package karajo
import (
"fmt"
"os"
"git.sr.ht/~shulhan/pakakeh.go/lib/ini"
"golang.org/x/crypto/bcrypt"
)
// User represent the account that can access Karajo user interface using
// name and password.
// The Password field store the bcrypt hash of plain password.
type User struct {
Name string
Password string `ini:"::password"`
}
// loadUsers load user from file, return the map with user's name as key.
// If the file is not exist it will return empty users without an error.
func loadUsers(file string) (users map[string]*User, err error) {
type container struct {
Users map[string]*User `ini:"user"`
}
var (
logp = `loadUsers`
content []byte
)
content, err = os.ReadFile(file)
if err != nil {
if os.IsNotExist(err) {
return nil, nil
}
return nil, fmt.Errorf(`%s: %w`, logp, err)
}
var cont = container{
Users: make(map[string]*User),
}
err = ini.Unmarshal(content, &cont)
if err != nil {
return nil, fmt.Errorf(`%s: %w`, logp, err)
}
users = cont.Users
cont.Users = nil
var (
name string
u *User
)
for name, u = range users {
u.Name = name
}
return users, nil
}
// authenticate return true if the hash of plain password match with user's
// Password.
func (u *User) authenticate(plain string) bool {
var err = bcrypt.CompareHashAndPassword([]byte(u.Password), []byte(plain))
return err == nil
}