mirror of
https://github.com/kevin-DL/services.git
synced 2026-01-17 13:24:56 +00:00
Make invites use store (#92)
This commit is contained in:
@@ -2,6 +2,8 @@ package handler
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"math/rand"
|
||||
"regexp"
|
||||
"strconv"
|
||||
@@ -11,9 +13,9 @@ import (
|
||||
"github.com/micro/micro/v3/service/auth"
|
||||
"github.com/micro/micro/v3/service/errors"
|
||||
"github.com/micro/micro/v3/service/logger"
|
||||
"github.com/micro/micro/v3/service/store"
|
||||
pb "github.com/micro/services/invites/proto"
|
||||
gorm2 "github.com/micro/services/pkg/gorm"
|
||||
"gorm.io/gorm"
|
||||
"github.com/micro/services/pkg/tenant"
|
||||
)
|
||||
|
||||
var (
|
||||
@@ -30,9 +32,9 @@ var (
|
||||
|
||||
type Invite struct {
|
||||
ID string
|
||||
Email string `gorm:"uniqueIndex:group_email"`
|
||||
GroupID string `gorm:"uniqueIndex:group_email"`
|
||||
Code string `gorm:"uniqueIndex"`
|
||||
Email string
|
||||
GroupID string
|
||||
Code string
|
||||
}
|
||||
|
||||
func (i *Invite) Serialize() *pb.Invite {
|
||||
@@ -44,10 +46,43 @@ func (i *Invite) Serialize() *pb.Invite {
|
||||
}
|
||||
}
|
||||
|
||||
type Invites struct {
|
||||
gorm2.Helper
|
||||
func (i *Invite) Key(ctx context.Context) string {
|
||||
key := fmt.Sprintf("invite:%s:%s", i.ID, i.Code)
|
||||
|
||||
t, ok := tenant.FromContext(ctx)
|
||||
if !ok {
|
||||
return key
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s/%s", t, key)
|
||||
}
|
||||
|
||||
func (i *Invite) GroupKey(ctx context.Context) string {
|
||||
key := fmt.Sprintf("group:%s:%s", i.GroupID, i.Email)
|
||||
|
||||
t, ok := tenant.FromContext(ctx)
|
||||
if !ok {
|
||||
return key
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%s/%s", t, key)
|
||||
}
|
||||
|
||||
func (i *Invite) Marshal() []byte {
|
||||
b, _ := json.Marshal(i)
|
||||
return b
|
||||
}
|
||||
|
||||
func (i *Invite) Unmarshal(b []byte) error {
|
||||
return json.Unmarshal(b, &i)
|
||||
}
|
||||
|
||||
type Invites struct{}
|
||||
|
||||
// schema
|
||||
// Read: id/code
|
||||
// List: group/email
|
||||
|
||||
// Create an invite
|
||||
func (i *Invites) Create(ctx context.Context, req *pb.CreateRequest, rsp *pb.CreateResponse) error {
|
||||
_, ok := auth.AccountFromContext(ctx)
|
||||
@@ -72,12 +107,22 @@ func (i *Invites) Create(ctx context.Context, req *pb.CreateRequest, rsp *pb.Cre
|
||||
GroupID: req.GroupId,
|
||||
Email: strings.ToLower(req.Email),
|
||||
}
|
||||
db, err := i.GetDBConn(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf("Error connecting to DB: %v", err)
|
||||
return errors.InternalServerError("DB_ERROR", "Error connecting to DB")
|
||||
|
||||
// id/val
|
||||
key := invite.Key(ctx)
|
||||
// get group key
|
||||
gkey := invite.GroupKey(ctx)
|
||||
|
||||
// TODO: Use the micro/micro/v3/service/sync interface to lock
|
||||
|
||||
// write the first record
|
||||
if err := store.Write(store.NewRecord(key, invite)); err != nil {
|
||||
logger.Errorf("Error writing to the store: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to the database")
|
||||
}
|
||||
if err := db.Create(invite).Error; err != nil && !strings.Contains(err.Error(), "group_email") {
|
||||
|
||||
// write the group record
|
||||
if err := store.Write(store.NewRecord(gkey, invite)); err != nil {
|
||||
logger.Errorf("Error writing to the store: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to the database")
|
||||
}
|
||||
@@ -94,29 +139,75 @@ func (i *Invites) Read(ctx context.Context, req *pb.ReadRequest, rsp *pb.ReadRes
|
||||
errors.Unauthorized("UNAUTHORIZED", "Unauthorized")
|
||||
}
|
||||
// validate the request
|
||||
var query Invite
|
||||
if req.Id != nil {
|
||||
query.ID = req.Id.Value
|
||||
} else if req.Code != nil {
|
||||
query.Code = req.Code.Value
|
||||
} else {
|
||||
if len(req.Id) == 0 && len(req.Code) == 0 {
|
||||
return ErrMissingIDAndCode
|
||||
}
|
||||
|
||||
db, err := i.GetDBConn(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf("Error connecting to DB: %v", err)
|
||||
return errors.InternalServerError("DB_ERROR", "Error connecting to DB")
|
||||
var recs []*store.Record
|
||||
var err error
|
||||
|
||||
// create a pseudo invite
|
||||
invite := &Invite{
|
||||
ID: req.Id,
|
||||
Code: req.Code,
|
||||
}
|
||||
// query the database
|
||||
var invite Invite
|
||||
if err := db.Where(&query).First(&invite).Error; err == gorm.ErrRecordNotFound {
|
||||
|
||||
if len(req.Id) > 0 && len(req.Code) > 0 {
|
||||
recs, err = store.Read(invite.Key(ctx), store.ReadLimit(1))
|
||||
} else if len(req.Id) > 0 {
|
||||
recs, err = store.Read(invite.Key(ctx), store.ReadLimit(1), store.ReadPrefix())
|
||||
} else if len(req.Code) > 0 {
|
||||
// create a code suffix key
|
||||
key := ":" + req.Code
|
||||
// read all the keys with the given code
|
||||
// TODO: potential race where if the code is not random
|
||||
// we read it for the wrong user e.g if two tenants generate the same code
|
||||
r, lerr := store.Read(key, store.ReadLimit(1), store.ReadSuffix())
|
||||
|
||||
// now scan for the prefix
|
||||
prefix := "invite:"
|
||||
|
||||
// additional prefix for the tenant
|
||||
if t, ok := tenant.FromContext(ctx); ok {
|
||||
prefix = t + "/" + prefix
|
||||
}
|
||||
|
||||
// scan for the key we're looking for
|
||||
for _, rec := range r {
|
||||
// skip the missing prefix
|
||||
if !strings.HasPrefix(rec.Key, prefix) {
|
||||
continue
|
||||
}
|
||||
|
||||
// skip missing suffix
|
||||
if !strings.HasSuffix(rec.Key, key) {
|
||||
continue
|
||||
}
|
||||
|
||||
// save the record
|
||||
recs = append(recs, rec)
|
||||
break
|
||||
}
|
||||
|
||||
// set the error
|
||||
// TODO: maybe just process this
|
||||
err = lerr
|
||||
}
|
||||
|
||||
// check if there are any records
|
||||
if err == store.ErrNotFound || len(recs) == 0 {
|
||||
return ErrInviteNotFound
|
||||
} else if err != nil {
|
||||
}
|
||||
|
||||
// check the error
|
||||
if err != nil {
|
||||
logger.Errorf("Error reading from the store: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to the database")
|
||||
}
|
||||
|
||||
// unmarshal the invite
|
||||
invite.Unmarshal(recs[0].Value)
|
||||
|
||||
// serialize the response
|
||||
rsp.Invite = invite.Serialize()
|
||||
return nil
|
||||
@@ -129,36 +220,77 @@ func (i *Invites) List(ctx context.Context, req *pb.ListRequest, rsp *pb.ListRes
|
||||
errors.Unauthorized("UNAUTHORIZED", "Unauthorized")
|
||||
}
|
||||
// validate the request
|
||||
if req.Email == nil && req.GroupId == nil {
|
||||
if len(req.Email) == 0 && len(req.GroupId) == 0 {
|
||||
return ErrMissingGroupIDAndEmail
|
||||
}
|
||||
|
||||
// construct the query
|
||||
var query Invite
|
||||
if req.GroupId != nil {
|
||||
query.GroupID = req.GroupId.Value
|
||||
}
|
||||
if req.Email != nil {
|
||||
query.Email = strings.ToLower(req.Email.Value)
|
||||
invite := &Invite{
|
||||
GroupID: req.GroupId,
|
||||
Email: req.Email,
|
||||
}
|
||||
|
||||
db, err := i.GetDBConn(ctx)
|
||||
if err != nil {
|
||||
logger.Errorf("Error connecting to DB: %v", err)
|
||||
return errors.InternalServerError("DB_ERROR", "Error connecting to DB")
|
||||
var recs []*store.Record
|
||||
var err error
|
||||
|
||||
if len(invite.GroupID) > 0 && len(invite.Email) > 0 {
|
||||
key := invite.GroupKey(ctx)
|
||||
recs, err = store.Read(key, store.ReadLimit(1))
|
||||
} else if len(invite.GroupID) > 0 {
|
||||
key := invite.GroupKey(ctx)
|
||||
recs, err = store.Read(key, store.ReadPrefix())
|
||||
} else if len(invite.Email) > 0 {
|
||||
// create a email suffix key
|
||||
key := ":" + invite.Email
|
||||
// read all the keys with the given code
|
||||
r, lerr := store.Read(key, store.ReadSuffix())
|
||||
|
||||
// now scan for the prefix
|
||||
prefix := "group:"
|
||||
|
||||
// additional prefix for the tenant
|
||||
if t, ok := tenant.FromContext(ctx); ok {
|
||||
prefix = t + "/" + prefix
|
||||
}
|
||||
|
||||
// scan for the key we're looking for
|
||||
for _, rec := range r {
|
||||
// skip the missing prefix
|
||||
if !strings.HasPrefix(rec.Key, prefix) {
|
||||
continue
|
||||
}
|
||||
|
||||
// skip missing suffix
|
||||
if !strings.HasSuffix(rec.Key, key) {
|
||||
continue
|
||||
}
|
||||
|
||||
// save the record
|
||||
recs = append(recs, rec)
|
||||
}
|
||||
|
||||
// set the error
|
||||
// TODO: maybe just process this
|
||||
err = lerr
|
||||
}
|
||||
// query the database
|
||||
var invites []Invite
|
||||
if err := db.Where(&query).Find(&invites).Error; err != nil {
|
||||
|
||||
// no records found
|
||||
if err == store.ErrNotFound {
|
||||
return nil
|
||||
}
|
||||
|
||||
// check the error
|
||||
if err != nil {
|
||||
logger.Errorf("Error reading from the store: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to the database")
|
||||
}
|
||||
|
||||
// serialize the response
|
||||
rsp.Invites = make([]*pb.Invite, len(invites))
|
||||
for i, inv := range invites {
|
||||
rsp.Invites[i] = inv.Serialize()
|
||||
// return response
|
||||
for _, rec := range recs {
|
||||
invite := new(Invite)
|
||||
invite.Unmarshal(rec.Value)
|
||||
rsp.Invites = append(rsp.Invites, invite.Serialize())
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
@@ -173,17 +305,30 @@ func (i *Invites) Delete(ctx context.Context, req *pb.DeleteRequest, rsp *pb.Del
|
||||
return ErrMissingID
|
||||
}
|
||||
|
||||
db, err := i.GetDBConn(ctx)
|
||||
if err != nil {
|
||||
invite := &Invite{ID: req.Id}
|
||||
key := invite.Key(ctx)
|
||||
|
||||
// check for the existing invite value
|
||||
recs, err := store.Read(key, store.ReadLimit(1), store.ReadPrefix())
|
||||
if err == store.ErrNotFound || len(recs) == 0 {
|
||||
return nil
|
||||
} else if err != nil {
|
||||
logger.Errorf("Error connecting to DB: %v", err)
|
||||
return errors.InternalServerError("DB_ERROR", "Error connecting to DB")
|
||||
}
|
||||
// delete from the database
|
||||
if err := db.Where(&Invite{ID: req.Id}).Delete(&Invite{}).Error; err != nil {
|
||||
logger.Errorf("Error deleting from the store: %v", err)
|
||||
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to the database")
|
||||
|
||||
// unmarshal the existing invite
|
||||
invite.Unmarshal(recs[0].Value)
|
||||
if invite.ID != req.Id {
|
||||
return nil
|
||||
}
|
||||
|
||||
// delete the record by id
|
||||
store.Delete(invite.Key(ctx))
|
||||
|
||||
// delete the record by group id
|
||||
store.Delete(invite.GroupKey(ctx))
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user