Skip to content

Commit

Permalink
(BIDS-3049) wip
Browse files Browse the repository at this point in the history
  • Loading branch information
guybrush committed Jun 5, 2024
1 parent 524a00e commit 1c6e70a
Show file tree
Hide file tree
Showing 7 changed files with 81 additions and 5 deletions.
10 changes: 9 additions & 1 deletion cmd/explorer/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -371,11 +371,19 @@ func main() {
if err != nil {
logrus.WithError(err).Error("error decoding csrf auth key falling back to empty csrf key")
}

sameSite := csrf.SameSiteStrictMode
if utils.Config.Frontend.SessionSameSiteNone {
sameSite = csrf.SameSiteNoneMode
}

csrfHandler := csrf.Protect(
csrfBytes,
csrf.FieldName("CsrfField"),
csrf.Secure(!cfg.Frontend.CsrfInsecure),
csrf.Path("/"),
csrf.Domain(cfg.Frontend.SessionCookieDomain),
csrf.SameSite(sameSite),
)

router.HandleFunc("/", handlers.Index).Methods("GET")
Expand Down Expand Up @@ -585,7 +593,7 @@ func main() {
}

authRouter.Use(handlers.UserAuthMiddleware)
authRouter.Use(csrfHandler)
// authRouter.Use(csrfHandler)

if utils.Config.Frontend.Debug {
// serve files from local directory when debugging, instead of from go embed file
Expand Down
7 changes: 7 additions & 0 deletions db/stripe.go
Original file line number Diff line number Diff line change
Expand Up @@ -110,6 +110,13 @@ func StripeUpdateSubscriptionStatus(tx *sql.Tx, id string, status bool, payload
return err
}

// StripeGetUserAPISubscriptions returns a users current subscriptions
func StripeGetUserSubscriptions(id uint64, purchaseGroup string) ([]types.UserSubscription, error) {
userSubs := []types.UserSubscription{}
err := FrontendWriterDB.Select(&userSubs, "SELECT users.id, users.email, users.stripe_customer_id, us.subscription_id, us.price_id, us.active, users.api_key FROM users INNER JOIN (SELECT subscription_id, customer_id, price_id, active FROM users_stripe_subscriptions WHERE purchase_group = $2 and (payload->'ended_at')::text = 'null') as us ON users.stripe_customer_id = us.customer_id WHERE users.id = $1 ORDER BY active desc", id, purchaseGroup)
return userSubs, err
}

// StripeGetUserAPISubscription returns a users current subscription
func StripeGetUserSubscription(id uint64, purchaseGroup string) (types.UserSubscription, error) {
userSub := types.UserSubscription{}
Expand Down
2 changes: 1 addition & 1 deletion go.mod
Original file line number Diff line number Diff line change
Expand Up @@ -265,7 +265,7 @@ require (
github.com/tklauser/go-sysconf v0.3.12 // indirect
github.com/tklauser/numcpus v0.6.1 // indirect
go.opencensus.io v0.24.0 // indirect
golang.org/x/net v0.18.0 // indirect
golang.org/x/net v0.18.0
golang.org/x/oauth2 v0.7.0 // indirect
golang.org/x/sys v0.16.0 // indirect
golang.org/x/tools v0.15.0 // indirect
Expand Down
6 changes: 6 additions & 0 deletions handlers/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -2921,6 +2921,9 @@ func getTokenByCode(w http.ResponseWriter, r *http.Request) {
pkg.Package = "standard"
}

// BIDS-3049 mobile app uses v1 package ids only
pkg.Package = utils.MapProductV2ToV1(pkg.Package)

var theme string = ""
if pkg.Store == "ethpool" {
theme = "ethpool"
Expand Down Expand Up @@ -2975,6 +2978,9 @@ func getTokenByRefresh(w http.ResponseWriter, r *http.Request) {
pkg.Package = "standard"
}

// BIDS-3049 mobile app uses v1 package ids only
pkg.Package = utils.MapProductV2ToV1(pkg.Package)

var theme string = ""
if pkg.Store == "ethpool" {
theme = "ethpool"
Expand Down
51 changes: 48 additions & 3 deletions handlers/stripe.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import (
"net/http"
"time"

"github.com/sirupsen/logrus"
"github.com/stripe/stripe-go/v72"
portalsession "github.com/stripe/stripe-go/v72/billingportal/session"
"github.com/stripe/stripe-go/v72/checkout/session"
Expand All @@ -26,7 +27,8 @@ func StripeCreateCheckoutSession(w http.ResponseWriter, r *http.Request) {

// get the product that the user wants to subscribe to
var req struct {
Price string `json:"priceId"`
Price string `json:"priceId"`
AddonQuantity int64 `json:"addonQuantity"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
Expand All @@ -37,8 +39,12 @@ func StripeCreateCheckoutSession(w http.ResponseWriter, r *http.Request) {

purchaseGroup := utils.GetPurchaseGroup(req.Price)

if purchaseGroup != utils.GROUP_ADDON {
req.AddonQuantity = 1
}

if purchaseGroup == "" {
http.Error(w, "Error invalid price item provided. Must be the price ID of Sapphire, Emerald or Diamond", http.StatusBadRequest)
http.Error(w, "Error invalid price item provided.", http.StatusBadRequest)
logger.Errorf("error invalid stripe price id provided: %v, expected one of [%v, %v, %v]", req.Price, utils.Config.Frontend.Stripe.Sapphire, utils.Config.Frontend.Stripe.Emerald, utils.Config.Frontend.Stripe.Diamond)
return
}
Expand All @@ -63,6 +69,43 @@ func StripeCreateCheckoutSession(w http.ResponseWriter, r *http.Request) {
})
return
}
} else {
addonSubs, err := db.StripeGetUserSubscriptions(user.UserID, utils.GROUP_ADDON)
if err != nil {
logger.Errorf("error retrieving user addon.subscriptions %v", err)
http.Error(w, "Internal server error", http.StatusInternalServerError)
return
}
totalAddonValidators := int64(0)
for _, s := range addonSubs {
p := utils.EffectiveProductId(utils.PriceIdToProductId(*s.PriceID))
switch p {
case "vdb_addon_1k", "vdb_addon_1k.yearly":
totalAddonValidators += 1_000
case "vdb_addon_10k", "vdb_addon_10k.yearly":
totalAddonValidators += 10_000
default:
logger.Warnf("unknown existing addon-product: %v", p)
}
}
p := utils.EffectiveProductId(utils.PriceIdToProductId(req.Price))
switch p {
case "vdb_addon_1k", "vdb_addon_1k.yearly":
totalAddonValidators += (1_000 * req.AddonQuantity)
case "vdb_addon_10k", "vdb_addon_10k.yearly":
totalAddonValidators += (10_000 * req.AddonQuantity)
default:
logger.Warnf("unknown new addon-product: %v", p)
}
if totalAddonValidators >= 100_000 {
logger.Errorf("error addon can not be purchased since limit has been reached: %v", totalAddonValidators)
w.WriteHeader(http.StatusBadRequest)
writeJSON(w, struct {
ErrorData string `json:"error"`
}{
ErrorData: "could not create a new stripe session",
})
}
}

// taxRates := utils.StripeDynamicRatesLive
Expand Down Expand Up @@ -95,7 +138,7 @@ func StripeCreateCheckoutSession(w http.ResponseWriter, r *http.Request) {
LineItems: []*stripe.CheckoutSessionLineItemParams{
{
Price: stripe.String(req.Price),
Quantity: stripe.Int64(1),
Quantity: stripe.Int64(req.AddonQuantity),
// DynamicTaxRates: taxRates,
},
},
Expand Down Expand Up @@ -197,6 +240,8 @@ func StripeWebhook(w http.ResponseWriter, r *http.Request) {
return
}

logger.WithFields(logrus.Fields{"type": event.Type}).Infof("received stripe webhook")

switch event.Type {
case "customer.created":
var customer stripe.Customer
Expand Down
1 change: 1 addition & 0 deletions types/config.go
Original file line number Diff line number Diff line change
Expand Up @@ -159,6 +159,7 @@ type Config struct {
VdbAddon10kYearly string `yaml:"vdbAddon10kYearly" envconfig:"FRONTEND_STRIPE_VDB_ADDON_10K_YEARLY"`
}
RatelimitUpdateInterval time.Duration `yaml:"ratelimitUpdateInterval" envconfig:"FRONTEND_RATELIMIT_UPDATE_INTERVAL"`
SessionSameSiteNone bool `yaml:"sessionSameSiteNone" envconfig:"FRONTEND_SESSION_SAMESITE_NONE"`
SessionSecret string `yaml:"sessionSecret" envconfig:"FRONTEND_SESSION_SECRET"`
SessionCookieDomain string `yaml:"sessionCookieDomain" envconfig:"FRONTEND_SESSION_COOKIE_DOMAIN"`
SessionCookieDeriveDomainFromRequest bool `yaml:"sessionCookieDeriveDomainFromRequest" envconfig:"FRONTEND_SESSION_COOKIE_DERIVE_DOMAIN_FROM_REQUEST"`
Expand Down
9 changes: 9 additions & 0 deletions utils/products.go
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,15 @@ func EffectiveProductName(productId string) string {
}
}

func ProductIsEligibleForAddons(productId string) bool {
switch productId {
case "orca", "orca.yearly":
return true
default:
return false
}
}

func PriceIdToProductId(priceId string) string {
switch priceId {
case Config.Frontend.Stripe.Plankton:
Expand Down

0 comments on commit 1c6e70a

Please sign in to comment.