]>
Commit | Line | Data |
---|---|---|
6988a057 JH |
1 | package hotline |
2 | ||
3 | import ( | |
d2810ae9 | 4 | "encoding/binary" |
95159e55 | 5 | "fmt" |
d2810ae9 | 6 | "golang.org/x/crypto/bcrypt" |
b129b7cb | 7 | "io" |
b129b7cb | 8 | "slices" |
6988a057 JH |
9 | ) |
10 | ||
11 | const GuestAccount = "guest" // default account used when no login is provided for a connection | |
12 | ||
13 | type Account struct { | |
187d6dc5 JH |
14 | Login string `yaml:"Login"` |
15 | Name string `yaml:"Name"` | |
16 | Password string `yaml:"Password"` | |
0ed51327 | 17 | Access accessBitmap `yaml:"Access,flow"` |
95159e55 JH |
18 | |
19 | readOffset int // Internal offset to track read progress | |
6988a057 JH |
20 | } |
21 | ||
a2ef262a JH |
22 | func NewAccount(login, name, password string, access accessBitmap) *Account { |
23 | return &Account{ | |
24 | Login: login, | |
25 | Name: name, | |
26 | Password: hashAndSalt([]byte(password)), | |
27 | Access: access, | |
28 | } | |
29 | } | |
30 | ||
926c7f55 | 31 | // Read implements io.Reader interface for Account |
95159e55 | 32 | func (a *Account) Read(p []byte) (int, error) { |
d2810ae9 | 33 | fields := []Field{ |
d005ef04 | 34 | NewField(FieldUserName, []byte(a.Name)), |
76d0c1f6 | 35 | NewField(FieldUserLogin, encodeString([]byte(a.Login))), |
d005ef04 | 36 | NewField(FieldUserAccess, a.Access[:]), |
d2810ae9 JH |
37 | } |
38 | ||
39 | if bcrypt.CompareHashAndPassword([]byte(a.Password), []byte("")) != nil { | |
d005ef04 | 40 | fields = append(fields, NewField(FieldUserPassword, []byte("x"))) |
d2810ae9 JH |
41 | } |
42 | ||
43 | fieldCount := make([]byte, 2) | |
44 | binary.BigEndian.PutUint16(fieldCount, uint16(len(fields))) | |
45 | ||
b129b7cb | 46 | var fieldBytes []byte |
d2810ae9 | 47 | for _, field := range fields { |
95159e55 JH |
48 | b, err := io.ReadAll(&field) |
49 | if err != nil { | |
50 | return 0, fmt.Errorf("error reading field: %w", err) | |
51 | } | |
52 | fieldBytes = append(fieldBytes, b...) | |
53 | } | |
54 | ||
55 | buf := slices.Concat(fieldCount, fieldBytes) | |
56 | if a.readOffset >= len(buf) { | |
57 | return 0, io.EOF // All bytes have been read | |
d2810ae9 JH |
58 | } |
59 | ||
95159e55 JH |
60 | n := copy(p, buf[a.readOffset:]) |
61 | a.readOffset += n | |
62 | ||
63 | return n, nil | |
6988a057 | 64 | } |
69af8ddb JH |
65 | |
66 | // hashAndSalt generates a password hash from a users obfuscated plaintext password | |
67 | func hashAndSalt(pwd []byte) string { | |
a2ef262a | 68 | hash, _ := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost) |
69af8ddb JH |
69 | |
70 | return string(hash) | |
71 | } |