2022-01-20 02:35:55 +00:00
|
|
|
package users
|
2022-01-19 20:45:53 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"encoding/json"
|
|
|
|
|
|
|
|
"go.etcd.io/bbolt"
|
|
|
|
)
|
|
|
|
|
2022-01-21 13:04:41 +00:00
|
|
|
var _ UserStore = &BoltUserStore{}
|
|
|
|
|
2022-01-19 20:45:53 +00:00
|
|
|
var keyUsers = []byte("users")
|
|
|
|
|
|
|
|
type BoltUserStore struct {
|
|
|
|
db *bbolt.DB
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewBoltUserStore(path string) (*BoltUserStore, error) {
|
2022-01-27 10:36:16 +00:00
|
|
|
db, err := bbolt.Open(path, 0o666, nil) // nolint: gomnd
|
2022-01-19 20:45:53 +00:00
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
if err := db.Update(func(tx *bbolt.Tx) error {
|
|
|
|
_, err := tx.CreateBucketIfNotExists(keyUsers)
|
|
|
|
return err
|
|
|
|
}); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return &BoltUserStore{db: db}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *BoltUserStore) Close() error {
|
|
|
|
return s.db.Close()
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *BoltUserStore) Get(username string) (*User, error) {
|
|
|
|
var user User
|
2022-01-24 19:25:52 +00:00
|
|
|
|
2022-01-19 20:45:53 +00:00
|
|
|
err := s.db.View(func(tx *bbolt.Tx) error {
|
|
|
|
bkt := tx.Bucket(keyUsers)
|
|
|
|
rawUser := bkt.Get([]byte(username))
|
|
|
|
if err := json.Unmarshal(rawUser, &user); err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-01-24 19:25:52 +00:00
|
|
|
|
2022-01-19 20:45:53 +00:00
|
|
|
return &user, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *BoltUserStore) Store(user *User) error {
|
|
|
|
return s.db.Update(func(tx *bbolt.Tx) error {
|
|
|
|
bkt := tx.Bucket(keyUsers)
|
|
|
|
|
|
|
|
data, err := json.Marshal(user)
|
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
return bkt.Put([]byte(user.Username), data)
|
|
|
|
})
|
|
|
|
}
|
|
|
|
|
|
|
|
func (s *BoltUserStore) Delete(username string) error {
|
|
|
|
return s.db.Update(func(tx *bbolt.Tx) error {
|
|
|
|
bkt := tx.Bucket(keyUsers)
|
|
|
|
return bkt.Delete([]byte(username))
|
|
|
|
})
|
|
|
|
}
|
2022-01-27 10:36:16 +00:00
|
|
|
|
2022-01-21 13:04:41 +00:00
|
|
|
func (s *BoltUserStore) List() ([]string, error) {
|
|
|
|
var ids []string
|
|
|
|
|
|
|
|
err := s.db.View(func(tx *bbolt.Tx) error {
|
|
|
|
bkt := tx.Bucket(keyUsers)
|
|
|
|
|
|
|
|
c := bkt.Cursor()
|
|
|
|
|
|
|
|
for k, _ := c.First(); k != nil; k, _ = c.Next() {
|
|
|
|
ids = append(ids, string(k))
|
|
|
|
}
|
|
|
|
|
|
|
|
return nil
|
|
|
|
})
|
|
|
|
if err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
2022-01-24 19:25:52 +00:00
|
|
|
|
2022-01-21 13:04:41 +00:00
|
|
|
return ids, nil
|
|
|
|
}
|