Skip to content

Commit

Permalink
Merge pull request #52 from bcgov/feature/connections
Browse files Browse the repository at this point in the history
Refactor tenant api's into sub-app
  • Loading branch information
usingtechnology authored Jan 31, 2022
2 parents 759b282 + 4bc35e5 commit 1ac2e8d
Show file tree
Hide file tree
Showing 5 changed files with 74 additions and 43 deletions.
3 changes: 3 additions & 0 deletions services/traction/api/core/config.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,9 @@ class GlobalConfig(BaseSettings):
TITLE: str = "Traction"
DESCRIPTION: str = "A digital wallet solution for organizations"

TENANT_TITLE: str = "Traction"
TENANT_DESCRIPTION: str = "A digital wallet solution for organizations"

ENVIRONMENT: EnvironmentEnum
DEBUG: bool = False
TESTING: bool = False
Expand Down
6 changes: 1 addition & 5 deletions services/traction/api/endpoints/routes/api.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,7 @@
from fastapi import APIRouter

from api.endpoints.routes import innkeeper, tenants, connections, ledger
from api.endpoints.routes import innkeeper, tenants

api_router = APIRouter()
api_router.include_router(
connections.router, prefix="/connections", tags=["connections"]
)
api_router.include_router(ledger.router, prefix="/ledger", tags=["ledger"])
api_router.include_router(innkeeper.router, prefix="/innkeeper", tags=["innkeeper"])
api_router.include_router(tenants.router, prefix="/tenants", tags=["tenants"])
9 changes: 9 additions & 0 deletions services/traction/api/endpoints/routes/tenant_api.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
from fastapi import APIRouter

from api.endpoints.routes import connections, ledger

tenant_router = APIRouter()
tenant_router.include_router(
connections.router, prefix="/connections", tags=["connections"]
)
tenant_router.include_router(ledger.router, prefix="/ledger", tags=["ledger"])
43 changes: 5 additions & 38 deletions services/traction/api/main.py
Original file line number Diff line number Diff line change
@@ -1,45 +1,27 @@
import os
import time
from datetime import timedelta

import uvicorn
from fastapi import Depends, FastAPI, HTTPException, Request, status
from fastapi.security import OAuth2PasswordRequestForm
from starlette.middleware import Middleware
from fastapi import FastAPI, Request, status
from starlette.responses import JSONResponse
from starlette_context import plugins
from starlette_context.middleware import RawContextMiddleware

from api.db.errors import DoesNotExist, AlreadyExists
from api.endpoints.routes.api import api_router
from api.endpoints.routes.webhooks import get_webhookapp
from api.tenant_security import (
TenantToken,
authenticate_tenant,
create_access_token,
JWTTFetchingMiddleware,
)
from api.core.config import settings
from api.tenant_main import get_tenantapp


os.environ["TZ"] = settings.TIMEZONE
time.tzset()

middleware = [
Middleware(
RawContextMiddleware,
plugins=(plugins.RequestIdPlugin(), plugins.CorrelationIdPlugin()),
),
Middleware(JWTTFetchingMiddleware),
]


def get_application() -> FastAPI:
application = FastAPI(
title=settings.TITLE,
description=settings.DESCRIPTION,
debug=settings.DEBUG,
middleware=middleware,
middleware=None,
)
application.include_router(api_router, prefix=settings.API_V1_STR)
return application
Expand All @@ -48,6 +30,8 @@ def get_application() -> FastAPI:
app = get_application()
webhook_app = get_webhookapp()
app.mount("/webhook", webhook_app)
tenant_app = get_tenantapp()
app.mount("/tenant", tenant_app)


@app.exception_handler(DoesNotExist)
Expand All @@ -71,23 +55,6 @@ def main():
return {"status": "ok", "health": "ok"}


@app.post("/token", response_model=TenantToken)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
tenant = await authenticate_tenant(form_data.username, form_data.password)
if not tenant:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect wallet_id or wallet_key",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": tenant["wallet_id"], "key": tenant["wallet_token"]},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}


if __name__ == "__main__":
print("main.")
uvicorn.run(app, host="0.0.0.0", port=8080)
56 changes: 56 additions & 0 deletions services/traction/api/tenant_main.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,56 @@
from datetime import timedelta

from fastapi import APIRouter, Depends, FastAPI, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from starlette.middleware import Middleware
from starlette_context import plugins
from starlette_context.middleware import RawContextMiddleware

from api.endpoints.routes.tenant_api import tenant_router
from api.tenant_security import (
TenantToken,
authenticate_tenant,
create_access_token,
JWTTFetchingMiddleware,
)
from api.core.config import settings


middleware = [
Middleware(
RawContextMiddleware,
plugins=(plugins.RequestIdPlugin(), plugins.CorrelationIdPlugin()),
),
Middleware(JWTTFetchingMiddleware),
]

router = APIRouter()


def get_tenantapp() -> FastAPI:
application = FastAPI(
title=settings.TENANT_TITLE,
description=settings.TENANT_DESCRIPTION,
debug=settings.DEBUG,
middleware=middleware,
)
application.include_router(tenant_router, prefix=settings.API_V1_STR)
application.include_router(router, prefix="")
return application


@router.post("/token", response_model=TenantToken)
async def login_for_access_token(form_data: OAuth2PasswordRequestForm = Depends()):
tenant = await authenticate_tenant(form_data.username, form_data.password)
if not tenant:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="Incorrect wallet_id or wallet_key",
headers={"WWW-Authenticate": "Bearer"},
)
access_token_expires = timedelta(minutes=settings.JWT_ACCESS_TOKEN_EXPIRE_MINUTES)
access_token = create_access_token(
data={"sub": tenant["wallet_id"], "key": tenant["wallet_token"]},
expires_delta=access_token_expires,
)
return {"access_token": access_token, "token_type": "bearer"}

0 comments on commit 1ac2e8d

Please sign in to comment.