-
Notifications
You must be signed in to change notification settings - Fork 2
/
couchdb_adapter.go
109 lines (87 loc) · 2.44 KB
/
couchdb_adapter.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
package adapters
import (
"context"
_ "github.com/go-kivik/couchdb/v4" // The CouchDB driver
"github.com/go-kivik/kivik/v4"
)
type securityConfig struct {
names []string
roles []string
}
type couchdbAdapter struct {
db *kivik.Client
}
func (adapter couchdbAdapter) HasDatabase(ctx context.Context, database string) (bool, error) {
return adapter.db.DBExists(ctx, database)
}
func (adapter couchdbAdapter) CreateDatabase(ctx context.Context, database string) error {
return adapter.db.CreateDB(ctx, database)
}
func (adapter couchdbAdapter) DeleteDatabase(ctx context.Context, database string) error {
return adapter.db.DestroyDB(ctx, database)
}
func (adapter couchdbAdapter) HasDatabaseUserWithAccess(ctx context.Context, database string, username string) (bool, error) {
sc, err := adapter.db.DB(database).Security(ctx)
if err != nil {
return false, err
}
for _, name := range sc.Admins.Names {
if name == username {
return true, nil
}
}
return false, nil
}
func (adapter couchdbAdapter) CreateDatabaseUser(ctx context.Context, database string, username string, password string) error {
exists, err := adapter.db.DBExists(ctx, "_users")
if err != nil {
return err
}
if !exists {
err := adapter.db.CreateDB(ctx, "_users")
if err != nil {
return err
}
}
_, err = adapter.db.DB("_users").Put(ctx, kivik.UserPrefix+username, map[string]interface{}{
"_id": kivik.UserPrefix + username,
"name": username,
"type": "user",
"roles": []string{},
"password": password,
})
if err != nil {
return err
}
db := adapter.db.DB(database)
sc, err := db.Security(ctx)
if err != nil {
return err
}
sc.Admins.Names = append(sc.Admins.Names, username)
return db.SetSecurity(ctx, sc)
}
func (adapter couchdbAdapter) DeleteDatabaseUser(ctx context.Context, database string, username string) error {
userDB := adapter.db.DB("_users")
row := userDB.Get(ctx, kivik.UserPrefix+username)
_, err := userDB.Delete(ctx, kivik.UserPrefix+username, row.Rev())
return err
}
func (adapter couchdbAdapter) Close(ctx context.Context) error {
return adapter.db.Close(ctx)
}
func GetCouchdbConnection(ctx context.Context, url string) (*couchdbAdapter, error) {
client, err := kivik.New("couch", url)
if err != nil {
return nil, err
}
// do some call to test if connection is working
_, err = client.ClusterStatus(ctx)
if err != nil {
return nil, err
}
adapter := couchdbAdapter{
db: client,
}
return &adapter, nil
}