feat/add arangodb support (#80)
*feat: add arangodb init * fix: dao for sql + arangodb * fix: update error logs * fix: use db name dynamically
This commit is contained in:
113
server/db/arangodb.go
Normal file
113
server/db/arangodb.go
Normal file
@@ -0,0 +1,113 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log"
|
||||
|
||||
"github.com/arangodb/go-driver"
|
||||
arangoDriver "github.com/arangodb/go-driver"
|
||||
"github.com/arangodb/go-driver/http"
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
)
|
||||
|
||||
// for this we need arangodb instance up and running
|
||||
// for local testing we can use dockerized version of it
|
||||
// docker run -p 8529:8529 -e ARANGO_ROOT_PASSWORD=root arangodb/arangodb:3.8.4
|
||||
|
||||
func initArangodb() (arangoDriver.Database, error) {
|
||||
ctx := context.Background()
|
||||
conn, err := http.NewConnection(http.ConnectionConfig{
|
||||
Endpoints: []string{constants.DATABASE_URL},
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
client, err := arangoDriver.NewClient(arangoDriver.ClientConfig{
|
||||
Connection: conn,
|
||||
})
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
var arangodb driver.Database
|
||||
|
||||
arangodb_exists, err := client.DatabaseExists(nil, constants.DATABASE_NAME)
|
||||
|
||||
if arangodb_exists {
|
||||
log.Println(constants.DATABASE_NAME + " db exists already")
|
||||
|
||||
arangodb, err = client.Database(nil, constants.DATABASE_NAME)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
} else {
|
||||
arangodb, err = client.CreateDatabase(nil, constants.DATABASE_NAME, nil)
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
|
||||
userCollectionExists, err := arangodb.CollectionExists(ctx, Collections.User)
|
||||
if userCollectionExists {
|
||||
log.Println(Collections.User + " collection exists already")
|
||||
} else {
|
||||
_, err = arangodb.CreateCollection(ctx, Collections.User, nil)
|
||||
if err != nil {
|
||||
log.Println("error creating collection("+Collections.User+"):", err)
|
||||
}
|
||||
}
|
||||
userCollection, _ := arangodb.Collection(nil, Collections.User)
|
||||
userCollection.EnsureHashIndex(ctx, []string{"id"}, &arangoDriver.EnsureHashIndexOptions{
|
||||
Unique: true,
|
||||
Sparse: true,
|
||||
})
|
||||
userCollection.EnsureHashIndex(ctx, []string{"email"}, &arangoDriver.EnsureHashIndexOptions{
|
||||
Unique: true,
|
||||
Sparse: true,
|
||||
})
|
||||
|
||||
verificationRequestCollectionExists, err := arangodb.CollectionExists(ctx, Collections.VerificationRequest)
|
||||
if verificationRequestCollectionExists {
|
||||
log.Println(Collections.VerificationRequest + " collection exists already")
|
||||
} else {
|
||||
_, err = arangodb.CreateCollection(ctx, Collections.VerificationRequest, nil)
|
||||
if err != nil {
|
||||
log.Println("error creating collection("+Collections.VerificationRequest+"):", err)
|
||||
}
|
||||
}
|
||||
verificationRequestCollection, _ := arangodb.Collection(nil, Collections.VerificationRequest)
|
||||
verificationRequestCollection.EnsureHashIndex(ctx, []string{"id"}, &arangoDriver.EnsureHashIndexOptions{
|
||||
Unique: true,
|
||||
Sparse: true,
|
||||
})
|
||||
verificationRequestCollection.EnsureHashIndex(ctx, []string{"email", "identifier"}, &arangoDriver.EnsureHashIndexOptions{
|
||||
Unique: true,
|
||||
Sparse: true,
|
||||
})
|
||||
verificationRequestCollection.EnsureHashIndex(ctx, []string{"token"}, &arangoDriver.EnsureHashIndexOptions{
|
||||
Unique: true,
|
||||
Sparse: true,
|
||||
})
|
||||
|
||||
sessionCollectionExists, err := arangodb.CollectionExists(ctx, Collections.Session)
|
||||
if sessionCollectionExists {
|
||||
log.Println(Collections.Session + " collection exists already")
|
||||
} else {
|
||||
_, err = arangodb.CreateCollection(ctx, Collections.Session, nil)
|
||||
if err != nil {
|
||||
log.Println("error creating collection("+Collections.Session+"):", err)
|
||||
}
|
||||
}
|
||||
|
||||
sessionCollection, _ := arangodb.Collection(nil, Collections.Session)
|
||||
sessionCollection.EnsureHashIndex(ctx, []string{"id"}, &arangoDriver.EnsureHashIndexOptions{
|
||||
Unique: true,
|
||||
Sparse: true,
|
||||
})
|
||||
|
||||
return arangodb, err
|
||||
}
|
@@ -3,9 +3,9 @@ package db
|
||||
import (
|
||||
"log"
|
||||
|
||||
arangoDriver "github.com/arangodb/go-driver"
|
||||
"github.com/authorizerdev/authorizer/server/constants"
|
||||
"github.com/authorizerdev/authorizer/server/enum"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/driver/postgres"
|
||||
"gorm.io/driver/sqlite"
|
||||
@@ -14,51 +14,94 @@ import (
|
||||
)
|
||||
|
||||
type Manager interface {
|
||||
SaveUser(user User) (User, error)
|
||||
AddUser(user User) (User, error)
|
||||
UpdateUser(user User) (User, error)
|
||||
DeleteUser(user User) error
|
||||
GetUsers() ([]User, error)
|
||||
GetUserByEmail(email string) (User, error)
|
||||
GetUserByID(email string) (User, error)
|
||||
UpdateVerificationTime(verifiedAt int64, id uuid.UUID) error
|
||||
AddVerification(verification VerificationRequest) (VerificationRequest, error)
|
||||
GetVerificationByToken(token string) (VerificationRequest, error)
|
||||
DeleteToken(email string) error
|
||||
DeleteVerificationRequest(verificationRequest VerificationRequest) error
|
||||
GetVerificationRequests() ([]VerificationRequest, error)
|
||||
GetVerificationByEmail(email string) (VerificationRequest, error)
|
||||
DeleteUser(email string) error
|
||||
SaveRoles(roles []Role) error
|
||||
SaveSession(session Session) error
|
||||
AddSession(session Session) error
|
||||
}
|
||||
|
||||
type manager struct {
|
||||
db *gorm.DB
|
||||
sqlDB *gorm.DB
|
||||
arangodb arangoDriver.Database
|
||||
}
|
||||
|
||||
var Mgr Manager
|
||||
// mainly used by nosql dbs
|
||||
type CollectionList struct {
|
||||
User string
|
||||
VerificationRequest string
|
||||
Session string
|
||||
}
|
||||
|
||||
var (
|
||||
IsSQL bool
|
||||
IsArangoDB bool
|
||||
Mgr Manager
|
||||
Prefix = "authorizer_"
|
||||
Collections = CollectionList{
|
||||
User: Prefix + "users",
|
||||
VerificationRequest: Prefix + "verification_requests",
|
||||
Session: Prefix + "sessions",
|
||||
}
|
||||
)
|
||||
|
||||
func InitDB() {
|
||||
var db *gorm.DB
|
||||
var sqlDB *gorm.DB
|
||||
var err error
|
||||
|
||||
IsSQL = constants.DATABASE_TYPE != enum.Arangodb.String()
|
||||
IsArangoDB = constants.DATABASE_TYPE == enum.Arangodb.String()
|
||||
|
||||
// sql db orm config
|
||||
ormConfig := &gorm.Config{
|
||||
NamingStrategy: schema.NamingStrategy{
|
||||
TablePrefix: "authorizer_",
|
||||
TablePrefix: Prefix,
|
||||
},
|
||||
}
|
||||
if constants.DATABASE_TYPE == enum.Postgres.String() {
|
||||
db, err = gorm.Open(postgres.Open(constants.DATABASE_URL), ormConfig)
|
||||
}
|
||||
if constants.DATABASE_TYPE == enum.Mysql.String() {
|
||||
db, err = gorm.Open(mysql.Open(constants.DATABASE_URL), ormConfig)
|
||||
}
|
||||
if constants.DATABASE_TYPE == enum.Sqlite.String() {
|
||||
db, err = gorm.Open(sqlite.Open(constants.DATABASE_URL), ormConfig)
|
||||
|
||||
log.Println("db type:", constants.DATABASE_TYPE)
|
||||
|
||||
switch constants.DATABASE_TYPE {
|
||||
case enum.Postgres.String():
|
||||
sqlDB, err = gorm.Open(postgres.Open(constants.DATABASE_URL), ormConfig)
|
||||
break
|
||||
case enum.Sqlite.String():
|
||||
sqlDB, err = gorm.Open(sqlite.Open(constants.DATABASE_URL), ormConfig)
|
||||
break
|
||||
case enum.Mysql.String():
|
||||
sqlDB, err = gorm.Open(mysql.Open(constants.DATABASE_URL), ormConfig)
|
||||
break
|
||||
case enum.Arangodb.String():
|
||||
arangodb, err := initArangodb()
|
||||
if err != nil {
|
||||
log.Fatal("error initing arangodb:", err)
|
||||
}
|
||||
|
||||
Mgr = &manager{
|
||||
sqlDB: nil,
|
||||
arangodb: arangodb,
|
||||
}
|
||||
|
||||
break
|
||||
}
|
||||
|
||||
if err != nil {
|
||||
log.Fatal("Failed to init db:", err)
|
||||
} else {
|
||||
db.AutoMigrate(&User{}, &VerificationRequest{}, &Role{}, &Session{})
|
||||
// common for all sql dbs that are configured via gorm
|
||||
if IsSQL {
|
||||
if err != nil {
|
||||
log.Fatal("Failed to init sqlDB:", err)
|
||||
} else {
|
||||
sqlDB.AutoMigrate(&User{}, &VerificationRequest{}, &Session{})
|
||||
}
|
||||
Mgr = &manager{
|
||||
sqlDB: sqlDB,
|
||||
arangodb: nil,
|
||||
}
|
||||
}
|
||||
|
||||
Mgr = &manager{db: db}
|
||||
}
|
||||
|
@@ -1,34 +0,0 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"log"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type Role struct {
|
||||
ID uuid.UUID `gorm:"primaryKey;type:char(36)"`
|
||||
Role string `gorm:"unique"`
|
||||
}
|
||||
|
||||
func (r *Role) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
r.ID = uuid.New()
|
||||
|
||||
return
|
||||
}
|
||||
|
||||
// SaveRoles function to save roles
|
||||
func (mgr *manager) SaveRoles(roles []Role) error {
|
||||
res := mgr.db.Clauses(
|
||||
clause.OnConflict{
|
||||
DoNothing: true,
|
||||
}).Create(&roles)
|
||||
if res.Error != nil {
|
||||
log.Println(`Error saving roles`)
|
||||
return res.Error
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
@@ -2,37 +2,62 @@ package db
|
||||
|
||||
import (
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type Session struct {
|
||||
ID uuid.UUID `gorm:"primaryKey;type:char(36)"`
|
||||
UserID uuid.UUID `gorm:"type:char(36)"`
|
||||
User User
|
||||
UserAgent string
|
||||
IP string
|
||||
CreatedAt int64 `gorm:"autoCreateTime"`
|
||||
UpdatedAt int64 `gorm:"autoUpdateTime"`
|
||||
Key string `json:"_key,omitempty"` // for arangodb
|
||||
ObjectID string `json:"_id,omitempty"` // for arangodb & mongodb
|
||||
ID string `gorm:"primaryKey;type:char(36)" json:"id"`
|
||||
UserID string `gorm:"type:char(36)" json:"user_id"`
|
||||
User User `json:"-"`
|
||||
UserAgent string `json:"user_agent"`
|
||||
IP string `json:"ip"`
|
||||
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
}
|
||||
|
||||
func (r *Session) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
r.ID = uuid.New()
|
||||
// AddSession function to save user sessiosn
|
||||
func (mgr *manager) AddSession(session Session) error {
|
||||
if session.ID == "" {
|
||||
session.ID = uuid.New().String()
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
if session.CreatedAt == 0 {
|
||||
session.CreatedAt = time.Now().Unix()
|
||||
}
|
||||
|
||||
// SaveSession function to save user sessiosn
|
||||
func (mgr *manager) SaveSession(session Session) error {
|
||||
res := mgr.db.Clauses(
|
||||
clause.OnConflict{
|
||||
DoNothing: true,
|
||||
}).Create(&session)
|
||||
if res.Error != nil {
|
||||
log.Println(`Error saving session`, res.Error)
|
||||
return res.Error
|
||||
if session.UpdatedAt == 0 {
|
||||
session.CreatedAt = time.Now().Unix()
|
||||
}
|
||||
|
||||
if IsSQL {
|
||||
// copy id as value for fields required for mongodb & arangodb
|
||||
session.Key = session.ID
|
||||
session.ObjectID = session.ID
|
||||
res := mgr.sqlDB.Clauses(
|
||||
clause.OnConflict{
|
||||
DoNothing: true,
|
||||
}).Create(&session)
|
||||
if res.Error != nil {
|
||||
log.Println(`error saving session`, res.Error)
|
||||
return res.Error
|
||||
}
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
|
||||
session.CreatedAt = time.Now().Unix()
|
||||
session.UpdatedAt = time.Now().Unix()
|
||||
sessionCollection, _ := mgr.arangodb.Collection(nil, Collections.Session)
|
||||
_, err := sessionCollection.CreateDocument(nil, session)
|
||||
if err != nil {
|
||||
log.Println(`error saving session`, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
|
@@ -1,45 +1,68 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
"log"
|
||||
"time"
|
||||
|
||||
"github.com/arangodb/go-driver"
|
||||
arangoDriver "github.com/arangodb/go-driver"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uuid.UUID `gorm:"primaryKey;type:char(36)"`
|
||||
FirstName string
|
||||
LastName string
|
||||
Email string `gorm:"unique"`
|
||||
Password string `gorm:"type:text"`
|
||||
SignupMethod string
|
||||
EmailVerifiedAt int64
|
||||
CreatedAt int64 `gorm:"autoCreateTime"`
|
||||
UpdatedAt int64 `gorm:"autoUpdateTime"`
|
||||
Image string `gorm:"type:text"`
|
||||
Roles string
|
||||
Key string `json:"_key,omitempty"` // for arangodb
|
||||
ObjectID string `json:"_id,omitempty"` // for arangodb & mongodb
|
||||
ID string `gorm:"primaryKey;type:char(36)" json:"id"`
|
||||
FirstName string `json:"first_name"`
|
||||
LastName string `json:"last_name"`
|
||||
Email string `gorm:"unique" json:"email"`
|
||||
Password string `gorm:"type:text" json:"password"`
|
||||
SignupMethod string `json:"signup_method"`
|
||||
EmailVerifiedAt int64 `json:"email_verified_at"`
|
||||
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
Image string `gorm:"type:text" json:"image"`
|
||||
Roles string `json:"roles"`
|
||||
}
|
||||
|
||||
func (u *User) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
u.ID = uuid.New()
|
||||
// AddUser function to add user even with email conflict
|
||||
func (mgr *manager) AddUser(user User) (User, error) {
|
||||
if user.ID == "" {
|
||||
user.ID = uuid.New().String()
|
||||
}
|
||||
|
||||
return
|
||||
}
|
||||
if IsSQL {
|
||||
// copy id as value for fields required for mongodb & arangodb
|
||||
user.Key = user.ID
|
||||
user.ObjectID = user.ID
|
||||
result := mgr.sqlDB.Clauses(
|
||||
clause.OnConflict{
|
||||
UpdateAll: true,
|
||||
Columns: []clause.Column{{Name: "email"}},
|
||||
}).Create(&user)
|
||||
|
||||
// SaveUser function to add user even with email conflict
|
||||
func (mgr *manager) SaveUser(user User) (User, error) {
|
||||
result := mgr.db.Clauses(
|
||||
clause.OnConflict{
|
||||
UpdateAll: true,
|
||||
Columns: []clause.Column{{Name: "email"}},
|
||||
}).Create(&user)
|
||||
if result.Error != nil {
|
||||
log.Println("error adding user:", result.Error)
|
||||
return user, result.Error
|
||||
}
|
||||
}
|
||||
|
||||
if result.Error != nil {
|
||||
log.Println(result.Error)
|
||||
return user, result.Error
|
||||
if IsArangoDB {
|
||||
user.CreatedAt = time.Now().Unix()
|
||||
user.UpdatedAt = time.Now().Unix()
|
||||
ctx := context.Background()
|
||||
userCollection, _ := mgr.arangodb.Collection(nil, Collections.User)
|
||||
meta, err := userCollection.CreateDocument(arangoDriver.WithOverwrite(ctx), user)
|
||||
if err != nil {
|
||||
log.Println("error adding user:", err)
|
||||
return user, err
|
||||
}
|
||||
user.Key = meta.Key
|
||||
user.ObjectID = meta.ID.String()
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
@@ -47,15 +70,26 @@ func (mgr *manager) SaveUser(user User) (User, error) {
|
||||
// UpdateUser function to update user with ID conflict
|
||||
func (mgr *manager) UpdateUser(user User) (User, error) {
|
||||
user.UpdatedAt = time.Now().Unix()
|
||||
result := mgr.db.Clauses(
|
||||
clause.OnConflict{
|
||||
UpdateAll: true,
|
||||
Columns: []clause.Column{{Name: "email"}},
|
||||
}).Create(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
log.Println(result.Error)
|
||||
return user, result.Error
|
||||
if IsSQL {
|
||||
result := mgr.sqlDB.Save(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
log.Println("error updating user:", result.Error)
|
||||
return user, result.Error
|
||||
}
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
collection, _ := mgr.arangodb.Collection(nil, Collections.User)
|
||||
meta, err := collection.UpdateDocument(nil, user.Key, user)
|
||||
if err != nil {
|
||||
log.Println("error updating user:", err)
|
||||
return user, err
|
||||
}
|
||||
|
||||
user.Key = meta.Key
|
||||
user.ObjectID = meta.ID.String()
|
||||
}
|
||||
return user, nil
|
||||
}
|
||||
@@ -63,20 +97,76 @@ func (mgr *manager) UpdateUser(user User) (User, error) {
|
||||
// GetUsers function to get all users
|
||||
func (mgr *manager) GetUsers() ([]User, error) {
|
||||
var users []User
|
||||
result := mgr.db.Find(&users)
|
||||
if result.Error != nil {
|
||||
log.Println(result.Error)
|
||||
return users, result.Error
|
||||
|
||||
if IsSQL {
|
||||
result := mgr.sqlDB.Find(&users)
|
||||
if result.Error != nil {
|
||||
log.Println("error getting users:", result.Error)
|
||||
return users, result.Error
|
||||
}
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
query := fmt.Sprintf("FOR d in %s RETURN d", Collections.User)
|
||||
|
||||
cursor, err := mgr.arangodb.Query(nil, query, nil)
|
||||
if err != nil {
|
||||
return users, err
|
||||
}
|
||||
defer cursor.Close()
|
||||
|
||||
for {
|
||||
var user User
|
||||
meta, err := cursor.ReadDocument(nil, &user)
|
||||
|
||||
if driver.IsNoMoreDocuments(err) {
|
||||
break
|
||||
} else if err != nil {
|
||||
return users, err
|
||||
}
|
||||
|
||||
if meta.Key != "" {
|
||||
user.Key = meta.Key
|
||||
user.ObjectID = meta.ID.String()
|
||||
users = append(users, user)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return users, nil
|
||||
}
|
||||
|
||||
func (mgr *manager) GetUserByEmail(email string) (User, error) {
|
||||
var user User
|
||||
result := mgr.db.Where("email = ?", email).First(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
return user, result.Error
|
||||
if IsSQL {
|
||||
result := mgr.sqlDB.Where("email = ?", email).First(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
return user, result.Error
|
||||
}
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
query := fmt.Sprintf("FOR d in %s FILTER d.email == @email LIMIT 1 RETURN d", Collections.User)
|
||||
bindVars := map[string]interface{}{
|
||||
"email": email,
|
||||
}
|
||||
|
||||
cursor, err := mgr.arangodb.Query(nil, query, bindVars)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
defer cursor.Close()
|
||||
|
||||
for {
|
||||
_, err := cursor.ReadDocument(nil, &user)
|
||||
if driver.IsNoMoreDocuments(err) {
|
||||
break
|
||||
} else if err != nil {
|
||||
return user, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return user, nil
|
||||
@@ -84,35 +174,62 @@ func (mgr *manager) GetUserByEmail(email string) (User, error) {
|
||||
|
||||
func (mgr *manager) GetUserByID(id string) (User, error) {
|
||||
var user User
|
||||
result := mgr.db.Where("id = ?", id).First(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
return user, result.Error
|
||||
if IsSQL {
|
||||
result := mgr.sqlDB.Where("id = ?", id).First(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
return user, result.Error
|
||||
}
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
query := fmt.Sprintf("FOR d in %s FILTER d.id == @id LIMIT 1 RETURN d", Collections.User)
|
||||
bindVars := map[string]interface{}{
|
||||
"id": id,
|
||||
}
|
||||
|
||||
cursor, err := mgr.arangodb.Query(nil, query, bindVars)
|
||||
if err != nil {
|
||||
return user, err
|
||||
}
|
||||
defer cursor.Close()
|
||||
|
||||
count := cursor.Count()
|
||||
if count == 0 {
|
||||
return user, errors.New("user not found")
|
||||
}
|
||||
|
||||
for {
|
||||
_, err := cursor.ReadDocument(nil, &user)
|
||||
if driver.IsNoMoreDocuments(err) {
|
||||
break
|
||||
} else if err != nil {
|
||||
return user, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return user, nil
|
||||
}
|
||||
|
||||
func (mgr *manager) UpdateVerificationTime(verifiedAt int64, id uuid.UUID) error {
|
||||
user := &User{
|
||||
ID: id,
|
||||
}
|
||||
result := mgr.db.Model(&user).Where("id = ?", id).Update("email_verified_at", verifiedAt)
|
||||
func (mgr *manager) DeleteUser(user User) error {
|
||||
if IsSQL {
|
||||
result := mgr.sqlDB.Delete(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
return result.Error
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func (mgr *manager) DeleteUser(email string) error {
|
||||
var user User
|
||||
result := mgr.db.Where("email = ?", email).Delete(&user)
|
||||
|
||||
if result.Error != nil {
|
||||
log.Println(`Error deleting user:`, result.Error)
|
||||
return result.Error
|
||||
if result.Error != nil {
|
||||
log.Println(`error deleting user:`, result.Error)
|
||||
return result.Error
|
||||
}
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
collection, _ := mgr.arangodb.Collection(nil, Collections.User)
|
||||
_, err := collection.RemoveDocument(nil, user.Key)
|
||||
if err != nil {
|
||||
log.Println(`error deleting user:`, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
|
@@ -1,50 +1,132 @@
|
||||
package db
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
|
||||
"github.com/arangodb/go-driver"
|
||||
"github.com/google/uuid"
|
||||
"gorm.io/gorm"
|
||||
"gorm.io/gorm/clause"
|
||||
)
|
||||
|
||||
type VerificationRequest struct {
|
||||
ID uuid.UUID `gorm:"primaryKey;type:char(36)"`
|
||||
Token string `gorm:"type:text"`
|
||||
Identifier string
|
||||
ExpiresAt int64
|
||||
CreatedAt int64 `gorm:"autoCreateTime"`
|
||||
UpdatedAt int64 `gorm:"autoUpdateTime"`
|
||||
Email string `gorm:"unique"`
|
||||
}
|
||||
|
||||
func (v *VerificationRequest) BeforeCreate(tx *gorm.DB) (err error) {
|
||||
v.ID = uuid.New()
|
||||
|
||||
return
|
||||
Key string `json:"_key,omitempty"` // for arangodb
|
||||
ObjectID string `json:"_id,omitempty"` // for arangodb & mongodb
|
||||
ID string `gorm:"primaryKey;type:char(36)" json:"id"`
|
||||
Token string `gorm:"type:text" json:"token"`
|
||||
Identifier string `gorm:"uniqueIndex:idx_email_identifier" json:"identifier"`
|
||||
ExpiresAt int64 `json:"expires_at"`
|
||||
CreatedAt int64 `gorm:"autoCreateTime" json:"created_at"`
|
||||
UpdatedAt int64 `gorm:"autoUpdateTime" json:"updated_at"`
|
||||
Email string `gorm:"uniqueIndex:idx_email_identifier" json:"email"`
|
||||
}
|
||||
|
||||
// AddVerification function to add verification record
|
||||
func (mgr *manager) AddVerification(verification VerificationRequest) (VerificationRequest, error) {
|
||||
result := mgr.db.Clauses(clause.OnConflict{
|
||||
Columns: []clause.Column{{Name: "email"}},
|
||||
DoUpdates: clause.AssignmentColumns([]string{"token", "identifier", "expires_at"}),
|
||||
}).Create(&verification)
|
||||
if verification.ID == "" {
|
||||
verification.ID = uuid.New().String()
|
||||
}
|
||||
if IsSQL {
|
||||
// copy id as value for fields required for mongodb & arangodb
|
||||
verification.Key = verification.ID
|
||||
verification.ObjectID = verification.ID
|
||||
result := mgr.sqlDB.Clauses(clause.OnConflict{
|
||||
DoUpdates: clause.AssignmentColumns([]string{"token", "expires_at"}),
|
||||
}).Create(&verification)
|
||||
|
||||
if result.Error != nil {
|
||||
log.Println(`Error saving verification record`, result.Error)
|
||||
return verification, result.Error
|
||||
if result.Error != nil {
|
||||
log.Println(`error saving verification record`, result.Error)
|
||||
return verification, result.Error
|
||||
}
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
verificationRequestCollection, _ := mgr.arangodb.Collection(nil, Collections.VerificationRequest)
|
||||
meta, err := verificationRequestCollection.CreateDocument(nil, verification)
|
||||
if err != nil {
|
||||
return verification, err
|
||||
}
|
||||
verification.Key = meta.Key
|
||||
verification.ObjectID = meta.ID.String()
|
||||
}
|
||||
return verification, nil
|
||||
}
|
||||
|
||||
// GetVerificationRequests function to get all verification requests
|
||||
func (mgr *manager) GetVerificationRequests() ([]VerificationRequest, error) {
|
||||
var verificationRequests []VerificationRequest
|
||||
|
||||
if IsSQL {
|
||||
result := mgr.sqlDB.Find(&verificationRequests)
|
||||
if result.Error != nil {
|
||||
log.Println("error getting verification requests:", result.Error)
|
||||
return verificationRequests, result.Error
|
||||
}
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
query := fmt.Sprintf("FOR d in %s RETURN d", Collections.VerificationRequest)
|
||||
|
||||
cursor, err := mgr.arangodb.Query(nil, query, nil)
|
||||
if err != nil {
|
||||
return verificationRequests, err
|
||||
}
|
||||
defer cursor.Close()
|
||||
|
||||
for {
|
||||
var verificationRequest VerificationRequest
|
||||
meta, err := cursor.ReadDocument(nil, &verificationRequest)
|
||||
|
||||
if driver.IsNoMoreDocuments(err) {
|
||||
break
|
||||
} else if err != nil {
|
||||
return verificationRequests, err
|
||||
}
|
||||
|
||||
if meta.Key != "" {
|
||||
verificationRequest.Key = meta.Key
|
||||
verificationRequest.ObjectID = meta.ID.String()
|
||||
verificationRequests = append(verificationRequests, verificationRequest)
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
return verificationRequests, nil
|
||||
}
|
||||
|
||||
func (mgr *manager) GetVerificationByToken(token string) (VerificationRequest, error) {
|
||||
var verification VerificationRequest
|
||||
result := mgr.db.Where("token = ?", token).First(&verification)
|
||||
|
||||
if result.Error != nil {
|
||||
log.Println(`Error getting verification token:`, result.Error)
|
||||
return verification, result.Error
|
||||
if IsSQL {
|
||||
result := mgr.sqlDB.Where("token = ?", token).First(&verification)
|
||||
|
||||
if result.Error != nil {
|
||||
log.Println(`error getting verification request:`, result.Error)
|
||||
return verification, result.Error
|
||||
}
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
query := fmt.Sprintf("FOR d in %s FILTER d.token == @token LIMIT 1 RETURN d", Collections.VerificationRequest)
|
||||
bindVars := map[string]interface{}{
|
||||
"token": token,
|
||||
}
|
||||
|
||||
cursor, err := mgr.arangodb.Query(nil, query, bindVars)
|
||||
if err != nil {
|
||||
return verification, err
|
||||
}
|
||||
defer cursor.Close()
|
||||
|
||||
for {
|
||||
_, err := cursor.ReadDocument(nil, &verification)
|
||||
|
||||
if driver.IsNoMoreDocuments(err) {
|
||||
break
|
||||
} else if err != nil {
|
||||
return verification, err
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
return verification, nil
|
||||
@@ -52,35 +134,60 @@ func (mgr *manager) GetVerificationByToken(token string) (VerificationRequest, e
|
||||
|
||||
func (mgr *manager) GetVerificationByEmail(email string) (VerificationRequest, error) {
|
||||
var verification VerificationRequest
|
||||
result := mgr.db.Where("email = ?", email).First(&verification)
|
||||
if IsSQL {
|
||||
result := mgr.sqlDB.Where("email = ?", email).First(&verification)
|
||||
|
||||
if result.Error != nil {
|
||||
log.Println(`Error getting verification token:`, result.Error)
|
||||
return verification, result.Error
|
||||
if result.Error != nil {
|
||||
log.Println(`error getting verification token:`, result.Error)
|
||||
return verification, result.Error
|
||||
}
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
query := fmt.Sprintf("FOR d in %s FILTER d.email == @email LIMIT 1 RETURN d", Collections.VerificationRequest)
|
||||
bindVars := map[string]interface{}{
|
||||
"email": email,
|
||||
}
|
||||
|
||||
cursor, err := mgr.arangodb.Query(nil, query, bindVars)
|
||||
if err != nil {
|
||||
return verification, err
|
||||
}
|
||||
defer cursor.Close()
|
||||
|
||||
for {
|
||||
_, err := cursor.ReadDocument(nil, &verification)
|
||||
|
||||
if driver.IsNoMoreDocuments(err) {
|
||||
break
|
||||
} else if err != nil {
|
||||
return verification, err
|
||||
}
|
||||
|
||||
}
|
||||
}
|
||||
|
||||
return verification, nil
|
||||
}
|
||||
|
||||
func (mgr *manager) DeleteToken(email string) error {
|
||||
var verification VerificationRequest
|
||||
result := mgr.db.Where("email = ?", email).Delete(&verification)
|
||||
func (mgr *manager) DeleteVerificationRequest(verificationRequest VerificationRequest) error {
|
||||
if IsSQL {
|
||||
result := mgr.sqlDB.Delete(&verificationRequest)
|
||||
|
||||
if result.Error != nil {
|
||||
log.Println(`Error deleting token:`, result.Error)
|
||||
return result.Error
|
||||
if result.Error != nil {
|
||||
log.Println(`error deleting verification request:`, result.Error)
|
||||
return result.Error
|
||||
}
|
||||
}
|
||||
|
||||
if IsArangoDB {
|
||||
collection, _ := mgr.arangodb.Collection(nil, Collections.VerificationRequest)
|
||||
_, err := collection.RemoveDocument(nil, verificationRequest.Key)
|
||||
if err != nil {
|
||||
log.Println(`error deleting verification request:`, err)
|
||||
return err
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
// GetUsers function to get all users
|
||||
func (mgr *manager) GetVerificationRequests() ([]VerificationRequest, error) {
|
||||
var verificationRequests []VerificationRequest
|
||||
result := mgr.db.Find(&verificationRequests)
|
||||
if result.Error != nil {
|
||||
log.Println(result.Error)
|
||||
return verificationRequests, result.Error
|
||||
}
|
||||
return verificationRequests, nil
|
||||
}
|
||||
|
Reference in New Issue
Block a user