You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
75 lines
1.5 KiB
75 lines
1.5 KiB
package mongodb
|
|
|
|
import (
|
|
"context"
|
|
"git.aiterp.net/rpdata/api/internal/generate"
|
|
"git.aiterp.net/rpdata/api/models"
|
|
"git.aiterp.net/rpdata/api/repositories"
|
|
"github.com/globalsign/mgo"
|
|
"github.com/globalsign/mgo/bson"
|
|
)
|
|
|
|
type keyRepository struct {
|
|
restoreIDs bool
|
|
keys *mgo.Collection
|
|
}
|
|
|
|
func newKeyRepository(db *mgo.Database, restoreIDs bool) (repositories.KeyRepository, error) {
|
|
collection := db.C("auth.keys")
|
|
|
|
err := collection.EnsureIndexKey("user")
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &keyRepository{
|
|
keys: collection,
|
|
restoreIDs: restoreIDs,
|
|
}, nil
|
|
}
|
|
|
|
func (r *keyRepository) Find(ctx context.Context, id string) (*models.Key, error) {
|
|
key := models.Key{}
|
|
err := r.keys.FindId(id).One(&key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &key, err
|
|
}
|
|
|
|
func (r *keyRepository) List(ctx context.Context, filter models.KeyFilter) ([]*models.Key, error) {
|
|
query := bson.M{}
|
|
if filter.UserID != nil {
|
|
query["user"] = *filter.UserID
|
|
}
|
|
|
|
keys := make([]*models.Key, 0, 4)
|
|
err := r.keys.Find(query).All(&keys)
|
|
if err != nil {
|
|
if err == mgo.ErrNotFound {
|
|
return nil, nil
|
|
}
|
|
|
|
return nil, err
|
|
}
|
|
|
|
return keys, nil
|
|
}
|
|
|
|
func (r *keyRepository) Insert(ctx context.Context, key models.Key) (*models.Key, error) {
|
|
if !r.restoreIDs {
|
|
key.ID = generate.KeyID()
|
|
}
|
|
|
|
err := r.keys.Insert(&key)
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return &key, nil
|
|
}
|
|
|
|
func (r *keyRepository) Delete(ctx context.Context, key models.Key) error {
|
|
return r.keys.RemoveId(key.ID)
|
|
}
|