Skip to content

Commit

Permalink
Manually fix up remaining ruff violations
Browse files Browse the repository at this point in the history
  • Loading branch information
wjdp committed Jul 28, 2023
1 parent 54c3c03 commit 00732b9
Show file tree
Hide file tree
Showing 12 changed files with 43 additions and 41 deletions.
5 changes: 3 additions & 2 deletions src/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,8 @@

# Initialize Sentry, want to do as early as possible
init_sentry()
from lumina.app import app
from mangum import Mangum

from lumina.app import app # noqa: E402
from mangum import Mangum # noqa: E402

handler = Mangum(app)
12 changes: 6 additions & 6 deletions src/lumina/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -55,11 +55,11 @@ async def __call__(self, request: Request) -> AuthenticatedToken | None:
if credentials:
try:
return decode_jwt(credentials.credentials)
except jwt.InvalidTokenError:
except jwt.InvalidTokenError as e:
raise HTTPException(
status_code=HTTPStatus.UNAUTHORIZED,
detail="Invalid or expired token",
)
) from e
elif self.optional:
return None
else:
Expand All @@ -69,20 +69,20 @@ async def __call__(self, request: Request) -> AuthenticatedToken | None:


def require_member(
authenticated_member=Depends(JWTBearer()),
authenticated_member=Depends(JWTBearer()), # noqa B008
) -> MemberModel:
"""Get member if token is provided, otherwise raise exception."""
try:
return lumina.database.operations.get_member(authenticated_member.id)
except lumina.database.operations.ResultNotFound:
except lumina.database.operations.ResultNotFound as e:
raise HTTPException(
status_code=HTTPStatus.UNAUTHORIZED,
detail="Member no longer exists",
)
) from e


def optional_member(
authenticated_member=Depends(JWTBearer(optional=True)),
authenticated_member=Depends(JWTBearer(optional=True)), # noqa B008
) -> MemberModel | None:
"""Get member if token is provided, otherwise return None."""
if not authenticated_member:
Expand Down
2 changes: 1 addition & 1 deletion src/lumina/database/table.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,9 @@

from lumina.config import settings
from lumina.database.connection import get_dynamo_db
from mypy_boto3_dynamodb.service_resource import Table

MEMBER_TABLE_NAME_PREFIX = "LuminaMember"
from mypy_boto3_dynamodb.service_resource import Table


def get_table_name() -> str:
Expand Down
2 changes: 1 addition & 1 deletion src/lumina/emails/send.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,7 +61,7 @@ def send_email(
# Display an error if something goes wrong.
except ClientError as e:
error_message = e.response.get("Error", {}).get("Message", "")
log.error("Failed to send email: %s", error_message)
log.exception("Failed to send email")
if "Email address not verified" in error_message:
raise EmailAddressUnverified from e
raise EmailError from e
Expand Down
3 changes: 1 addition & 2 deletions src/lumina/endpoints/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,5 +33,4 @@ def check_auth_optional(
):
if member:
return AuthCheckOptionalResponse(id=member.id, expires_at=token.expires_at)
else:
return AuthCheckOptionalResponse()
return AuthCheckOptionalResponse()
12 changes: 8 additions & 4 deletions src/lumina/endpoints/member.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,8 +56,10 @@ def check_member(id: str):
try:
member = lumina.database.operations.get_member(id)
return MemberPublicResponse(id=member.pk, masked_email=mask_email(member.email))
except lumina.database.operations.ResultNotFound:
raise HTTPException(status_code=HTTPStatus.NOT_FOUND, detail="Member not found")
except lumina.database.operations.ResultNotFound as e:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Member not found"
) from e


@router.post(
Expand Down Expand Up @@ -146,7 +148,9 @@ def send_token_link_for_member(id: str):
auth_url=auth.get_auth_url(id),
),
)
except lumina.database.operations.ResultNotFound:
raise HTTPException(status_code=HTTPStatus.NOT_FOUND, detail="Member not found")
except lumina.database.operations.ResultNotFound as e:
raise HTTPException(
status_code=HTTPStatus.NOT_FOUND, detail="Member not found"
) from e

return "OK"
6 changes: 2 additions & 4 deletions src/lumina/endpoints/submissions.py
Original file line number Diff line number Diff line change
Expand Up @@ -90,8 +90,7 @@ def create_show_submission(
require_submitter_or_member(submission, member)
if member:
return member.id
else:
return "not authenticated, but it's fine"
return "not authenticated, but it's fine"


@router.post("/bio")
Expand All @@ -102,5 +101,4 @@ def create_bio_submission(
require_submitter_or_member(submission, member)
if member:
return member.id
else:
return "not authenticated, but it's fine"
return "not authenticated, but it's fine"
7 changes: 5 additions & 2 deletions src/lumina/github/webhooks.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,11 @@ def get_webhook_secret() -> str:
end
def verify_signature(payload_body)
signature = 'sha256=' + OpenSSL::HMAC.hexdigest(OpenSSL::Digest.new('sha256'), ENV['SECRET_TOKEN'], payload_body)
return halt 500, "Signatures didn't match!" unless Rack::Utils.secure_compare(signature, request.env['HTTP_X_HUB_SIGNATURE_256'])
signature = 'sha256=' + OpenSSL::HMAC.hexdigest(
OpenSSL::Digest.new('sha256'), ENV['SECRET_TOKEN'], payload_body
)
return halt 500, "Signatures didn't match!" unless
Rack::Utils.secure_compare(signature, request.env['HTTP_X_HUB_SIGNATURE_256'])
end
"""

Expand Down
30 changes: 14 additions & 16 deletions src/lumina/health.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import contextlib
import logging
from http import HTTPStatus

Expand Down Expand Up @@ -28,15 +29,15 @@ def check_ssm() -> HealthCheckCondition:
timestamp=dates.now(),
message="Parameter not found",
)
except botocore.exceptions.ClientError as e:
log.error(e)
except botocore.exceptions.ClientError:
log.exception("Could not get parameter from SSM")
return HealthCheckCondition(
ok=False,
timestamp=dates.now(),
message="ClientError",
)
except Exception as e:
log.error(e)
except Exception:
log.exception("Unknown error getting parameter from SSM")
return HealthCheckCondition(
ok=False,
timestamp=dates.now(),
Expand All @@ -47,24 +48,21 @@ def check_ssm() -> HealthCheckCondition:
def check_dynamodb() -> HealthCheckCondition:
try:
# Check if dynamodb is available by attempting fetch of a member
try:
with contextlib.suppress(ResultNotFound):
operations.get_member("fred_bloggs")
except ResultNotFound:
# We don't expect member to exist
pass
return HealthCheckCondition(
ok=True,
timestamp=dates.now(),
)
except botocore.exceptions.ClientError as e:
log.error(e)
except botocore.exceptions.ClientError:
log.exception("Could not get member from DynamoDB")
return HealthCheckCondition(
ok=False,
timestamp=dates.now(),
message="ClientError",
)
except Exception as e:
log.error(e)
except Exception:
log.exception("Unknown error getting member from DynamoDB")
return HealthCheckCondition(
ok=False,
timestamp=dates.now(),
Expand All @@ -86,15 +84,15 @@ def check_github() -> HealthCheckCondition:
timestamp=dates.now(),
message="Bad credentials",
)
except botocore.exceptions.ClientError as e:
log.error(e)
except botocore.exceptions.ClientError:
log.exception("Could not get credentials from SSM")
return HealthCheckCondition(
ok=False,
timestamp=dates.now(),
message="Cannot get credentials",
)
except Exception as e:
log.error(e)
except Exception:
log.exception("Unknown error getting content repo from GitHub")
return HealthCheckCondition(
ok=False,
timestamp=dates.now(),
Expand Down
2 changes: 1 addition & 1 deletion src/lumina/util/types.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@


class BaseModelProtocol(Protocol):
def dict(
def dict( # noqa: PLR0913
self,
*,
include: Union["AbstractSetIntStr", "MappingIntStrAny"] = None,
Expand Down
1 change: 0 additions & 1 deletion tests/unit/lumina/database/test_operations.py
Original file line number Diff line number Diff line change
Expand Up @@ -60,7 +60,6 @@ def test_set_member_email_verified(fred_bloggs):
with freezegun.freeze_time("2020-01-01 12:34:56"):
operations.set_member_email_verified(fred_bloggs.pk)
get_member = operations.get_member(fred_bloggs.pk)
print(get_member.dict())
assert get_member.email_verified is True
assert get_member.email_verified_at == datetime.datetime(
2020, 1, 1, 12, 34, 56, tzinfo=datetime.timezone.utc
Expand Down
2 changes: 1 addition & 1 deletion tests/unit/lumina/util/test_email.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,4 +25,4 @@ def test_mask_email(self, input, expected):
)
def test_raises_value_error(self, input):
with pytest.raises(ValueError):
print(email.mask_email(input))
email.mask_email(input)

0 comments on commit 00732b9

Please sign in to comment.