mirror of
https://github.com/kevin-DL/services.git
synced 2026-01-14 20:14:47 +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
|
||||
}
|
||||
|
||||
|
||||
@@ -2,38 +2,21 @@ package handler_test
|
||||
|
||||
import (
|
||||
"context"
|
||||
"database/sql"
|
||||
"os"
|
||||
"testing"
|
||||
|
||||
"github.com/micro/micro/v3/service/auth"
|
||||
"github.com/micro/micro/v3/service/store"
|
||||
"github.com/micro/micro/v3/service/store/memory"
|
||||
"github.com/micro/services/invites/handler"
|
||||
pb "github.com/micro/services/invites/proto"
|
||||
"google.golang.org/protobuf/types/known/wrapperspb"
|
||||
|
||||
"github.com/google/uuid"
|
||||
"github.com/stretchr/testify/assert"
|
||||
)
|
||||
|
||||
func testHandler(t *testing.T) *handler.Invites {
|
||||
// connect to the database
|
||||
addr := os.Getenv("POSTGRES_URL")
|
||||
if len(addr) == 0 {
|
||||
addr = "postgresql://postgres@localhost:5432/postgres?sslmode=disable"
|
||||
}
|
||||
sqlDB, err := sql.Open("pgx", addr)
|
||||
if err != nil {
|
||||
t.Fatalf("Failed to open connection to DB %s", err)
|
||||
}
|
||||
|
||||
// clean any data from a previous run
|
||||
if _, err := sqlDB.Exec(`DROP TABLE IF EXISTS "micro_someID_invites" CASCADE`); err != nil {
|
||||
t.Fatalf("Error cleaning database: %v", err)
|
||||
}
|
||||
|
||||
h := &handler.Invites{}
|
||||
h.DBConn(sqlDB).Migrations(&handler.Invite{})
|
||||
return h
|
||||
store.DefaultStore = memory.NewStore()
|
||||
return &handler.Invites{}
|
||||
}
|
||||
|
||||
func TestCreate(t *testing.T) {
|
||||
@@ -112,8 +95,8 @@ func TestRead(t *testing.T) {
|
||||
|
||||
tt := []struct {
|
||||
Name string
|
||||
ID *wrapperspb.StringValue
|
||||
Code *wrapperspb.StringValue
|
||||
ID string
|
||||
Code string
|
||||
Error error
|
||||
Invite *pb.Invite
|
||||
}{
|
||||
@@ -123,22 +106,22 @@ func TestRead(t *testing.T) {
|
||||
},
|
||||
{
|
||||
Name: "NotFoundByID",
|
||||
ID: &wrapperspb.StringValue{Value: uuid.New().String()},
|
||||
ID: uuid.New().String(),
|
||||
Error: handler.ErrInviteNotFound,
|
||||
},
|
||||
{
|
||||
Name: "NotFoundByCode",
|
||||
Code: &wrapperspb.StringValue{Value: "12345678"},
|
||||
Code: "12345678",
|
||||
Error: handler.ErrInviteNotFound,
|
||||
},
|
||||
{
|
||||
Name: "ValidID",
|
||||
ID: &wrapperspb.StringValue{Value: cRsp.Invite.Id},
|
||||
ID: cRsp.Invite.Id,
|
||||
Invite: cRsp.Invite,
|
||||
},
|
||||
{
|
||||
Name: "ValidCode",
|
||||
Code: &wrapperspb.StringValue{Value: cRsp.Invite.Code},
|
||||
Code: cRsp.Invite.Code,
|
||||
Invite: cRsp.Invite,
|
||||
},
|
||||
}
|
||||
@@ -172,8 +155,8 @@ func TestList(t *testing.T) {
|
||||
|
||||
tt := []struct {
|
||||
Name string
|
||||
GroupID *wrapperspb.StringValue
|
||||
Email *wrapperspb.StringValue
|
||||
GroupID string
|
||||
Email string
|
||||
Error error
|
||||
Invite *pb.Invite
|
||||
}{
|
||||
@@ -183,26 +166,26 @@ func TestList(t *testing.T) {
|
||||
},
|
||||
{
|
||||
Name: "NoResultsForEmail",
|
||||
Email: &wrapperspb.StringValue{Value: "foo@bar.com"},
|
||||
Email: "foo@bar.com",
|
||||
},
|
||||
{
|
||||
Name: "NoResultsForGroupID",
|
||||
GroupID: &wrapperspb.StringValue{Value: uuid.New().String()},
|
||||
GroupID: uuid.New().String(),
|
||||
},
|
||||
{
|
||||
Name: "ValidGroupID",
|
||||
GroupID: &wrapperspb.StringValue{Value: cRsp.Invite.GroupId},
|
||||
GroupID: cRsp.Invite.GroupId,
|
||||
Invite: cRsp.Invite,
|
||||
},
|
||||
{
|
||||
Name: "ValidEmail",
|
||||
Email: &wrapperspb.StringValue{Value: cRsp.Invite.Email},
|
||||
Email: cRsp.Invite.Email,
|
||||
Invite: cRsp.Invite,
|
||||
},
|
||||
{
|
||||
Name: "EmailAndGroupID",
|
||||
Email: &wrapperspb.StringValue{Value: cRsp.Invite.Email},
|
||||
GroupID: &wrapperspb.StringValue{Value: uuid.New().String()},
|
||||
Email: cRsp.Invite.Email,
|
||||
GroupID: uuid.New().String(),
|
||||
},
|
||||
}
|
||||
|
||||
@@ -246,7 +229,7 @@ func TestDelete(t *testing.T) {
|
||||
err := h.Delete(microAccountCtx(), &pb.DeleteRequest{Id: cRsp.Invite.Id}, &pb.DeleteResponse{})
|
||||
assert.NoError(t, err)
|
||||
|
||||
err = h.Read(microAccountCtx(), &pb.ReadRequest{Id: &wrapperspb.StringValue{Value: cRsp.Invite.Id}}, &pb.ReadResponse{})
|
||||
err = h.Read(microAccountCtx(), &pb.ReadRequest{Id: cRsp.Invite.Id}, &pb.ReadResponse{})
|
||||
assert.Equal(t, handler.ErrInviteNotFound, err)
|
||||
})
|
||||
|
||||
|
||||
Reference in New Issue
Block a user