Skip to content

Commit

Permalink
Access tokens moved to core, stockx oauth fixed
Browse files Browse the repository at this point in the history
  • Loading branch information
peterrauscher committed Mar 16, 2024
1 parent 91418d7 commit 7f8e5cd
Show file tree
Hide file tree
Showing 3 changed files with 16 additions and 22 deletions.
12 changes: 1 addition & 11 deletions src/api/data/models.py
Original file line number Diff line number Diff line change
@@ -1,19 +1,9 @@
from enum import Enum
from typing import List

from beanie import Document
from core.models.shoes import SneakerView
from pydantic import BaseModel

from core.models.shoes import Sneaker, SneakerView


class Token(Document):
type: str
token: str

class Settings:
collection = "OAuth"


class PaginatedSneakersResponse(BaseModel):
total: int
Expand Down
8 changes: 4 additions & 4 deletions src/api/main.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
__version__ = "2.0.0"
__version__ = "2.1.0"

import os

from core.models import Token
from dotenv import load_dotenv

# Load environment variables from .env file if not running in AWS Lambda
Expand All @@ -10,16 +11,15 @@
load_dotenv(os.path.join(os.getcwd(), ".env"))

from beanie import init_beanie
from core.models.shoes import Sneaker
from fastapi import FastAPI
from fastapi.middleware.cors import CORSMiddleware
from fastapi.openapi.docs import get_swagger_ui_html
from fastapi.staticfiles import StaticFiles
from mangum import Mangum
from starlette.middleware.sessions import SessionMiddleware

from api.data.instance import DATABASE_NAME, client
from api.routes import auth, sneakers
from core.models.shoes import Sneaker

desc = """
### The Bloomberg Terminal of Sneakers
Expand Down Expand Up @@ -56,7 +56,7 @@ async def startup_event():
# Initialize Beanie ODM
await init_beanie(
database=client.get_database(DATABASE_NAME),
document_models=[Sneaker],
document_models=[Sneaker, Token],
)
# Include all routers
app.include_router(sneakers.router)
Expand Down
18 changes: 11 additions & 7 deletions src/api/routes/auth.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,13 @@
import logging
import os
from datetime import UTC, datetime, timedelta
from urllib.parse import urlparse

import requests
from core.models import Token
from fastapi import APIRouter, HTTPException, Request
from fastapi.responses import RedirectResponse

from api.data.models import Token

STOCKX_CLIENT_ID = os.environ.get("SOLESEARCH_STOCKX_CLIENT_ID", None)
STOCKX_CLIENT_SECRET = os.environ.get("SOLESEARCH_STOCKX_CLIENT_SECRET", None)
STOCKX_API_KEY = os.environ.get("SOLESEARCH_STOCKX_API_KEY", None)
Expand Down Expand Up @@ -56,7 +56,7 @@ async def stockx_oauth_callback(state: str, code: str, request: Request):
"client_id": STOCKX_CLIENT_ID,
"client_secret": STOCKX_CLIENT_SECRET,
"code": code,
"redirect_uri": f"https://{urlparse(request.url_for('get_sneakers')).netloc}",
"redirect_uri": f"https://{urlparse(str(request.url_for('get_sneakers'))).netloc}",
}
tokens = (
session.post(
Expand All @@ -67,11 +67,15 @@ async def stockx_oauth_callback(state: str, code: str, request: Request):
).json()
for token_type in ["id_token", "access_token", "refresh_token"]:
if token_type in tokens:
await Token.find_one(Token.type == token_type).set(
{"$set": {"token": tokens[token_type]}}
)
token = await Token.find_one(Token.id == token_type)
setattr(token, "value", tokens[token_type])
if token_type == "access_token":
token.expires = datetime.now(UTC) + timedelta(
seconds=int(tokens["expires_in"]) - 30
)
await token.save()
logging.info(f"Updated {token_type}")
return tokens
except Exception as e:
logging.error(e)
logging.exception(e)
raise HTTPException(status_code=500, detail=str(e))

0 comments on commit 7f8e5cd

Please sign in to comment.