]> git.r.bdr.sh - rbdr/mobius/blobdiff - hotline/account.go
Account for the root
[rbdr/mobius] / hotline / account.go
index a6808615f5fad507526b7b8b4ec3d59d52e0b9a6..39ea9740275c1771fa3892b1d4429661f4de0b8e 100644 (file)
@@ -2,7 +2,10 @@ 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
@@ -11,29 +14,59 @@ type Account struct {
        Login    string       `yaml:"Login"`
        Name     string       `yaml:"Name"`
        Password string       `yaml:"Password"`
-       Access   accessBitmap `yaml:"Access"`
+       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) (n int, err error) {
+func (a *Account) Read(p []byte) (int, error) {
        fields := []Field{
-               NewField(fieldUserName, []byte(a.Name)),
-               NewField(fieldUserLogin, negateString([]byte(a.Login))),
-               NewField(fieldUserAccess, a.Access[:]),
+               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")))
+               fields = append(fields, NewField(FieldUserPassword, []byte("x")))
        }
 
        fieldCount := make([]byte, 2)
        binary.BigEndian.PutUint16(fieldCount, uint16(len(fields)))
 
-       p = append(p, fieldCount...)
-
+       var fieldBytes []byte
        for _, field := range fields {
-               p = append(p, field.Payload()...)
+               b, err := io.ReadAll(&field)
+               if err != nil {
+                       return 0, fmt.Errorf("error reading field: %w", err)
+               }
+               fieldBytes = append(fieldBytes, b...)
        }
 
-       return len(p), nil
+       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)
 }