Skip to content

Commit 6547829

Browse files
authored
feat: add mongodb support (#82)
* feat: add mongodb enum * fix: isMongodb var condition * feat: add init mongodb connection * feat: add mongodb operations for various db methods * fix: error message
1 parent 2342f7c commit 6547829

File tree

10 files changed

+334
-76
lines changed

10 files changed

+334
-76
lines changed

server/db/arangodb.go

Lines changed: 4 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -23,7 +23,7 @@ func initArangodb() (arangoDriver.Database, error) {
2323
return nil, err
2424
}
2525

26-
client, err := arangoDriver.NewClient(arangoDriver.ClientConfig{
26+
arangoClient, err := arangoDriver.NewClient(arangoDriver.ClientConfig{
2727
Connection: conn,
2828
})
2929
if err != nil {
@@ -32,19 +32,19 @@ func initArangodb() (arangoDriver.Database, error) {
3232

3333
var arangodb driver.Database
3434

35-
arangodb_exists, err := client.DatabaseExists(nil, constants.DATABASE_NAME)
35+
arangodb_exists, err := arangoClient.DatabaseExists(nil, constants.DATABASE_NAME)
3636

3737
if arangodb_exists {
3838
log.Println(constants.DATABASE_NAME + " db exists already")
3939

40-
arangodb, err = client.Database(nil, constants.DATABASE_NAME)
40+
arangodb, err = arangoClient.Database(nil, constants.DATABASE_NAME)
4141

4242
if err != nil {
4343
return nil, err
4444
}
4545

4646
} else {
47-
arangodb, err = client.CreateDatabase(nil, constants.DATABASE_NAME, nil)
47+
arangodb, err = arangoClient.CreateDatabase(nil, constants.DATABASE_NAME, nil)
4848

4949
if err != nil {
5050
return nil, err
@@ -89,7 +89,6 @@ func initArangodb() (arangoDriver.Database, error) {
8989
Sparse: true,
9090
})
9191
verificationRequestCollection.EnsureHashIndex(ctx, []string{"token"}, &arangoDriver.EnsureHashIndexOptions{
92-
Unique: true,
9392
Sparse: true,
9493
})
9594

server/db/db.go

Lines changed: 26 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@ import (
66
arangoDriver "github.com/arangodb/go-driver"
77
"github.com/authorizerdev/authorizer/server/constants"
88
"github.com/authorizerdev/authorizer/server/enum"
9+
"go.mongodb.org/mongo-driver/mongo"
910
"gorm.io/driver/mysql"
1011
"gorm.io/driver/postgres"
1112
"gorm.io/driver/sqlite"
@@ -32,6 +33,7 @@ type Manager interface {
3233
type manager struct {
3334
sqlDB *gorm.DB
3435
arangodb arangoDriver.Database
36+
mongodb *mongo.Database
3537
}
3638

3739
// mainly used by nosql dbs
@@ -42,11 +44,12 @@ type CollectionList struct {
4244
}
4345

4446
var (
45-
IsSQL bool
46-
IsArangoDB bool
47-
Mgr Manager
48-
Prefix = "authorizer_"
49-
Collections = CollectionList{
47+
IsORMSupported bool
48+
IsArangoDB bool
49+
IsMongoDB bool
50+
Mgr Manager
51+
Prefix = "authorizer_"
52+
Collections = CollectionList{
5053
User: Prefix + "users",
5154
VerificationRequest: Prefix + "verification_requests",
5255
Session: Prefix + "sessions",
@@ -57,8 +60,9 @@ func InitDB() {
5760
var sqlDB *gorm.DB
5861
var err error
5962

60-
IsSQL = constants.DATABASE_TYPE != enum.Arangodb.String()
63+
IsORMSupported = constants.DATABASE_TYPE != enum.Arangodb.String() && constants.DATABASE_TYPE != enum.Mongodb.String()
6164
IsArangoDB = constants.DATABASE_TYPE == enum.Arangodb.String()
65+
IsMongoDB = constants.DATABASE_TYPE == enum.Mongodb.String()
6266

6367
// sql db orm config
6468
ormConfig := &gorm.Config{
@@ -85,19 +89,31 @@ func InitDB() {
8589
case enum.Arangodb.String():
8690
arangodb, err := initArangodb()
8791
if err != nil {
88-
log.Fatal("error initing arangodb:", err)
92+
log.Fatal("error initializing arangodb:", err)
8993
}
9094

9195
Mgr = &manager{
9296
sqlDB: nil,
97+
mongodb: nil,
9398
arangodb: arangodb,
9499
}
95100

96101
break
102+
case enum.Mongodb.String():
103+
mongodb, err := initMongodb()
104+
if err != nil {
105+
log.Fatal("error initializing mongodb connection:", err)
106+
}
107+
108+
Mgr = &manager{
109+
sqlDB: nil,
110+
arangodb: nil,
111+
mongodb: mongodb,
112+
}
97113
}
98114

99-
// common for all sql dbs that are configured via gorm
100-
if IsSQL {
115+
// common for all sql dbs that are configured via go-orm
116+
if IsORMSupported {
101117
if err != nil {
102118
log.Fatal("Failed to init sqlDB:", err)
103119
} else {
@@ -106,6 +122,7 @@ func InitDB() {
106122
Mgr = &manager{
107123
sqlDB: sqlDB,
108124
arangodb: nil,
125+
mongodb: nil,
109126
}
110127
}
111128
}

server/db/mongodb.go

Lines changed: 81 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,81 @@
1+
package db
2+
3+
import (
4+
"context"
5+
"time"
6+
7+
"github.com/authorizerdev/authorizer/server/constants"
8+
"go.mongodb.org/mongo-driver/bson"
9+
"go.mongodb.org/mongo-driver/mongo"
10+
"go.mongodb.org/mongo-driver/mongo/options"
11+
"go.mongodb.org/mongo-driver/mongo/readpref"
12+
)
13+
14+
func initMongodb() (*mongo.Database, error) {
15+
mongodbOptions := options.Client().ApplyURI(constants.DATABASE_URL)
16+
maxWait := time.Duration(5 * time.Second)
17+
mongodbOptions.ConnectTimeout = &maxWait
18+
mongoClient, err := mongo.NewClient(mongodbOptions)
19+
if err != nil {
20+
return nil, err
21+
}
22+
ctx, _ := context.WithTimeout(context.Background(), 30*time.Second)
23+
err = mongoClient.Connect(ctx)
24+
if err != nil {
25+
return nil, err
26+
}
27+
28+
err = mongoClient.Ping(ctx, readpref.Primary())
29+
if err != nil {
30+
return nil, err
31+
}
32+
33+
mongodb := mongoClient.Database(constants.DATABASE_NAME, options.Database())
34+
35+
mongodb.CreateCollection(ctx, Collections.User, options.CreateCollection())
36+
userCollection := mongodb.Collection(Collections.User, options.Collection())
37+
userCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
38+
mongo.IndexModel{
39+
Keys: bson.M{"id": 1},
40+
Options: options.Index().SetUnique(true).SetSparse(true),
41+
},
42+
}, options.CreateIndexes())
43+
userCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
44+
mongo.IndexModel{
45+
Keys: bson.M{"email": 1},
46+
Options: options.Index().SetUnique(true).SetSparse(true),
47+
},
48+
}, options.CreateIndexes())
49+
50+
mongodb.CreateCollection(ctx, Collections.VerificationRequest, options.CreateCollection())
51+
verificationRequestCollection := mongodb.Collection(Collections.VerificationRequest, options.Collection())
52+
verificationRequestCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
53+
mongo.IndexModel{
54+
Keys: bson.M{"id": 1},
55+
Options: options.Index().SetUnique(true).SetSparse(true),
56+
},
57+
}, options.CreateIndexes())
58+
verificationRequestCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
59+
mongo.IndexModel{
60+
Keys: bson.M{"email": 1, "identifier": 1},
61+
Options: options.Index().SetUnique(true).SetSparse(true),
62+
},
63+
}, options.CreateIndexes())
64+
verificationRequestCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
65+
mongo.IndexModel{
66+
Keys: bson.M{"token": 1},
67+
Options: options.Index().SetSparse(true),
68+
},
69+
}, options.CreateIndexes())
70+
71+
mongodb.CreateCollection(ctx, Collections.Session, options.CreateCollection())
72+
sessionCollection := mongodb.Collection(Collections.Session, options.Collection())
73+
sessionCollection.Indexes().CreateMany(ctx, []mongo.IndexModel{
74+
mongo.IndexModel{
75+
Keys: bson.M{"id": 1},
76+
Options: options.Index().SetUnique(true).SetSparse(true),
77+
},
78+
}, options.CreateIndexes())
79+
80+
return mongodb, nil
81+
}

server/db/session.go

Lines changed: 24 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -5,19 +5,20 @@ import (
55
"time"
66

77
"github.com/google/uuid"
8+
"go.mongodb.org/mongo-driver/mongo/options"
89
"gorm.io/gorm/clause"
910
)
1011

1112
type Session struct {
12-
Key string `json:"_key,omitempty"` // for arangodb
13-
ObjectID string `json:"_id,omitempty"` // for arangodb & mongodb
14-
ID string `gorm:"primaryKey;type:char(36)" json:"id"`
15-
UserID string `gorm:"type:char(36)" json:"user_id"`
16-
User User `json:"-"`
17-
UserAgent string `json:"user_agent"`
18-
IP string `json:"ip"`
19-
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
20-
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
13+
Key string `json:"_key,omitempty" bson:"_key,omitempty"` // for arangodb
14+
ObjectID string `json:"_id,omitempty" bson:"_id"` // for arangodb & mongodb
15+
ID string `gorm:"primaryKey;type:char(36)" json:"id" bson:"id"`
16+
UserID string `gorm:"type:char(36)" json:"user_id" bson:"user_id"`
17+
User User `json:"-" bson:"-"`
18+
UserAgent string `json:"user_agent" bson:"user_agent"`
19+
IP string `json:"ip" bson:"ip"`
20+
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at" bson:"created_at"`
21+
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at" bson:"updated_at"`
2122
}
2223

2324
// AddSession function to save user sessiosn
@@ -26,16 +27,7 @@ func (mgr *manager) AddSession(session Session) error {
2627
session.ID = uuid.New().String()
2728
}
2829

29-
if session.CreatedAt == 0 {
30-
session.CreatedAt = time.Now().Unix()
31-
}
32-
33-
if session.UpdatedAt == 0 {
34-
session.CreatedAt = time.Now().Unix()
35-
}
36-
37-
if IsSQL {
38-
// copy id as value for fields required for mongodb & arangodb
30+
if IsORMSupported {
3931
session.Key = session.ID
4032
session.ObjectID = session.ID
4133
res := mgr.sqlDB.Clauses(
@@ -49,7 +41,6 @@ func (mgr *manager) AddSession(session Session) error {
4941
}
5042

5143
if IsArangoDB {
52-
5344
session.CreatedAt = time.Now().Unix()
5445
session.UpdatedAt = time.Now().Unix()
5546
sessionCollection, _ := mgr.arangodb.Collection(nil, Collections.Session)
@@ -60,5 +51,18 @@ func (mgr *manager) AddSession(session Session) error {
6051
}
6152
}
6253

54+
if IsMongoDB {
55+
session.Key = session.ID
56+
session.ObjectID = session.ID
57+
session.CreatedAt = time.Now().Unix()
58+
session.UpdatedAt = time.Now().Unix()
59+
sessionCollection := mgr.mongodb.Collection(Collections.Session, options.Collection())
60+
_, err := sessionCollection.InsertOne(nil, session)
61+
if err != nil {
62+
log.Println(`error saving session`, err)
63+
return err
64+
}
65+
}
66+
6367
return nil
6468
}

0 commit comments

Comments
 (0)