Skip to content

Commit

Permalink
clean up
Browse files Browse the repository at this point in the history
  • Loading branch information
Josh-XT committed Nov 18, 2024
1 parent 495bf75 commit 8eb524f
Show file tree
Hide file tree
Showing 2 changed files with 1 addition and 165 deletions.
108 changes: 1 addition & 107 deletions agixt/MagicalAuth.py
Original file line number Diff line number Diff line change
Expand Up @@ -508,8 +508,6 @@ def update_user(self, **kwargs):
.filter(UserPreferences.user_id == self.user_id)
.all()
)
if "stripe_id" in kwargs:
del kwargs["stripe_id"]
if "email" in kwargs:
del kwargs["email"]
if "input_tokens" in kwargs:
Expand Down Expand Up @@ -673,63 +671,8 @@ def registration_requirements(self):
requirements = json.load(file)
if not requirements:
requirements = {}
if "stripe_id" not in requirements:
requirements["stripe_id"] = "None"
return requirements

def get_subscribed_products(self, stripe_api_key, stripe_customer_id):
import stripe

# TODO make sure if the stripe request fails, an exception gets thrown.
stripe.api_key = stripe_api_key
logging.info(f"Checking subscriptions for customer {stripe_customer_id}...")
all_subscriptions = stripe.Subscription.list(
customer=stripe_customer_id,
expand=["data.items.data.price"],
)
logging.info(f"Found {len(all_subscriptions)} subscriptions.")
relevant_subscriptions = []
for subscription in all_subscriptions:
logging.info(f"Checking subscription {subscription['id']}")
if subscription.status == "active":
logging.info(f"Subscription {subscription['id']} active.")
relevant_to_this_app = None
for item in subscription["items"]:
product_id = item["price"]["product"]
product = stripe.Product.retrieve(product_id)
try:
relevant_app = product["metadata"]["APP_NAME"]
except:
relevant_app = "[No App Defined in Product]"
logging.warning(
f"Subscription detected with items missing relevant APP_NAME metadata: {subscription['id']}"
)
print(product)
print(relevant_app)
if relevant_app == getenv("APP_NAME"):
if relevant_to_this_app == False:
raise Exception(
f"Subscription detected with items from multiple apps (or products missing metadata): {subscription['id']}"
)
relevant_to_this_app = True
logging.info(
f"Subscription {subscription['id']} relevant to this app {getenv('APP_NAME')}."
)
else:
if relevant_to_this_app == True:
raise Exception(
f"Subscription detected with items from multiple apps (or products missing metadata): {subscription['id']}"
)
relevant_to_this_app = False
logging.info(
f"Subscription {subscription['id']} not relevant to this app {getenv('APP_NAME')}, is for {relevant_app}."
)
if relevant_to_this_app:
relevant_subscriptions.append(subscription)
else:
logging.info(f"Subscription {subscription['id']} not active.")
return relevant_subscriptions

def get_user_preferences(self):
session = get_session()
user = session.query(User).filter(User.id == self.user_id).first()
Expand All @@ -746,54 +689,6 @@ def get_user_preferences(self):
user_preferences["input_tokens"] = 0
if "output_tokens" not in user_preferences:
user_preferences["output_tokens"] = 0
if user.email != getenv("DEFAULT_USER"):
api_key = getenv("STRIPE_API_KEY")
if api_key != "" and api_key is not None and str(api_key).lower() != "none":
import stripe

stripe.api_key = api_key
if "stripe_id" not in user_preferences or not user_preferences[
"stripe_id"
].startswith("cus_"):
logging.info("No Stripe ID found in user preferences.")
customer = stripe.Customer.create(email=user.email)
user_preferences["stripe_id"] = customer.id
user_preference = UserPreferences(
user_id=self.user_id,
pref_key="stripe_id",
pref_value=customer.id,
)
session.add(user_preference)
session.commit()

else:
logging.info("Stripe ID found: " + user_preferences["stripe_id"])
relevant_subscriptions = self.get_subscribed_products(
api_key, user_preferences["stripe_id"]
)
if not relevant_subscriptions:
logging.info(f"No active subscriptions for this app detected.")
c_session = stripe.CustomerSession.create(
customer=user_preferences["stripe_id"],
components={"pricing_table": {"enabled": True}},
)
user = (
session.query(User).filter(User.id == self.user_id).first()
)
user.is_active = False
session.commit()
session.close()
raise HTTPException(
status_code=402,
detail={
"message": f"No active subscriptions.",
"customer_session": c_session,
},
)
else:
logging.info(
f"{len(relevant_subscriptions)} subscriptions relevant to this app detected."
)
if "email" in user_preferences:
del user_preferences["email"]
if "first_name" in user_preferences:
Expand All @@ -806,8 +701,7 @@ def get_user_preferences(self):
if user_requirements:
for key, value in user_requirements.items():
if key not in user_preferences:
if key != "stripe_id":
missing_requirements.append({key: value})
missing_requirements.append({key: value})
if missing_requirements:
user_preferences["missing_requirements"] = missing_requirements
session.close()
Expand Down
58 changes: 0 additions & 58 deletions agixt/endpoints/Auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
from Models import WebhookUser, WebhookModel
from Globals import getenv
import pyotp
import stripe
import logging

app = APIRouter()
Expand Down Expand Up @@ -146,63 +145,6 @@ async def createuser(account: WebhookUser):
return {"status": "Success"}, 200


if getenv("STRIPE_WEBHOOK_SECRET") != "":

@app.post(
"/v1/webhook",
summary="Webhook endpoint for events.",
response_model=WebhookModel,
tags=["Webhook"],
)
async def webhook(request: Request):
event = None
data = None
try:
event = stripe.Webhook.construct_event(
payload=(await request.body()).decode("utf-8"),
sig_header=request.headers.get("stripe-signature"),
secret=getenv("STRIPE_WEBHOOK_SECRET"),
)
data = event["data"]["object"]
except stripe.error.SignatureVerificationError as e:
logging.debug(f"Webhook signature verification failed: {str(e)}.")
raise HTTPException(
status_code=400, detail="Webhook signature verification failed."
)
logging.debug(f"Stripe Webhook Event of type {event['type']} received")
if event and event["type"] == "checkout.session.completed":
session = get_session()
logging.debug("Checkout session completed.")
email = data["customer_details"]["email"]
user = session.query(User).filter_by(email=email).first()
stripe_id = data["customer"]
name = data["customer_details"]["name"]
if not user:
logging.debug("User not found.")
return {"success": "false"}
user_preference_stripe_id = (
session.query(UserPreferences)
.filter_by(user_id=user.id, pref_key="stripe_id")
.first()
)
if not user_preference_stripe_id:
user_preference_stripe_id = UserPreferences(
user_id=user.id, pref_key="stripe_id", pref_value=stripe_id
)
session.add(user_preference_stripe_id)
session.commit()
name = name.split(" ")
user.is_active = True
session.commit()
session.close()
return {"success": "true"}
elif event and event["type"] == "customer.subscription.updated":
logging.debug("Customer Subscription Update session completed.")
else:
logging.debug("Unhandled Stripe event type {}".format(event["type"]))
return {"success": "true"}


@app.post(
"/v1/oauth2/{provider}",
tags=["User"],
Expand Down

0 comments on commit 8eb524f

Please sign in to comment.