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