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