filebrowser/bolt/users.go

91 lines
1.8 KiB
Go
Raw Normal View History

2017-08-19 11:35:44 +00:00
package bolt
import (
"reflect"
"github.com/asdine/storm"
fm "github.com/hacdias/filemanager"
)
2017-08-20 08:27:03 +00:00
// UsersStore is a users store.
2017-08-19 11:35:44 +00:00
type UsersStore struct {
DB *storm.DB
}
2017-08-20 08:27:03 +00:00
// Get gets a user with a certain id from the database.
2017-08-20 08:21:36 +00:00
func (u UsersStore) Get(id int, builder fm.FSBuilder) (*fm.User, error) {
2017-08-20 08:55:45 +00:00
var us fm.User
err := u.DB.One("ID", id, &us)
2017-08-19 11:35:44 +00:00
if err == storm.ErrNotFound {
2017-08-20 07:42:38 +00:00
return nil, fm.ErrNotExist
2017-08-19 11:35:44 +00:00
}
if err != nil {
return nil, err
}
2017-08-20 08:21:36 +00:00
us.FileSystem = builder(us.Scope)
2017-08-20 08:55:45 +00:00
return &us, nil
}
// GetByUsername gets a user with a certain username from the database.
func (u UsersStore) GetByUsername(username string, builder fm.FSBuilder) (*fm.User, error) {
var us fm.User
err := u.DB.One("Username", username, &us)
if err == storm.ErrNotFound {
return nil, fm.ErrNotExist
}
if err != nil {
return nil, err
}
us.FileSystem = builder(us.Scope)
return &us, nil
2017-08-19 11:35:44 +00:00
}
2017-08-20 08:27:03 +00:00
// Gets gets all the users from the database.
2017-08-20 08:21:36 +00:00
func (u UsersStore) Gets(builder fm.FSBuilder) ([]*fm.User, error) {
2017-08-19 11:35:44 +00:00
var us []*fm.User
2017-08-20 08:55:45 +00:00
err := u.DB.All(&us)
if err == storm.ErrNotFound {
return nil, fm.ErrNotExist
}
2017-08-20 08:21:36 +00:00
if err != nil {
return us, err
}
for _, user := range us {
user.FileSystem = builder(user.Scope)
}
2017-08-19 11:35:44 +00:00
return us, err
}
2017-08-20 08:55:45 +00:00
// Update updates the whole user object or only certain fields.
2017-08-19 11:35:44 +00:00
func (u UsersStore) Update(us *fm.User, fields ...string) error {
if len(fields) == 0 {
return u.Save(us)
}
for _, field := range fields {
val := reflect.ValueOf(us).Elem().FieldByName(field).Interface()
if err := u.DB.UpdateField(us, field, val); err != nil {
return err
}
}
return nil
}
2017-08-20 08:27:03 +00:00
// Save saves a user to the database.
2017-08-19 11:35:44 +00:00
func (u UsersStore) Save(us *fm.User) error {
return u.DB.Save(us)
}
2017-08-20 08:27:03 +00:00
// Delete deletes a user from the database.
2017-08-19 11:35:44 +00:00
func (u UsersStore) Delete(id int) error {
return u.DB.DeleteStruct(&fm.User{ID: id})
}