2019-05-06 00:56:27 +00:00
|
|
|
package repositories
|
|
|
|
|
|
|
|
import (
|
|
|
|
"context"
|
|
|
|
|
|
|
|
"github.com/mediocregopher/radix/v3"
|
|
|
|
"github.com/mitchell/selfpass/credentials/types"
|
|
|
|
)
|
|
|
|
|
2019-05-22 15:22:40 +00:00
|
|
|
func NewRedisConn(networkType, address string, connCount uint, options ...radix.PoolOpt) (c RedisConn, err error) {
|
|
|
|
p, err := radix.NewPool(networkType, address, int(connCount), options...)
|
2019-05-06 00:56:27 +00:00
|
|
|
return RedisConn{p: p}, err
|
|
|
|
}
|
|
|
|
|
|
|
|
type RedisConn struct {
|
|
|
|
p *radix.Pool
|
|
|
|
}
|
|
|
|
|
|
|
|
func (conn RedisConn) GetAllMetadata(ctx context.Context, sourceHost string, errch chan<- error) (output <-chan types.Metadata) {
|
|
|
|
mdch := make(chan types.Metadata, 1)
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
defer close(mdch)
|
|
|
|
|
|
|
|
var key string
|
2019-05-22 15:22:40 +00:00
|
|
|
scr := radix.NewScanner(conn.p, radix.ScanOpts{Command: scan, Pattern: types.TypePrefixCred + dash + sourceHost + star})
|
2019-05-06 00:56:27 +00:00
|
|
|
|
|
|
|
for scr.Next(&key) {
|
|
|
|
select {
|
|
|
|
case <-ctx.Done():
|
|
|
|
return
|
|
|
|
default:
|
2019-05-22 15:22:40 +00:00
|
|
|
}
|
2019-05-06 00:56:27 +00:00
|
|
|
|
2019-05-22 15:22:40 +00:00
|
|
|
var md types.Metadata
|
2019-05-06 00:56:27 +00:00
|
|
|
|
2019-05-22 15:22:40 +00:00
|
|
|
if err := conn.p.Do(radix.Cmd(&md, hGetAll, key)); err != nil {
|
|
|
|
errch <- err
|
|
|
|
return
|
2019-05-06 00:56:27 +00:00
|
|
|
}
|
2019-05-22 15:22:40 +00:00
|
|
|
|
|
|
|
mdch <- md
|
2019-05-06 00:56:27 +00:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
return mdch
|
|
|
|
}
|
|
|
|
|
|
|
|
func (conn RedisConn) Get(ctx context.Context, id string) (output types.Credential, err error) {
|
2019-05-22 15:22:40 +00:00
|
|
|
err = conn.p.Do(radix.Cmd(&output, hGetAll, id))
|
2019-05-06 00:56:27 +00:00
|
|
|
return output, err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (conn RedisConn) Put(ctx context.Context, c types.Credential) (err error) {
|
2019-05-22 15:22:40 +00:00
|
|
|
err = conn.p.Do(radix.FlatCmd(nil, hMSet, c.ID, c))
|
2019-05-06 00:56:27 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (conn RedisConn) Delete(ctx context.Context, id string) (err error) {
|
2019-05-22 15:22:40 +00:00
|
|
|
err = conn.p.Do(radix.Cmd(nil, del, id))
|
2019-05-06 00:56:27 +00:00
|
|
|
return err
|
|
|
|
}
|
|
|
|
|
|
|
|
func (conn RedisConn) DumpDB(ctx context.Context) (bs []byte, err error) {
|
|
|
|
bs = []byte{}
|
|
|
|
|
|
|
|
if err := conn.p.Do(radix.Cmd(&bs, "DUMP")); err != nil {
|
|
|
|
return nil, err
|
|
|
|
}
|
|
|
|
|
|
|
|
return bs, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
const (
|
|
|
|
dash = "-"
|
|
|
|
star = "*"
|
|
|
|
scan = "SCAN"
|
|
|
|
hGetAll = "HGETALL"
|
|
|
|
hMSet = "HMSET"
|
|
|
|
del = "DEL"
|
|
|
|
)
|