rove/pkg/accounts/accounts.go

75 lines
1.7 KiB
Go
Raw Normal View History

package accounts
import (
"fmt"
2020-06-11 18:38:18 +01:00
"time"
)
// Account represents a registered user
type Account struct {
// Name simply describes the account and must be unique
Name string `json:"name"`
// Data represents internal account data
Data map[string]string `json:"data"`
}
// Accountant manages a set of accounts
type Accountant struct {
Accounts map[string]Account `json:"accounts"`
}
// NewAccountant creates a new accountant
func NewAccountant() *Accountant {
return &Accountant{
Accounts: make(map[string]Account),
}
}
// RegisterAccount adds an account to the set of internal accounts
func (a *Accountant) RegisterAccount(name string) (acc Account, err error) {
// Set the account name
acc.Name = name
acc.Data = make(map[string]string)
// Verify this acount isn't already registered
2020-06-02 17:51:54 +01:00
for _, a := range a.Accounts {
if a.Name == acc.Name {
return Account{}, fmt.Errorf("account name already registered: %s", a.Name)
}
}
2020-06-11 18:38:18 +01:00
// Set the creation time
acc.Data["created"] = time.Now().String()
// Simply add the account to the map
a.Accounts[acc.Name] = acc
return
}
2020-06-30 23:59:58 +01:00
// AssignData assigns data to an account
func (a *Accountant) AssignData(account string, key string, value string) error {
// Find the account matching the ID
2020-06-02 17:51:54 +01:00
if this, ok := a.Accounts[account]; ok {
this.Data[key] = value
2020-06-02 17:51:54 +01:00
a.Accounts[account] = this
} else {
return fmt.Errorf("no account found for id: %s", account)
}
return nil
}
2020-06-30 23:59:58 +01:00
// GetValue gets the rover rover for the account
func (a *Accountant) GetValue(account string, key string) (string, error) {
// Find the account matching the ID
2020-06-30 23:59:58 +01:00
this, ok := a.Accounts[account]
if !ok {
return "", fmt.Errorf("no account found for id: %s", account)
}
2020-06-30 23:59:58 +01:00
return this.Data[key], nil
}