Skip to content

Commit

Permalink
Logging & admin creation revision
Browse files Browse the repository at this point in the history
  • Loading branch information
na-stewart committed Nov 4, 2024
1 parent e98608d commit 13d6fd2
Show file tree
Hide file tree
Showing 5 changed files with 27 additions and 11 deletions.
18 changes: 13 additions & 5 deletions sanic_security/authentication.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@
ExpiredError,
)
from sanic_security.models import Account, AuthenticationSession, Role, TwoStepSession
from sanic_security.utils import get_ip

"""
Copyright (c) 2020-present Nicholas Aidan Stewart
Expand Down Expand Up @@ -75,15 +76,15 @@ async def register(
raise CredentialsError(
"An account with this phone number may already exist.", 409
)
validate_password(request.form.get("password"))
account = await Account.create(
email=email_lower,
username=request.form.get("username"),
password=password_hasher.hash(request.form.get("password")),
password=password_hasher.hash(validate_password(request.form.get("password"))),
phone=request.form.get("phone"),
verified=verified,
disabled=disabled,
)
logger.info(f"Client {get_ip(request)} has registered account {account.id}.")
return account


Expand Down Expand Up @@ -122,6 +123,7 @@ async def login(
account.password = password_hasher.hash(password)
await account.save(update_fields=["password"])
account.validate()
logger.info(f"Client {get_ip(request)} has logged into account {account.id}.")
return await AuthenticationSession.new(
request, account, requires_second_factor=require_second_factor
)
Expand Down Expand Up @@ -149,6 +151,9 @@ async def logout(request: Request) -> AuthenticationSession:
raise DeactivatedError("Already logged out.", 403)
authentication_session.active = False
await authentication_session.save(update_fields=["active"])
logger.info(
f"Client {get_ip(request)} has logged out{'' if authentication_session.anonymous else f' of account {authentication_session.bearer.id}.'}."
)
return authentication_session


Expand Down Expand Up @@ -180,6 +185,9 @@ async def fulfill_second_factor(request: Request) -> AuthenticationSession:
await two_step_session.check_code(request, request.form.get("code"))
authentication_session.requires_second_factor = False
await authentication_session.save(update_fields=["requires_second_factor"])
logger.info(
f"Client {get_ip(request)} has fulfilled session {authentication_session.id} second factor."
)
return authentication_session


Expand Down Expand Up @@ -276,12 +284,12 @@ def create_initial_admin_account(app: Sanic) -> None:
@app.listener("before_server_start")
async def create(app, loop):
try:
role = await Role.filter(name="Head Admin").get()
role = await Role.filter(name="Admin").get()
except DoesNotExist:
role = await Role.create(
description="Has root abilities, assign sparingly.",
permissions="*:*",
name="Head Admin",
name="Admin",
)
try:
account = await Account.filter(
Expand All @@ -293,7 +301,7 @@ async def create(app, loop):
logger.warning("Initial admin account role has been reinstated.")
except DoesNotExist:
account = await Account.create(
username="Head-Admin",
username="Admin",
email=security_config.INITIAL_ADMIN_EMAIL,
password=password_hasher.hash(security_config.INITIAL_ADMIN_PASSWORD),
verified=True,
Expand Down
2 changes: 2 additions & 0 deletions sanic_security/authorization.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import functools
from fnmatch import fnmatch

from sanic.log import logger
from sanic.request import Request
from tortoise.exceptions import DoesNotExist

Expand Down Expand Up @@ -119,6 +120,7 @@ async def assign_role(
description=description, permissions=permissions, name=name
)
await account.roles.add(role)
logger.info(f"Role {role.id} has been assigned to account {account.id}.")
return role


Expand Down
14 changes: 9 additions & 5 deletions sanic_security/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -142,6 +142,7 @@ async def disable(self):
else:
self.disabled = True
await self.save(update_fields=["disabled"])
logger.info(f"Account {self.id} has been disabled.")

@property
def json(self) -> dict:
Expand Down Expand Up @@ -319,6 +320,7 @@ async def deactivate(self):
if self.active:
self.active = False
await self.save(update_fields=["active"])
logger.info(f"Session {self.id} has been deactivated.")
else:
raise DeactivatedError("Session is already deactivated.", 403)

Expand Down Expand Up @@ -513,13 +515,12 @@ async def check_code(self, request: Request, code: str) -> None:
"Your code does not match verification session code."
)
else:
logger.warning(
f"Client ({get_ip(request)}) has maxed out on session challenge attempts"
)
raise MaxedOutChallengeError()
else:
self.active = False
await self.save(update_fields=["active"])
logger.info(
f"Client {get_ip(request)} has completed session {self.id} challenge."
)
await self.deactivate()

@classmethod
async def new(cls, request: Request, account: Account, **kwargs):
Expand Down Expand Up @@ -633,6 +634,9 @@ async def refresh(self, request: Request):
):
self.active = False
await self.save(update_fields=["active"])
logger.info(
f"Client {get_ip(request)} has refreshed authentication session."
)
return await self.new(request, self.bearer, True)
else:
raise e
Expand Down
2 changes: 1 addition & 1 deletion sanic_security/test/tests.py
Original file line number Diff line number Diff line change
Expand Up @@ -255,7 +255,7 @@ def test_initial_admin_login(self):
permitted_authorization_response = self.client.post(
"http://127.0.0.1:8000/api/test/auth/roles",
data={
"role": "Head Admin",
"role": "Admin",
"permissions_required": "perm1:create,add, perm2:*",
},
)
Expand Down
2 changes: 2 additions & 0 deletions sanic_security/verification.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
import functools
from contextlib import suppress

from sanic.log import logger
from sanic.request import Request

from sanic_security.exceptions import (
Expand Down Expand Up @@ -156,6 +157,7 @@ async def verify_account(request: Request) -> TwoStepSession:
await two_step_session.check_code(request, request.form.get("code"))
two_step_session.bearer.verified = True
await two_step_session.bearer.save(update_fields=["verified"])
logger.info(f"Account {two_step_session.bearer} has been verified.")
return two_step_session


Expand Down

0 comments on commit 13d6fd2

Please sign in to comment.