Skip to content

Commit

Permalink
fix: demo bugs
Browse files Browse the repository at this point in the history
  • Loading branch information
Reapor-Yurnero committed May 15, 2024
1 parent 6a5bc15 commit 847e757
Show file tree
Hide file tree
Showing 5 changed files with 597 additions and 665 deletions.
39 changes: 35 additions & 4 deletions brick_server/playground/securities/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -91,6 +91,22 @@ async def get_domain_user_app(
return domain_user_app


async def get_token_domain_user_app(
token: dict | None = Depends(get_jwt_payload),
) -> DomainUserApp | None:
logger.info(token)
try:
domain_user_app_id = token.get("domain_user_app")
domain_user_app = await DomainUserApp.get(
domain_user_app_id, fetch_links=True, nesting_depth=1
)
except Exception:
domain_user_app = None
if domain_user_app is None:
raise BizError(ErrorCode.DomainUserAppNotFoundError)
return domain_user_app


class Authorization:
def __init__(
self,
Expand Down Expand Up @@ -299,7 +315,15 @@ async def check_profile(
entity_ids, prefixes = await self.get_authorized_entities_in_profile(
profile, arguments, permission
)
return entity_id in entity_ids
entity_id_parsed = self.brick_db.parse_entity_with_prefixes(entity_id, prefixes)
logger.info(
"check_profile {}: {} ({}) {}",
profile.id,
entity_id,
entity_id_parsed,
entity_id_parsed in entity_ids,
)
return entity_id_parsed in entity_ids

async def check_entities_permission(
self, entity_ids: set[str], permission: PermissionType
Expand Down Expand Up @@ -350,12 +374,19 @@ async def check_entities_permission(
# app must be installed by user
if self.domain_user_app is None:
return False
profile = await self.app.approved_data.permission_profile.fetch()
authed = await self.check_profile(
self.app.profile, self.domain_user_app.arguments, entity_id, permission
profile, self.domain_user_app.arguments, entity_id, permission
)
if self.app.permission_model == PermissionModel.AUGMENTATION and authed:
if (
self.app.approved_data.permission_model == PermissionModel.AUGMENTATION
and authed
):
return True
if self.app.permission_model == PermissionModel.INTERSECTION and not authed:
if (
self.app.approved_data.permission_model == PermissionModel.INTERSECTION
and not authed
):
return False

# check permission by domain_user profile
Expand Down
134 changes: 71 additions & 63 deletions brick_server/playground/services/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
from brick_server.playground import models, schemas
from brick_server.playground.config.manager import settings
from brick_server.playground.interfaces.app_management import get_container_ip
from brick_server.playground.securities.auth import Authorization
from brick_server.playground.securities.auth import get_token_domain_user_app
from brick_server.playground.utilities.dependencies import (
AsyncDatabase,
get_app_management_redis_db,
Expand Down Expand Up @@ -64,6 +64,68 @@ def ensure_safe_path(path, must_exist=False) -> pathlib.Path | None:
return None


@cbv(router)
class AppApi:
caddr_db: StrictRedis = Depends(get_app_management_redis_db)

@router.api_route(
"/api/{path:path}",
methods=["GET", "POST", "DELETE", "PUT", "OPTIONS", "HEAD", "PATCH", "TRACE"],
description="Call a backend api of an app.",
name="apps:api",
)
async def app_api(
self,
request: Request,
path: str = Path(description="Api endpoint in the app"),
domain_user_app: models.DomainUserApp = Depends(get_token_domain_user_app),
):
if path.startswith("/"):
path = path[1:]
# if checker.domain_user_app is None:
# raise BizError(ErrorCode.DomainUserAppNotFoundError)

# TODO: cache cname or put in token
cname = domain_user_app.get_container_name()
container_ip = get_container_ip(cname)

if container_ip:
container_url = (
"http://" + container_ip + ":5000/"
) # TODO: Configure the port
else:
raise BizError(ErrorCode.AppContainerNotFoundError)

dest = container_url + path
request_data = await request.body()
async with httpx.AsyncClient() as client:
api_resp = await client.request(
method=request.method,
url=dest,
# url=request.url.replace(request.host_url, container_url).replace(request.path, '/'+path),
headers={
key: value
for key, value in request.headers.items()
if key != "Host"
},
params={key: value for key, value in request.query_params.items()},
content=request_data,
follow_redirects=False,
)
headers = {
name: value
for name, value in api_resp.headers.items()
if name.lower() not in EXCLUDED_HEADERS
}

resp = Response(
api_resp.content,
status_code=api_resp.status_code,
headers=headers,
)
return resp


@cbv(router)
class AppRoute:

Expand Down Expand Up @@ -95,6 +157,14 @@ async def register_app(
await app.save()
return schemas.AppRead.model_validate(app.dict()).to_response()

@router.get("/me", name="apps:current_app")
async def get_current_app(
self, domain_user_app: models.DomainUserApp = Depends(get_token_domain_user_app)
) -> schemas.StandardResponse[schemas.DomainUserAppRead]:
return schemas.DomainUserAppRead.model_validate(
domain_user_app.dict()
).to_response()

@router.get(
"/{app}",
description="Get information about an app.",
Expand Down Expand Up @@ -430,65 +500,3 @@ def get_static(
"transfer-encoding",
"connection",
]


@cbv(router)
class AppApi:
caddr_db: StrictRedis = Depends(get_app_management_redis_db)

@router.api_route(
"/{app}/api/{path:path}",
methods=["GET", "POST", "DELETE", "PUT", "OPTIONS", "HEAD", "PATCH", "TRACE"],
description="Call a backend api of an app.",
name="apps:api",
)
async def app_api(
self,
request: Request,
path: str = Path(description="Api endpoint in the app"),
checker: Authorization = Depends(PermissionChecker()),
):
if path.startswith("/"):
path = path[1:]
if checker.domain_user_app is None:
raise BizError(ErrorCode.DomainUserAppNotFoundError)

# TODO: cache cname or put in token
cname = checker.domain_user_app.get_container_name()
container_ip = get_container_ip(cname)

if container_ip:
container_url = (
"http://" + container_ip + ":5000/"
) # TODO: Configure the port
else:
raise BizError(ErrorCode.AppContainerNotFoundError)

dest = container_url + path
request_data = await request.body()
async with httpx.AsyncClient() as client:
api_resp = await client.request(
method=request.method,
url=dest,
# url=request.url.replace(request.host_url, container_url).replace(request.path, '/'+path),
headers={
key: value
for key, value in request.headers.items()
if key != "Host"
},
params={key: value for key, value in request.query_params.items()},
content=request_data,
follow_redirects=False,
)
headers = {
name: value
for name, value in api_resp.headers.items()
if name.lower() not in EXCLUDED_HEADERS
}

resp = Response(
api_resp.content,
status_code=api_resp.status_code,
headers=headers,
)
return resp
6 changes: 3 additions & 3 deletions docker-compose-dev.yml
Original file line number Diff line number Diff line change
@@ -1,12 +1,12 @@
version: '3.5'
services:
mongo:
image: mongo:5.0-focal
# mongo:
# image: mongo:5.0-focal
core:
environment:
DEBUG: true
WORKERS: 1
FRONTEND_URL: http://localhost:8000
# FRONTEND_URL: http://localhost:8000
volumes:
- ./static:/root/brick-server-playground/static
- ./brick_server/playground:/root/brick-server-playground/brick_server/playground
Expand Down
17 changes: 17 additions & 0 deletions docker-compose.yml
Original file line number Diff line number Diff line change
Expand Up @@ -78,6 +78,23 @@ services:
privileged: true
command: dockerize -wait http://graphdb:7200/rest/repositories python3 -m brick_server.playground
# entrypoint: /app/docker/start-reload.sh
mongo-express:
image: mongo-express
restart: always
environment:
ME_CONFIG_BASICAUTH_USERNAME: ${MONGO_USERNAME:-root}
ME_CONFIG_BASICAUTH_PASSWORD: ${MONGO_PASSWORD:-pass}
ME_CONFIG_MONGODB_ADMINUSERNAME: ${MONGO_USERNAME:-r oot}
ME_CONFIG_MONGODB_ADMINPASSWORD: ${MONGO_PASSWORD:-pass}
# ME_CONFIG_MONGODB_URL: mongodb://${MONGO_USERNAME:-root}:${MONGO_PASSWORD:-pass}@mongo:27017/
ME_CONFIG_MONGODB_URL: mongodb://mongo:27017/
networks:
- brick-server-network
ports:
- "38082:8081"
depends_on:
- mongo

redis-commander:
image: ghcr.io/joeferner/redis-commander:latest
restart: always
Expand Down
Loading

0 comments on commit 847e757

Please sign in to comment.