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

hotfix: squash bugs #28

Merged
merged 3 commits into from
Jan 25, 2024
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
16 changes: 12 additions & 4 deletions src/pwncore/routes/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import datetime
import typing as t
from logging import getLogger

import jwt
from fastapi import APIRouter, Header, Response, HTTPException, Depends
Expand All @@ -19,6 +20,7 @@
}

router = APIRouter(prefix="/auth", tags=["auth"])
logger = getLogger(__name__)


class AuthBody(BaseModel):
Expand Down Expand Up @@ -48,13 +50,14 @@ async def signup_team(team: SignupBody, response: Response):
return {"msg_code": config.msg_codes["team_exists"]}

q = await User.filter(tag__in=members)
# print(q, members)
if len(q) != len(members):
response.status_code = 404
return {
"msg_code": config.msg_codes["users_not_found"],
"tags": list(members - set(map(lambda h: h.tag, q))),
}
in_teams = list(filter(lambda h: h.team is not None, q))
in_teams = list(filter(lambda h: h.team, q))
if in_teams:
response.status_code = 401
return {
Expand All @@ -68,10 +71,13 @@ async def signup_team(team: SignupBody, response: Response):

for user in q:
# Mypy kinda not working
user.team = newteam # type: ignore[assignment]
user.team_id = newteam.id # type: ignore[attr-defined]
if q:
await User.bulk_update(q, fields=["team"])
b = User.bulk_update(q, fields=["team_id"])
# print(b.sql())
await b
except Exception:
logger.exception("error in signup!")
response.status_code = 500
return {"msg_code": config.msg_codes["db_error"]}
return {"msg_code": config.msg_codes["signup_success"]}
Expand Down Expand Up @@ -107,10 +113,12 @@ async def team_login(team_data: AuthBody, response: Response):
def get_jwt(*, authorization: t.Annotated[str, Header()]) -> JwtInfo:
try:
token = authorization.split(" ")[1] # Remove Bearer
# print(token, authorization)
decoded_token: JwtInfo = jwt.decode(
token, config.jwt_secret, algorithms=["HS256"]
)
except Exception: # Will filter for invalid signature/expired tokens
except Exception as err: # Will filter for invalid signature/expired tokens
logger.warning("Invalid login", exc_info=err)
raise HTTPException(status_code=401)
return decoded_token

Expand Down
22 changes: 12 additions & 10 deletions src/pwncore/routes/ctf/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,6 +52,15 @@ class Flag(BaseModel):
flag: str


@router.get("/completed")
async def completed_problem_get(jwt: RequireJwt):
team_id = jwt["team_id"]
problems = await Problem_Pydantic.from_queryset(
Problem.filter(solvedproblems__team_id=team_id, visible=True)
)
return problems


@router.get("/list")
async def ctf_list():
problems = await Problem_Pydantic.from_queryset(Problem.filter(visible=True))
Expand Down Expand Up @@ -88,7 +97,9 @@ async def flag_post(
)
if check_solved:
hints = await Hint.filter(
problem_id=ctf_id, viewedhints__team_id=team_id, with_points=True
problem_id=ctf_id,
viewedhints__team_id=team_id,
viewedhints__with_points=True,
)
pnlt = (100 - sum(map(lambda h: HINTPENALTY[h.order], hints))) / 100

Expand Down Expand Up @@ -147,15 +158,6 @@ async def viewed_problem_hints_get(ctf_id: int, jwt: RequireJwt):
return viewed_hints


@router.get("/completed")
async def completed_problem_get(jwt: RequireJwt):
team_id = jwt["team_id"]
problems = await Problem_Pydantic.from_queryset(
Problem.filter(solvedproblems__team_id=team_id, visible=True)
)
return problems


@router.get("/{ctf_id}")
async def ctf_get(ctf_id: int, response: Response):
problem = await Problem_Pydantic.from_queryset(
Expand Down
6 changes: 5 additions & 1 deletion src/pwncore/routes/ctf/start.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
from __future__ import annotations

from logging import getLogger

from fastapi import APIRouter, Response
import uuid
from tortoise.transactions import atomic
Expand All @@ -10,6 +12,7 @@
from pwncore.routes.auth import RequireJwt

router = APIRouter(tags=["ctf"])
logger = getLogger(__name__)


@atomic()
Expand Down Expand Up @@ -90,10 +93,11 @@ async def start_docker_container(ctf_id: int, response: Response, jwt: RequireJw
ports.append(port)
await Ports.create(port=port, container=db_container)

except Exception:
except Exception as err:
# Stop the container if failed to make a DB record
await container.stop()
await container.delete()
logger.exception("Error while starting", exc_info=err)

response.status_code = 500
return {"msg_code": config.msg_codes["db_error"]}
Expand Down