Skip to content

Commit

Permalink
Fix middleware. Code refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Zaptoss committed May 23, 2024
1 parent f854573 commit 2feff0a
Show file tree
Hide file tree
Showing 9 changed files with 28 additions and 45 deletions.
1 change: 0 additions & 1 deletion internal/assets/migrations/001_initial.sql
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,6 @@ CREATE TABLE IF NOT EXISTS balances
created_at integer NOT NULL default EXTRACT('EPOCH' FROM NOW()),
updated_at integer NOT NULL default EXTRACT('EPOCH' FROM NOW()),
referred_by text UNIQUE,
is_withdrawal_allowed boolean NOT NULL default false
);

CREATE INDEX IF NOT EXISTS balances_page_index ON balances (amount, updated_at) WHERE referred_by IS NOT NULL;
Expand Down
2 changes: 1 addition & 1 deletion internal/config/verifier.go
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ import (
"gitlab.com/distributed_lab/kit/kv"
)

const proofEventIDValue = ""
const proofEventIDValue = "TODO"

func (c *config) Verifier() *zk.Verifier {
return c.verifier.Do(func() interface{} {
Expand Down
14 changes: 6 additions & 8 deletions internal/data/balances.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,20 +7,18 @@ import (
)

type Balance struct {
Nullifier string `db:"nullifier"`
Amount int64 `db:"amount"`
CreatedAt int32 `db:"created_at"`
UpdatedAt int32 `db:"updated_at"`
ReferredBy sql.NullString `db:"referred_by"`
Rank *int `db:"rank"`
IsWithdrawalAllowed bool `db:"is_withdrawal_allowed"`
Nullifier string `db:"nullifier"`
Amount int64 `db:"amount"`
CreatedAt int32 `db:"created_at"`
UpdatedAt int32 `db:"updated_at"`
ReferredBy sql.NullString `db:"referred_by"`
Rank *int `db:"rank"`
}

type BalancesQ interface {
New() BalancesQ
Insert(Balance) error
UpdateAmountBy(points int64) error
SetIsWithdrawalAllowed(isWithdrawalAllowed bool) error
SetReferredBy(referralCode string) error

Page(*pgdb.OffsetPageParams) BalancesQ
Expand Down
11 changes: 0 additions & 11 deletions internal/data/pg/balances.go
Original file line number Diff line number Diff line change
Expand Up @@ -54,17 +54,6 @@ func (q *balances) UpdateAmountBy(points int64) error {
return nil
}

func (q *balances) SetIsWithdrawalAllowed(isWithdrawalAllowed bool) error {
stmt := q.updater.
Set("is_withdrawal_allowed", isWithdrawalAllowed)

if err := q.db.Exec(stmt); err != nil {
return fmt.Errorf("set isWithdrawalAllowed: %w", err)
}

return nil
}

func (q *balances) SetReferredBy(referralCode string) error {
stmt := q.updater.
Set("referred_by", referralCode)
Expand Down
2 changes: 0 additions & 2 deletions internal/service/handlers/get_balance.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,8 +72,6 @@ func newBalanceModel(balance data.Balance) resources.Balance {

func newBalanceResponse(balance data.Balance, referrals []data.Referral) resources.BalanceResponse {
resp := resources.BalanceResponse{Data: newBalanceModel(balance)}
resp.Data.Attributes.IsWithdrawalAllowed = &balance.IsWithdrawalAllowed

if len(referrals) == 0 {
return resp
}
Expand Down
29 changes: 15 additions & 14 deletions internal/service/handlers/middleware.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,28 +5,29 @@ import (
"net/http"

"github.com/rarimo/decentralized-auth-svc/pkg/auth"
"github.com/rarimo/decentralized-auth-svc/resources"
"github.com/rarimo/rarime-points-svc/internal/data/pg"
"gitlab.com/distributed_lab/ape"
"gitlab.com/distributed_lab/ape/problems"
"gitlab.com/distributed_lab/kit/pgdb"
"gitlab.com/distributed_lab/logan/v3"
)

func AuthMiddleware(auth *auth.Client, log *logan.Entry) func(http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// claims, err := auth.ValidateJWT(r)
// if err != nil {
// log.WithError(err).Info("Got invalid auth or validation error")
// ape.RenderErr(w, problems.Unauthorized())
// return
// }

// if len(claims) == 0 {
// ape.RenderErr(w, problems.Unauthorized())
// return
// }

ctx := CtxUserClaims([]resources.Claim{{Nullifier: r.Header.Get("nullifier")}})(r.Context())
claims, err := auth.ValidateJWT(r)
if err != nil {
log.WithError(err).Info("Got invalid auth or validation error")
ape.RenderErr(w, problems.Unauthorized())
return
}

if len(claims) == 0 {
ape.RenderErr(w, problems.Unauthorized())
return
}

ctx := CtxUserClaims(claims)(r.Context())
next.ServeHTTP(w, r.WithContext(ctx))
})
}
Expand Down
8 changes: 4 additions & 4 deletions internal/service/handlers/verify_passport.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"net/http"

"github.com/ethereum/go-ethereum/common/hexutil"
validation "github.com/go-ozzo/ozzo-validation/v4"
zkptypes "github.com/iden3/go-rapidsnark/types"
"github.com/rarimo/decentralized-auth-svc/pkg/auth"
"github.com/rarimo/rarime-points-svc/internal/data"
Expand Down Expand Up @@ -47,14 +48,14 @@ func VerifyPassport(w http.ResponseWriter, r *http.Request) {

if !balance.ReferredBy.Valid {
Log(r).Debug("Balance inactive")
ape.RenderErr(w, problems.BadRequest(errors.New("Balance inactive"))...)
ape.RenderErr(w, problems.BadRequest(validation.Errors{"referred_by": errors.New("balance inactive")})...)
return
}

evType := EventTypes(r).Get(evtypes.TypePassportScan, evtypes.FilterInactive)
if evType == nil {
Log(r).Debug("Passport scan event absent, disabled, hasn't start yet or expired")
w.WriteHeader(http.StatusNoContent)
ape.RenderErr(w, problems.BadRequest(validation.Errors{"passport_scan": errors.New("event disabled or absent")})...)
return
}

Expand Down Expand Up @@ -87,8 +88,7 @@ func VerifyPassport(w http.ResponseWriter, r *http.Request) {
}

_, err = EventsQ(r).
FilterByNullifier(nullifier).
FilterByType(evtypes.TypePassportScan).
FilterByID(event.ID).
Update(data.EventFulfilled, nil, nil)
if err != nil {
Log(r).WithError(err).Error("Failed to update passport scan event")
Expand Down
2 changes: 0 additions & 2 deletions internal/service/handlers/withdraw.go
Original file line number Diff line number Diff line change
Expand Up @@ -122,8 +122,6 @@ func isEligibleToWithdraw(balance *data.Balance, amount int64) error {
switch {
case !balance.ReferredBy.Valid:
return mapValidationErr("is_disabled", "user must be referred to withdraw")
case !balance.IsWithdrawalAllowed:
return mapValidationErr("is_withdrawal_allowed", "withdrawal ability was disabled for this user")
case balance.Amount < amount:
return mapValidationErr("data/attributes/amount", "insufficient balance: %d", balance.Amount)
}
Expand Down
4 changes: 2 additions & 2 deletions internal/service/requests/verify_passport.go
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@ import (
"github.com/rarimo/rarime-points-svc/resources"
)

var NullifierRegexp = regexp.MustCompile("^0x[0-9a-fA-F]{64}$")
var nullifierRegexp = regexp.MustCompile("^0x[0-9a-fA-F]{64}$")

func NewVerifyPassport(r *http.Request) (req resources.VerifyPassportRequest, err error) {
if err = json.NewDecoder(r.Body).Decode(&req); err != nil {
Expand All @@ -25,7 +25,7 @@ func NewVerifyPassport(r *http.Request) (req resources.VerifyPassportRequest, er
"data/id": validation.Validate(req.Data.ID,
validation.Required,
validation.In(strings.ToLower(chi.URLParam(r, "nullifier"))),
validation.Match(NullifierRegexp)),
validation.Match(nullifierRegexp)),
"data/type": validation.Validate(req.Data.Type,
validation.Required,
validation.In(resources.VERIFY_PASSPORT)),
Expand Down

0 comments on commit 2feff0a

Please sign in to comment.