Skip to content

Commit

Permalink
fix: Using correct ID for user in ketchup store (#35)
Browse files Browse the repository at this point in the history
  • Loading branch information
ViBiOh authored Apr 28, 2020
1 parent 20fb8d8 commit 8e481cd
Show file tree
Hide file tree
Showing 11 changed files with 215 additions and 18 deletions.
27 changes: 27 additions & 0 deletions pkg/model/user.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,17 @@
package model

import (
"context"

authModel "github.com/ViBiOh/auth/v2/pkg/model"
)

type key int

const (
ctxUserKey key = iota
)

var (
// NoneUser is an undefined user
NoneUser = User{}
Expand All @@ -15,3 +23,22 @@ type User struct {
Email string `json:"email"`
Login authModel.User
}

// StoreUser stores given User in context
func StoreUser(ctx context.Context, user User) context.Context {
return context.WithValue(ctx, ctxUserKey, user)
}

// ReadUser retrieves user from context
func ReadUser(ctx context.Context) User {
rawUser := ctx.Value(ctxUserKey)
if rawUser == nil {
return NoneUser
}

if user, ok := rawUser.(User); ok {
return user
}

return NoneUser
}
48 changes: 48 additions & 0 deletions pkg/model/user_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,48 @@
package model

import (
"context"
"testing"
)

func TestReadUser(t *testing.T) {
type args struct {
ctx context.Context
}

var cases = []struct {
intention string
args args
want User
}{
{
"empty",
args{
ctx: context.Background(),
},
NoneUser,
},
{
"with User",
args{
ctx: StoreUser(context.Background(), User{ID: 8000, Email: "nobody@localhost"}),
},
User{ID: 8000, Email: "nobody@localhost"},
},
{
"not an User",
args{
ctx: context.WithValue(context.Background(), ctxUserKey, args{}),
},
NoneUser,
},
}

for _, tc := range cases {
t.Run(tc.intention, func(t *testing.T) {
if got := ReadUser(tc.args.ctx); got != tc.want {
t.Errorf("ReadUser() = %v, want %v", got, tc.want)
}
})
}
}
4 changes: 2 additions & 2 deletions pkg/renderer/ketchups.go
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ func (a app) ketchups() http.Handler {

func (a app) handleCreate(w http.ResponseWriter, r *http.Request) {
ketchup := model.Ketchup{
Version: r.FormValue("currentVersion"),
Version: r.FormValue("version"),
Repository: model.Repository{
Name: r.FormValue("repository"),
},
Expand Down Expand Up @@ -73,7 +73,7 @@ func (a app) handleUpdate(w http.ResponseWriter, r *http.Request) {
}

newKetchup := oldKetchup.(model.Ketchup)
newKetchup.Version = r.FormValue("currentVersion")
newKetchup.Version = r.FormValue("version")

if errs := a.ketchupApp.Check(r.Context(), oldKetchup, newKetchup); len(errs) > 0 {
a.handleCrudError(w, errs)
Expand Down
34 changes: 34 additions & 0 deletions pkg/service/ketchup/ketchup.go
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,11 @@ func (a app) Unmarshal(data []byte, contentType string) (interface{}, error) {
}

func (a app) List(ctx context.Context, page, pageSize uint, sortKey string, sortAsc bool, filters map[string][]string) ([]interface{}, uint, error) {
ctx, err := a.convertLoginToUser(ctx)
if err != nil {
return nil, 0, fmt.Errorf("unable to convert user: %s", err)
}

list, total, err := a.ketchupStore.List(ctx, page, pageSize, sortKey, sortAsc)
if err != nil {
return nil, 0, fmt.Errorf("unable to list: %s", err)
Expand All @@ -74,6 +79,11 @@ func (a app) List(ctx context.Context, page, pageSize uint, sortKey string, sort
}

func (a app) Get(ctx context.Context, ID uint64) (interface{}, error) {
ctx, err := a.convertLoginToUser(ctx)
if err != nil {
return nil, fmt.Errorf("unable to convert user: %s", err)
}

item, err := a.ketchupStore.GetByRepositoryID(ctx, ID)
if err != nil {
return nil, fmt.Errorf("unable to get: %s", err)
Expand All @@ -94,6 +104,11 @@ func (a app) Get(ctx context.Context, ID uint64) (interface{}, error) {
}

func (a app) Create(ctx context.Context, o interface{}) (output interface{}, err error) {
ctx, err = a.convertLoginToUser(ctx)
if err != nil {
return nil, fmt.Errorf("unable to convert user: %s", err)
}

output = model.NoneKetchup
item := o.(model.Ketchup)

Expand Down Expand Up @@ -124,6 +139,11 @@ func (a app) Create(ctx context.Context, o interface{}) (output interface{}, err
}

func (a app) Update(ctx context.Context, o interface{}) (interface{}, error) {
ctx, err := a.convertLoginToUser(ctx)
if err != nil {
return nil, fmt.Errorf("unable to convert user: %s", err)
}

item := o.(model.Ketchup)

if err := a.ketchupStore.Update(ctx, item); err != nil {
Expand All @@ -134,6 +154,11 @@ func (a app) Update(ctx context.Context, o interface{}) (interface{}, error) {
}

func (a app) Delete(ctx context.Context, o interface{}) error {
ctx, err := a.convertLoginToUser(ctx)
if err != nil {
return fmt.Errorf("unable to convert user: %s", err)
}

item := o.(model.Ketchup)

if err := a.ketchupStore.Delete(ctx, item); err != nil {
Expand Down Expand Up @@ -188,3 +213,12 @@ func (a app) Check(ctx context.Context, old, new interface{}) []crud.Error {

return errors
}

func (a app) convertLoginToUser(ctx context.Context) (context.Context, error) {
user, err := a.userService.GetFromContext(ctx)
if err != nil {
return ctx, err
}

return model.StoreUser(ctx, user.(model.User)), nil
}
15 changes: 15 additions & 0 deletions pkg/service/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,8 @@ type App interface {
Create(ctx context.Context, o interface{}) (interface{}, error)
Update(ctx context.Context, o interface{}) (interface{}, error)
Delete(ctx context.Context, o interface{}) error

GetFromContext(ctx context.Context) (interface{}, error)
}

type app struct {
Expand Down Expand Up @@ -95,6 +97,19 @@ func (a app) Get(ctx context.Context, ID uint64) (interface{}, error) {
return item, nil
}

func (a app) GetFromContext(ctx context.Context) (interface{}, error) {
item, err := a.userStore.GetByLoginID(ctx, authModel.ReadUser(ctx).ID)
if err != nil {
return nil, fmt.Errorf("unable to get: %w", err)
}

if item == model.NoneUser {
return nil, crud.ErrNotFound
}

return item, nil
}

func (a app) Create(ctx context.Context, o interface{}) (output interface{}, err error) {
output = model.NoneUser
item := o.(model.User)
Expand Down
11 changes: 5 additions & 6 deletions pkg/store/ketchup/ketchup.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@ import (
"fmt"
"regexp"

authModel "github.com/ViBiOh/auth/v2/pkg/model"
"github.com/ViBiOh/httputils/v3/pkg/db"
"github.com/ViBiOh/ketchup/pkg/model"
"github.com/ViBiOh/ketchup/pkg/store"
Expand Down Expand Up @@ -112,7 +111,7 @@ func (a app) List(ctx context.Context, page, pageSize uint, sortKey string, sort
ctx, cancel := context.WithTimeout(ctx, db.SQLTimeout)
defer cancel()

rows, err := a.db.QueryContext(ctx, fmt.Sprintf(listQuery, order), pageSize, offset, authModel.ReadUser(ctx).ID)
rows, err := a.db.QueryContext(ctx, fmt.Sprintf(listQuery, order), pageSize, offset, model.ReadUser(ctx).ID)
if err != nil {
return nil, 0, err
}
Expand Down Expand Up @@ -175,7 +174,7 @@ WHERE
`

func (a app) GetByRepositoryID(ctx context.Context, id uint64) (model.Ketchup, error) {
return scanItem(db.GetRow(ctx, a.db, getQuery, id, authModel.ReadUser(ctx).ID))
return scanItem(db.GetRow(ctx, a.db, getQuery, id, model.ReadUser(ctx).ID))
}

const insertQuery = `
Expand All @@ -193,7 +192,7 @@ INSERT INTO
`

func (a app) Create(ctx context.Context, o model.Ketchup) (uint64, error) {
return db.Create(ctx, a.db, insertQuery, o.Version, o.Repository.ID, authModel.ReadUser(ctx).ID)
return db.Create(ctx, a.db, insertQuery, o.Version, o.Repository.ID, model.ReadUser(ctx).ID)
}

const updateQuery = `
Expand All @@ -207,7 +206,7 @@ WHERE
`

func (a app) Update(ctx context.Context, o model.Ketchup) error {
return db.Exec(ctx, a.db, updateQuery, o.Repository.ID, authModel.ReadUser(ctx).ID, o.Version)
return db.Exec(ctx, a.db, updateQuery, o.Repository.ID, model.ReadUser(ctx).ID, o.Version)
}

const deleteQuery = `
Expand All @@ -219,5 +218,5 @@ WHERE
`

func (a app) Delete(ctx context.Context, o model.Ketchup) error {
return db.Exec(ctx, a.db, deleteQuery, o.Repository.ID, authModel.ReadUser(ctx).ID)
return db.Exec(ctx, a.db, deleteQuery, o.Repository.ID, model.ReadUser(ctx).ID)
}
11 changes: 5 additions & 6 deletions pkg/store/ketchup/ketchup_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,6 @@ import (
"time"

"github.com/DATA-DOG/go-sqlmock"
authModel "github.com/ViBiOh/auth/v2/pkg/model"
"github.com/ViBiOh/httputils/v3/pkg/db"
"github.com/ViBiOh/ketchup/pkg/model"
)
Expand Down Expand Up @@ -156,7 +155,7 @@ func TestList(t *testing.T) {
expectedQuery.WillDelayFor(db.SQLTimeout * 2)
}

got, gotCount, gotErr := New(mockDb).List(authModel.StoreUser(context.Background(), authModel.NewUser(3, "vibioh")), tc.args.page, tc.args.pageSize, tc.args.sortKey, tc.args.sortAsc)
got, gotCount, gotErr := New(mockDb).List(model.StoreUser(context.Background(), model.User{ID: 3}), tc.args.page, tc.args.pageSize, tc.args.sortKey, tc.args.sortAsc)
failed := false

if tc.wantErr == nil && gotErr != nil {
Expand Down Expand Up @@ -219,7 +218,7 @@ func TestGetByRepositoryID(t *testing.T) {

mock.ExpectQuery("SELECT version, repository_id, user_id FROM ketchup").WithArgs(1, 3).WillReturnRows(sqlmock.NewRows([]string{"email", "repository_id", "user_id"}).AddRow("0.9.0", 1, 3))

got, gotErr := New(mockDb).GetByRepositoryID(authModel.StoreUser(context.Background(), authModel.NewUser(3, "vibioh")), tc.args.id)
got, gotErr := New(mockDb).GetByRepositoryID(model.StoreUser(context.Background(), model.User{ID: 3}), tc.args.id)

failed := false

Expand Down Expand Up @@ -280,7 +279,7 @@ func TestCreate(t *testing.T) {
mock.ExpectQuery("INSERT INTO ketchup").WithArgs("0.9.0", 1, 3).WillReturnRows(sqlmock.NewRows([]string{"id"}).AddRow(1))
mock.ExpectCommit()

got, gotErr := New(mockDb).Create(authModel.StoreUser(context.Background(), authModel.NewUser(3, "vibioh")), tc.args.o)
got, gotErr := New(mockDb).Create(model.StoreUser(context.Background(), model.User{ID: 3}), tc.args.o)

failed := false

Expand Down Expand Up @@ -339,7 +338,7 @@ func TestUpdate(t *testing.T) {
mock.ExpectExec("UPDATE ketchup SET version").WithArgs(1, 3, "0.9.0").WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectCommit()

gotErr := New(mockDb).Update(authModel.StoreUser(context.Background(), authModel.NewUser(3, "vibioh")), tc.args.o)
gotErr := New(mockDb).Update(model.StoreUser(context.Background(), model.User{ID: 3}), tc.args.o)

failed := false

Expand Down Expand Up @@ -395,7 +394,7 @@ func TestDelete(t *testing.T) {
mock.ExpectExec("DELETE FROM ketchup").WithArgs(1, 3).WillReturnResult(sqlmock.NewResult(0, 1))
mock.ExpectCommit()

gotErr := New(mockDb).Delete(authModel.StoreUser(context.Background(), authModel.NewUser(3, "vibioh")), tc.args.o)
gotErr := New(mockDb).Delete(model.StoreUser(context.Background(), model.User{ID: 3}), tc.args.o)

failed := false

Expand Down
1 change: 1 addition & 0 deletions pkg/store/store.go
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ type UserStore interface {
List(ctx context.Context, page, pageSize uint, sortKey string, sortAsc bool) ([]model.User, uint, error)
Get(ctx context.Context, id uint64) (model.User, error)
GetByEmail(ctx context.Context, email string) (model.User, error)
GetByLoginID(ctx context.Context, loginID uint64) (model.User, error)
Create(ctx context.Context, o model.User) (uint64, error)
Update(ctx context.Context, o model.User) error
Delete(ctx context.Context, o model.User) error
Expand Down
16 changes: 16 additions & 0 deletions pkg/store/user/user.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ type App interface {
List(ctx context.Context, page, pageSize uint, sortKey string, sortAsc bool) ([]model.User, uint, error)
Get(ctx context.Context, id uint64) (model.User, error)
GetByEmail(ctx context.Context, email string) (model.User, error)
GetByLoginID(ctx context.Context, loginID uint64) (model.User, error)
Create(ctx context.Context, o model.User) (uint64, error)
Update(ctx context.Context, o model.User) error
Delete(ctx context.Context, o model.User) error
Expand Down Expand Up @@ -150,6 +151,21 @@ func (a app) GetByEmail(ctx context.Context, email string) (model.User, error) {
return scanItem(db.GetRow(ctx, a.db, getByEmailQuery, email))
}

const getByLoginIDQuery = `
SELECT
id,
email,
login_id
FROM
"user"
WHERE
login_id = $1
`

func (a app) GetByLoginID(ctx context.Context, loginID uint64) (model.User, error) {
return scanItem(db.GetRow(ctx, a.db, getByLoginIDQuery, loginID))
}

const insertQuery = `
INSERT INTO
"user"
Expand Down
Loading

0 comments on commit 8e481cd

Please sign in to comment.