Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

prod deploy #141

Merged
merged 4 commits into from
Oct 27, 2021
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
97 changes: 97 additions & 0 deletions myauth/migrations/0021_update_stripe_storage_prices.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,97 @@
# flake8: noqa: W291
import os
from django.db import migrations


class Migration(migrations.Migration):

dependencies = [
("myauth", "0020_auto_20210920_1016"),
]

if os.environ.get("DJANGO_SETTINGS_MODULE") == "server.settings.production":
print("Running PRODUCTION migration")
operations = [
migrations.RunSQL(
"""
UPDATE myauth_tier SET name = 'COMMUNITY',
stripe_flat_price_id = null,
stripe_storage_price_id = 'price_1JPNxkFauXVlvS5wweWbfiGw',
stripe_collaborator_price_id = 'price_1JPNytFauXVlvS5waAQC8czE',
stripe_user_price_id = null,
stripe_project_price_id = 'price_1JPNyyFauXVlvS5wqfqzkrBS',
base_collaborator_limit = 2,
base_project_limit = 1,
base_storage_limit = 1000,
base_user_limit = 1
WHERE id = 1;

UPDATE myauth_tier SET name = 'PRO',
stripe_flat_price_id = 'price_1JPNxxFauXVlvS5wva02Iw90',
stripe_storage_price_id = 'price_1JjkCuFauXVlvS5w9pot4NWr',
stripe_collaborator_price_id = 'price_1JPNyAFauXVlvS5wPyAFUOxl',
stripe_user_price_id = 'price_1JPNyOFauXVlvS5w8eIGos3k',
stripe_project_price_id = null,
base_collaborator_limit = 2,
base_project_limit = null,
base_storage_limit = 10000,
base_user_limit = 10
WHERE id = 2;

UPDATE myauth_tier SET name = 'TEAM',
stripe_flat_price_id = 'price_1JPNyUFauXVlvS5wbefopTwb',
stripe_storage_price_id = 'price_1JjkDgFauXVlvS5wtbQt4voC',
stripe_collaborator_price_id = 'price_1JPNynFauXVlvS5wfssg6GST',
stripe_user_price_id = 'price_1JPNyjFauXVlvS5w8IiOPJxP',
stripe_project_price_id = null,
base_collaborator_limit = 5,
base_project_limit = null,
base_storage_limit = 100000,
base_user_limit = 15
WHERE id = 3;
"""
)
]
else:
print("Running NON-PRODUCTION migration")
operations = [
migrations.RunSQL(
"""
UPDATE myauth_tier SET name = 'COMMUNITY',
stripe_flat_price_id = null,
stripe_storage_price_id = 'price_1JMrOtFauXVlvS5wTLRzIqqu',
stripe_collaborator_price_id = 'price_1JMrOtFauXVlvS5wTLRzIqqu',
stripe_user_price_id = null,
stripe_project_price_id = 'price_1JMrT4FauXVlvS5wtoHCunES',
base_collaborator_limit = 2,
base_project_limit = 1,
base_storage_limit = 1000,
base_user_limit = 1
WHERE id = 1;

UPDATE myauth_tier SET name = 'PRO',
stripe_flat_price_id = 'price_1JMrINFauXVlvS5wQxncCCrF',
stripe_storage_price_id = 'price_1Jjk6xFauXVlvS5wnfx98Ojr',
stripe_collaborator_price_id = 'price_1JMrJRFauXVlvS5w2WpMI1IK',
stripe_user_price_id = 'price_1JMrKHFauXVlvS5wYzIX36Rm',
stripe_project_price_id = null,
base_collaborator_limit = 2,
base_project_limit = null,
base_storage_limit = 10000,
base_user_limit = 10
WHERE id = 2;

UPDATE myauth_tier SET name = 'TEAM',
stripe_flat_price_id = 'price_1JMrQGFauXVlvS5wDBOJnJHm',
stripe_storage_price_id = 'price_1JMrOtFauXVlvS5wKV9LOuw8',
stripe_collaborator_price_id = 'price_1JMrRtFauXVlvS5w2vMOo1sv',
stripe_user_price_id = 'price_1JMrRCFauXVlvS5wQeuL7Z1l',
stripe_project_price_id = null,
base_collaborator_limit = 5,
base_project_limit = null,
base_storage_limit = 100000,
base_user_limit = 15
WHERE id = 3;
"""
)
]
18 changes: 18 additions & 0 deletions myauth/migrations/0022_team_name.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
# Generated by Django 3.1.4 on 2021-10-14 12:53

from django.db import migrations, models


class Migration(migrations.Migration):

dependencies = [
('myauth', '0021_update_stripe_storage_prices'),
]

operations = [
migrations.AddField(
model_name='team',
name='name',
field=models.CharField(default='', max_length=200),
),
]
29 changes: 29 additions & 0 deletions myauth/migrations/0023_auto_20211020_1000.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
# Generated by Django 3.1.4 on 2021-10-20 10:00

from django.db import migrations, models
import django.db.models.deletion


class Migration(migrations.Migration):

dependencies = [
('myauth', '0022_team_name'),
]

operations = [
migrations.AddField(
model_name='tier',
name='is_custom',
field=models.BooleanField(default=False),
),
migrations.CreateModel(
name='CustomBilling',
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('start_date', models.DateTimeField(blank=True, null=True)),
('renewal_date', models.DateTimeField(blank=True, null=True)),
('cancel_date', models.DateTimeField(blank=True, null=True)),
('team', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, to='myauth.team')),
],
),
]
51 changes: 51 additions & 0 deletions myauth/migrations/0024_add_custom_tiers_1.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,51 @@
# Generated by Craig 3.1.4 on 2021-10-20 09:23

from django.db import migrations
import os


def add_tiers(apps, schema_editor):
Tier = apps.get_model("myauth", "Tier")

if os.environ.get("DJANGO_SETTINGS_MODULE") == "server.settings.production":
print("Running PRODUCTION migration")

Tier(
id=10001,
name="ACACIA",
base_user_limit=5,
base_collaborator_limit=0,
base_project_limit=None,
base_storage_limit=10000,
is_custom=True,
).save()

Tier(
id=10002,
name="OCTAHEDRON",
base_user_limit=5,
base_collaborator_limit=50,
base_project_limit=None,
base_storage_limit=1000 * 1000,
is_custom=True,
).save()
else:
print("Running NON-PRODUCTION migration")
Tier(
id=10001,
name="CUSTOM TEST PLAN",
base_user_limit=5,
base_collaborator_limit=50,
base_project_limit=None,
base_storage_limit=1000 * 1000,
is_custom=True,
).save()


class Migration(migrations.Migration):

dependencies = [
("myauth", "0023_auto_20211020_1000"),
]

operations = [migrations.RunPython(add_tiers)]
12 changes: 10 additions & 2 deletions myauth/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,10 +71,12 @@ class Tier(models.Model):
base_collaborator_limit = models.IntegerField(null=True)
base_storage_limit = models.IntegerField(null=True)

is_custom = models.BooleanField(null=False, default=False)


class Team(models.Model):
id: int

name = models.CharField(max_length=200, default="")
# Protect means you can't delete an owner, remove the team first!
owner = models.OneToOneField(User, on_delete=models.PROTECT)
tier = models.ForeignKey(Tier, on_delete=models.PROTECT)
Expand Down Expand Up @@ -108,14 +110,20 @@ def __str__(self):

class Billing(models.Model):
team = models.OneToOneField(Team, on_delete=models.CASCADE)

stripe_customer_id = models.CharField(max_length=255, unique=True)
start_date = models.DateTimeField(blank=True, null=True)
renewal_date = models.DateTimeField(blank=True, null=True)
subscription_id = models.CharField(max_length=255, blank=True)
cancel_date = models.DateTimeField(blank=True, null=True)


class CustomBilling(models.Model):
team = models.OneToOneField(Team, on_delete=models.CASCADE)
start_date = models.DateTimeField(blank=True, null=True)
renewal_date = models.DateTimeField(blank=True, null=True)
cancel_date = models.DateTimeField(blank=True, null=True)


class Invite(models.Model):
uid = models.CharField(db_index=True, blank=False, null=False, max_length=43, validators=[UidValidator])
from_team = models.ForeignKey(Team, on_delete=models.CASCADE)
Expand Down
48 changes: 41 additions & 7 deletions server/api/billing.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@
import stripe


from myauth.models import Tier, Team, Billing, TierAddons, User, UserProfile
from myauth.models import Tier, Team, Billing, TierAddons, User, UserProfile, CustomBilling
from server.api.schemas import (
CheckoutSessionIn,
CheckoutSessionOut,
Expand Down Expand Up @@ -54,6 +54,8 @@ def calculate_plan_total(base, addons):
def calculate_plan(team):
plan = dict(tier_name=team.tier.name, tier_id=team.tier.id)

# They are either on the free plan or a custom plan
# Either way, they can't have addons so just return the standard plan
if not hasattr(team, "billing"):
return plan

Expand Down Expand Up @@ -132,7 +134,7 @@ def calculate_limits(team):
plan["storage_included_limit"] = team.tier.base_storage_limit

# Add limits
if not hasattr(team, "billing"):
if not hasattr(team, "billing") and not hasattr(team, "custombilling"):
# Team is on the free plan so it's whatever those limits are
plan["has_billing"] = False
plan["projects_limit"] = team.tier.base_project_limit
Expand All @@ -158,12 +160,15 @@ def calculate_limits(team):

@router.get(
"/payment-method",
response={200: PaymentOut, 403: Error, 500: Error},
response={200: PaymentOut, 403: Error, 422: Error, 500: Error},
)
def get_payments(request):
user = request.auth
team = Team.objects.get(owner_id=user.id)

if hasattr(team, "custombilling"):
return 422, {"message": "Payment methods for custom plans cannot be shown here"}

subscription = stripe.Subscription.retrieve(team.billing.subscription_id)
payment_method = stripe.PaymentMethod.retrieve(subscription["default_payment_method"])

Expand All @@ -188,6 +193,9 @@ def get_invoices(request):
if user.team.owner_id is not user.id:
return 403, {"message": "Only owners can view invoices"}

if hasattr(team, "custombilling"):
return 403, {"message": "Custom invoices cannot be shown here"}

invoices = stripe.Invoice.list(customer=team.billing.stripe_customer_id)
if invoices:
return {"invoices": invoices.data}
Expand All @@ -211,7 +219,7 @@ def get_plan_limits(request):

@router.get(
"/plan",
response={200: CurrentPlanOut, 403: Error, 500: Error},
response={200: CurrentPlanOut, 204: None, 403: Error, 500: Error},
)
def get_plan(request):
user = request.auth
Expand All @@ -220,6 +228,9 @@ def get_plan(request):
if user.team.owner_id is not user.id:
return 403, {"message": "Only owners can view plan details"}

if hasattr(team, "custombilling"):
return 204, None

return calculate_plan(team)


Expand Down Expand Up @@ -299,6 +310,9 @@ def addon(request, payload: AddonIn):
if user.team.owner_id is not user.id:
return 403, {"message": "Only owners can upgrade plans"}

if hasattr(team, "custombilling"):
return 422, {"message": "You can't have addons on a custom plan"}

if not hasattr(team, "billing"):
return 422, {"message": "No valid subscription to upgrade. Try changing your plan"}

Expand Down Expand Up @@ -362,7 +376,7 @@ def addon(request, payload: AddonIn):
return 500, {"message": "Unknown Error"}


@router.post("/create-authd-checkout-session", response={200: CheckoutSessionOut, 422: Error, 403: Error})
@router.post("/create-authd-checkout-session/", response={200: CheckoutSessionOut, 422: Error, 403: Error})
def create_auth_checkout_session(request):
try:
user = request.auth
Expand All @@ -371,6 +385,9 @@ def create_auth_checkout_session(request):
if user.team.owner_id is not user.id:
return 403, {"message": "Only owners can upgrade plans"}

if hasattr(team, "custombilling"):
return 422, {"message": "You can't upgrade a custom plan"}

if not hasattr(team, "billing"):
return 422, {"message": "No valid subscription to upgrade. Try changing your plan"}

Expand All @@ -393,18 +410,35 @@ def create_auth_checkout_session(request):
return 403, {"message": str(e)}


@router.post("/create-checkout-session", response={200: CheckoutSessionOut, 403: Error, 409: Error}, auth=None)
@router.post(
"/create-checkout-session/", response={200: CheckoutSessionOut, 201: None, 403: Error, 409: Error}, auth=None
)
def create_checkout_session(request, payload: CheckoutSessionIn):
try:
user = User.objects.get(id__exact=payload.user_id)
tier = Tier.objects.get(id__exact=payload.tier_id)
team = Team.objects.get(owner_id=user.id)

# This is a free plan, no need to bill them
if tier.stripe_flat_price_id is None:
if tier.id == 1:
logger.error(f"we shouldn't create_checkout_session for a free plan?! ({payload.tier_id})")
return 409, {"message": "Can't pay for a free tier"}

if tier.is_custom:
# Has this plan already been used?
if Team.objects.filter(tier_id=payload.tier_id):
logger.error(f"Custom Tier already used - ({payload.tier_id})")
return 409, {"message": "This tier is unavailable"}

CustomBilling.objects.create(
start_date=datetime.now(tz=timezone.utc),
renewal_date=None,
team_id=team.id,
).save()

Team.objects.filter(id=team.id).update(tier_id=payload.tier_id)
return 201, None

# Charge the flat rate and add storage, which is updated daily
line_items = [
{"price": tier.stripe_flat_price_id, "quantity": 1},
Expand Down
7 changes: 6 additions & 1 deletion server/api/middleware/EnforceCollabMiddleware.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:

# Explicit Allow
allowed_routes = [
("POST", "/django/api/billing/create-checkout-session"),
("POST", "/django/api/billing/create-checkout-session/"),
("POST", "/django/api/billing/webhook"),
("POST", "/api/v1/collection/list_multi/"),
("POST", "/item/fetch_updates/"),
Expand All @@ -47,6 +47,11 @@ async def __call__(self, scope: Scope, receive: Receive, send: Send) -> None:
if (method == scope["method"] or method == "*") and scope["path"].startswith(path):
# This runs before our regular auth, so we have to check here
key = get_key_from_headers(scope["headers"])
if key is None:
logger.error("Blocked by EnforceCollabMiddleware (No key)")
response = JSONResponse({"message": "Collaborators can't access this"}, status_code=401)
await response(scope, receive, send)
return
is_collab = await get_user_is_collab(key)
if is_collab:
logger.info("Blocked by EnforceCollabMiddleware")
Expand Down
Loading