aboutsummaryrefslogtreecommitdiff
path: root/hotline/account.go
blob: 39ea9740275c1771fa3892b1d4429661f4de0b8e (plain)
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
package hotline

import (
	"encoding/binary"
	"fmt"
	"golang.org/x/crypto/bcrypt"
	"io"
	"slices"
)

const GuestAccount = "guest" // default account used when no login is provided for a connection

type Account struct {
	Login    string       `yaml:"Login"`
	Name     string       `yaml:"Name"`
	Password string       `yaml:"Password"`
	Access   AccessBitmap `yaml:"Access"`
	FileRoot string       `yaml:"FileRoot"`

	readOffset int // Internal offset to track read progress
}

func NewAccount(login, name, password string, access AccessBitmap) *Account {
	return &Account{
		Login:    login,
		Name:     name,
		Password: HashAndSalt([]byte(password)),
		Access:   access,
	}
}

// Read implements io.Reader interface for Account
func (a *Account) Read(p []byte) (int, error) {
	fields := []Field{
		NewField(FieldUserName, []byte(a.Name)),
		NewField(FieldUserLogin, EncodeString([]byte(a.Login))),
		NewField(FieldUserAccess, a.Access[:]),
	}

	if bcrypt.CompareHashAndPassword([]byte(a.Password), []byte("")) != nil {
		fields = append(fields, NewField(FieldUserPassword, []byte("x")))
	}

	fieldCount := make([]byte, 2)
	binary.BigEndian.PutUint16(fieldCount, uint16(len(fields)))

	var fieldBytes []byte
	for _, field := range fields {
		b, err := io.ReadAll(&field)
		if err != nil {
			return 0, fmt.Errorf("error reading field: %w", err)
		}
		fieldBytes = append(fieldBytes, b...)
	}

	buf := slices.Concat(fieldCount, fieldBytes)
	if a.readOffset >= len(buf) {
		return 0, io.EOF // All bytes have been read
	}

	n := copy(p, buf[a.readOffset:])
	a.readOffset += n

	return n, nil
}

// HashAndSalt generates a password hash from a users obfuscated plaintext password
func HashAndSalt(pwd []byte) string {
	hash, _ := bcrypt.GenerateFromPassword(pwd, bcrypt.MinCost)

	return string(hash)
}