lockdown invites (#80)

This commit is contained in:
Dominic Wong
2021-03-25 22:22:46 +00:00
committed by GitHub
parent 88085c7044
commit 81252c1611
3 changed files with 76 additions and 35 deletions

View File

@@ -8,9 +8,11 @@ import (
"strings" "strings"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/micro/micro/v3/service/auth"
"github.com/micro/micro/v3/service/errors" "github.com/micro/micro/v3/service/errors"
"github.com/micro/micro/v3/service/logger" "github.com/micro/micro/v3/service/logger"
pb "github.com/micro/services/invites/proto" pb "github.com/micro/services/invites/proto"
gorm2 "github.com/micro/services/pkg/gorm"
"gorm.io/gorm" "gorm.io/gorm"
) )
@@ -43,11 +45,15 @@ func (i *Invite) Serialize() *pb.Invite {
} }
type Invites struct { type Invites struct {
DB *gorm.DB gorm2.Helper
} }
// Create an invite // Create an invite
func (i *Invites) Create(ctx context.Context, req *pb.CreateRequest, rsp *pb.CreateResponse) error { func (i *Invites) Create(ctx context.Context, req *pb.CreateRequest, rsp *pb.CreateResponse) error {
_, ok := auth.AccountFromContext(ctx)
if !ok {
errors.Unauthorized("UNAUTHORIZED", "Unauthorized")
}
// validate the request // validate the request
if len(req.GroupId) == 0 { if len(req.GroupId) == 0 {
return ErrMissingGroupID return ErrMissingGroupID
@@ -66,8 +72,12 @@ func (i *Invites) Create(ctx context.Context, req *pb.CreateRequest, rsp *pb.Cre
GroupID: req.GroupId, GroupID: req.GroupId,
Email: strings.ToLower(req.Email), Email: strings.ToLower(req.Email),
} }
if err := i.DB.Create(invite).Error; err != nil && strings.Contains(err.Error(), "group_email") { db, err := i.GetDBConn(ctx)
} else if err != nil { if err != nil {
logger.Errorf("Error connecting to DB: %v", err)
return errors.InternalServerError("DB_ERROR", "Error connecting to DB")
}
if err := db.Create(invite).Error; err != nil && !strings.Contains(err.Error(), "group_email") {
logger.Errorf("Error writing to the store: %v", err) logger.Errorf("Error writing to the store: %v", err)
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to the database") return errors.InternalServerError("DATABASE_ERROR", "Error connecting to the database")
} }
@@ -79,6 +89,10 @@ func (i *Invites) Create(ctx context.Context, req *pb.CreateRequest, rsp *pb.Cre
// Read an invite using ID or code // Read an invite using ID or code
func (i *Invites) Read(ctx context.Context, req *pb.ReadRequest, rsp *pb.ReadResponse) error { func (i *Invites) Read(ctx context.Context, req *pb.ReadRequest, rsp *pb.ReadResponse) error {
_, ok := auth.AccountFromContext(ctx)
if !ok {
errors.Unauthorized("UNAUTHORIZED", "Unauthorized")
}
// validate the request // validate the request
var query Invite var query Invite
if req.Id != nil { if req.Id != nil {
@@ -89,9 +103,14 @@ func (i *Invites) Read(ctx context.Context, req *pb.ReadRequest, rsp *pb.ReadRes
return ErrMissingIDAndCode 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")
}
// query the database // query the database
var invite Invite var invite Invite
if err := i.DB.Where(&query).First(&invite).Error; err == gorm.ErrRecordNotFound { if err := db.Where(&query).First(&invite).Error; err == gorm.ErrRecordNotFound {
return ErrInviteNotFound return ErrInviteNotFound
} else if err != nil { } else if err != nil {
logger.Errorf("Error reading from the store: %v", err) logger.Errorf("Error reading from the store: %v", err)
@@ -105,6 +124,10 @@ func (i *Invites) Read(ctx context.Context, req *pb.ReadRequest, rsp *pb.ReadRes
// List invited for a group or specific email // List invited for a group or specific email
func (i *Invites) List(ctx context.Context, req *pb.ListRequest, rsp *pb.ListResponse) error { func (i *Invites) List(ctx context.Context, req *pb.ListRequest, rsp *pb.ListResponse) error {
_, ok := auth.AccountFromContext(ctx)
if !ok {
errors.Unauthorized("UNAUTHORIZED", "Unauthorized")
}
// validate the request // validate the request
if req.Email == nil && req.GroupId == nil { if req.Email == nil && req.GroupId == nil {
return ErrMissingGroupIDAndEmail return ErrMissingGroupIDAndEmail
@@ -119,9 +142,14 @@ func (i *Invites) List(ctx context.Context, req *pb.ListRequest, rsp *pb.ListRes
query.Email = strings.ToLower(req.Email.Value) query.Email = strings.ToLower(req.Email.Value)
} }
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")
}
// query the database // query the database
var invites []Invite var invites []Invite
if err := i.DB.Where(&query).Find(&invites).Error; err != nil { if err := db.Where(&query).Find(&invites).Error; err != nil {
logger.Errorf("Error reading from the store: %v", err) logger.Errorf("Error reading from the store: %v", err)
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to the database") return errors.InternalServerError("DATABASE_ERROR", "Error connecting to the database")
} }
@@ -136,13 +164,22 @@ func (i *Invites) List(ctx context.Context, req *pb.ListRequest, rsp *pb.ListRes
// Delete an invite // Delete an invite
func (i *Invites) Delete(ctx context.Context, req *pb.DeleteRequest, rsp *pb.DeleteResponse) error { func (i *Invites) Delete(ctx context.Context, req *pb.DeleteRequest, rsp *pb.DeleteResponse) error {
_, ok := auth.AccountFromContext(ctx)
if !ok {
errors.Unauthorized("UNAUTHORIZED", "Unauthorized")
}
// validate the request // validate the request
if len(req.Id) == 0 { if len(req.Id) == 0 {
return ErrMissingID return ErrMissingID
} }
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")
}
// delete from the database // delete from the database
if err := i.DB.Where(&Invite{ID: req.Id}).Delete(&Invite{}).Error; err != nil { if err := db.Where(&Invite{ID: req.Id}).Delete(&Invite{}).Error; err != nil {
logger.Errorf("Error deleting from the store: %v", err) logger.Errorf("Error deleting from the store: %v", err)
return errors.InternalServerError("DATABASE_ERROR", "Error connecting to the database") return errors.InternalServerError("DATABASE_ERROR", "Error connecting to the database")
} }

View File

@@ -2,17 +2,17 @@ package handler_test
import ( import (
"context" "context"
"database/sql"
"os" "os"
"testing" "testing"
"github.com/micro/micro/v3/service/auth"
"github.com/micro/services/invites/handler" "github.com/micro/services/invites/handler"
pb "github.com/micro/services/invites/proto" pb "github.com/micro/services/invites/proto"
"google.golang.org/protobuf/types/known/wrapperspb" "google.golang.org/protobuf/types/known/wrapperspb"
"github.com/google/uuid" "github.com/google/uuid"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"gorm.io/driver/postgres"
"gorm.io/gorm"
) )
func testHandler(t *testing.T) *handler.Invites { func testHandler(t *testing.T) *handler.Invites {
@@ -21,22 +21,19 @@ func testHandler(t *testing.T) *handler.Invites {
if len(addr) == 0 { if len(addr) == 0 {
addr = "postgresql://postgres@localhost:5432/postgres?sslmode=disable" addr = "postgresql://postgres@localhost:5432/postgres?sslmode=disable"
} }
db, err := gorm.Open(postgres.Open(addr), &gorm.Config{}) sqlDB, err := sql.Open("pgx", addr)
if err != nil { if err != nil {
t.Fatalf("Error connecting to database: %v", err) t.Fatalf("Failed to open connection to DB %s", err)
} }
// clean any data from a previous run // clean any data from a previous run
if err := db.Exec("DROP TABLE IF EXISTS invites CASCADE").Error; err != nil { if _, err := sqlDB.Exec("DROP TABLE IF EXISTS micro_invites CASCADE"); err != nil {
t.Fatalf("Error cleaning database: %v", err) t.Fatalf("Error cleaning database: %v", err)
} }
// migrate the database h := &handler.Invites{}
if err := db.AutoMigrate(&handler.Invite{}); err != nil { h.DBConn(sqlDB).Migrations(&handler.Invite{})
t.Fatalf("Error migrating database: %v", err) return h
}
return &handler.Invites{DB: db}
} }
func TestCreate(t *testing.T) { func TestCreate(t *testing.T) {
@@ -78,7 +75,7 @@ func TestCreate(t *testing.T) {
for _, tc := range tt { for _, tc := range tt {
t.Run(tc.Name, func(t *testing.T) { t.Run(tc.Name, func(t *testing.T) {
var rsp pb.CreateResponse var rsp pb.CreateResponse
err := h.Create(context.TODO(), &pb.CreateRequest{ err := h.Create(microAccountCtx(), &pb.CreateRequest{
GroupId: tc.GroupID, Email: tc.Email, GroupId: tc.GroupID, Email: tc.Email,
}, &rsp) }, &rsp)
assert.Equal(t, tc.Error, err) assert.Equal(t, tc.Error, err)
@@ -106,7 +103,7 @@ func TestRead(t *testing.T) {
// seed some data // seed some data
var cRsp pb.CreateResponse var cRsp pb.CreateResponse
err := h.Create(context.TODO(), &pb.CreateRequest{Email: "john@doe.com", GroupId: uuid.New().String()}, &cRsp) err := h.Create(microAccountCtx(), &pb.CreateRequest{Email: "john@doe.com", GroupId: uuid.New().String()}, &cRsp)
assert.NoError(t, err) assert.NoError(t, err)
if cRsp.Invite == nil { if cRsp.Invite == nil {
t.Fatal("No invite returned on create") t.Fatal("No invite returned on create")
@@ -149,7 +146,7 @@ func TestRead(t *testing.T) {
for _, tc := range tt { for _, tc := range tt {
t.Run(tc.Name, func(t *testing.T) { t.Run(tc.Name, func(t *testing.T) {
var rsp pb.ReadResponse var rsp pb.ReadResponse
err := h.Read(context.TODO(), &pb.ReadRequest{Id: tc.ID, Code: tc.Code}, &rsp) err := h.Read(microAccountCtx(), &pb.ReadRequest{Id: tc.ID, Code: tc.Code}, &rsp)
assert.Equal(t, tc.Error, err) assert.Equal(t, tc.Error, err)
if tc.Invite == nil { if tc.Invite == nil {
@@ -166,7 +163,7 @@ func TestList(t *testing.T) {
// seed some data // seed some data
var cRsp pb.CreateResponse var cRsp pb.CreateResponse
err := h.Create(context.TODO(), &pb.CreateRequest{Email: "john@doe.com", GroupId: uuid.New().String()}, &cRsp) err := h.Create(microAccountCtx(), &pb.CreateRequest{Email: "john@doe.com", GroupId: uuid.New().String()}, &cRsp)
assert.NoError(t, err) assert.NoError(t, err)
if cRsp.Invite == nil { if cRsp.Invite == nil {
t.Fatal("No invite returned on create") t.Fatal("No invite returned on create")
@@ -212,7 +209,7 @@ func TestList(t *testing.T) {
for _, tc := range tt { for _, tc := range tt {
t.Run(tc.Name, func(t *testing.T) { t.Run(tc.Name, func(t *testing.T) {
var rsp pb.ListResponse var rsp pb.ListResponse
err := h.List(context.TODO(), &pb.ListRequest{Email: tc.Email, GroupId: tc.GroupID}, &rsp) err := h.List(microAccountCtx(), &pb.ListRequest{Email: tc.Email, GroupId: tc.GroupID}, &rsp)
assert.Equal(t, tc.Error, err) assert.Equal(t, tc.Error, err)
if tc.Invite == nil { if tc.Invite == nil {
@@ -232,13 +229,13 @@ func TestDelete(t *testing.T) {
h := testHandler(t) h := testHandler(t)
t.Run("MissingID", func(t *testing.T) { t.Run("MissingID", func(t *testing.T) {
err := h.Delete(context.TODO(), &pb.DeleteRequest{}, &pb.DeleteResponse{}) err := h.Delete(microAccountCtx(), &pb.DeleteRequest{}, &pb.DeleteResponse{})
assert.Equal(t, handler.ErrMissingID, err) assert.Equal(t, handler.ErrMissingID, err)
}) })
// seed some data // seed some data
var cRsp pb.CreateResponse var cRsp pb.CreateResponse
err := h.Create(context.TODO(), &pb.CreateRequest{Email: "john@doe.com", GroupId: uuid.New().String()}, &cRsp) err := h.Create(microAccountCtx(), &pb.CreateRequest{Email: "john@doe.com", GroupId: uuid.New().String()}, &cRsp)
assert.NoError(t, err) assert.NoError(t, err)
if cRsp.Invite == nil { if cRsp.Invite == nil {
t.Fatal("No invite returned on create") t.Fatal("No invite returned on create")
@@ -246,15 +243,15 @@ func TestDelete(t *testing.T) {
} }
t.Run("Valid", func(t *testing.T) { t.Run("Valid", func(t *testing.T) {
err := h.Delete(context.TODO(), &pb.DeleteRequest{Id: cRsp.Invite.Id}, &pb.DeleteResponse{}) err := h.Delete(microAccountCtx(), &pb.DeleteRequest{Id: cRsp.Invite.Id}, &pb.DeleteResponse{})
assert.NoError(t, err) assert.NoError(t, err)
err = h.Read(context.TODO(), &pb.ReadRequest{Id: &wrapperspb.StringValue{Value: cRsp.Invite.Id}}, &pb.ReadResponse{}) err = h.Read(microAccountCtx(), &pb.ReadRequest{Id: &wrapperspb.StringValue{Value: cRsp.Invite.Id}}, &pb.ReadResponse{})
assert.Equal(t, handler.ErrInviteNotFound, err) assert.Equal(t, handler.ErrInviteNotFound, err)
}) })
t.Run("Repeat", func(t *testing.T) { t.Run("Repeat", func(t *testing.T) {
err := h.Delete(context.TODO(), &pb.DeleteRequest{Id: cRsp.Invite.Id}, &pb.DeleteResponse{}) err := h.Delete(microAccountCtx(), &pb.DeleteRequest{Id: cRsp.Invite.Id}, &pb.DeleteResponse{})
assert.NoError(t, err) assert.NoError(t, err)
}) })
} }
@@ -269,3 +266,9 @@ func assertInvitesMatch(t *testing.T, exp, act *pb.Invite) {
assert.Equal(t, exp.Email, act.Email) assert.Equal(t, exp.Email, act.Email)
assert.Equal(t, exp.GroupId, act.GroupId) assert.Equal(t, exp.GroupId, act.GroupId)
} }
func microAccountCtx() context.Context {
return auth.ContextWithAccount(context.TODO(), &auth.Account{
Issuer: "micro",
})
}

View File

@@ -1,14 +1,16 @@
package main package main
import ( import (
"database/sql"
"github.com/micro/services/invites/handler" "github.com/micro/services/invites/handler"
pb "github.com/micro/services/invites/proto" pb "github.com/micro/services/invites/proto"
"github.com/micro/micro/v3/service" "github.com/micro/micro/v3/service"
"github.com/micro/micro/v3/service/config" "github.com/micro/micro/v3/service/config"
"github.com/micro/micro/v3/service/logger" "github.com/micro/micro/v3/service/logger"
"gorm.io/driver/postgres"
"gorm.io/gorm" _ "github.com/jackc/pgx/v4/stdlib"
) )
var dbAddress = "postgresql://postgres:postgres@localhost:5432/invites?sslmode=disable" var dbAddress = "postgresql://postgres:postgres@localhost:5432/invites?sslmode=disable"
@@ -26,16 +28,15 @@ func main() {
logger.Fatalf("Error loading config: %v", err) logger.Fatalf("Error loading config: %v", err)
} }
addr := cfg.String(dbAddress) addr := cfg.String(dbAddress)
db, err := gorm.Open(postgres.Open(addr), &gorm.Config{}) sqlDB, err := sql.Open("pgx", addr)
if err != nil { if err != nil {
logger.Fatalf("Error connecting to database: %v", err) logger.Fatalf("Failed to open connection to DB %s", err)
}
if err := db.AutoMigrate(&handler.Invite{}); err != nil {
logger.Fatalf("Error migrating database: %v", err)
} }
h := &handler.Invites{}
h.DBConn(sqlDB).Migrations(&handler.Invite{})
// Register handler // Register handler
pb.RegisterInvitesHandler(srv.Server(), &handler.Invites{DB: db}) pb.RegisterInvitesHandler(srv.Server(), h)
// Run service // Run service
if err := srv.Run(); err != nil { if err := srv.Run(); err != nil {