Skip to content

Commit

Permalink
added logging for user ip and email on log-in
Browse files Browse the repository at this point in the history
Problem
Currently no audit trail for log ins

Solution
- added logging of email, date, and ip address when the user succeeds and fails log in

Ticket URL
https://mediform.atlassian.net/browse/MEDI-88

Documentation
NA

Tests Run
- make testapi
- tested that logs show in expected cases
  • Loading branch information
MadelaineJ committed Mar 18, 2024
1 parent 668c015 commit faa043f
Showing 1 changed file with 17 additions and 2 deletions.
19 changes: 17 additions & 2 deletions app/api/routes/login.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,8 @@
from typing import Any

from fastapi import APIRouter, Depends, HTTPException
from fastapi import APIRouter, Depends, HTTPException, Request
from sqlalchemy.orm import Session
from datetime import datetime

from api.schemas.users import UserLogin, UserLoginResponse
from api.models.user import get_user_by_email
Expand All @@ -12,31 +13,45 @@
import yaml

router = APIRouter()
logger = logging.getLogger(__name__)

@router.post("/login", status_code=200, response_model=UserLoginResponse, name="login")
def login_user(user: UserLogin) -> Any:
def login_user(user: UserLogin, request: Request) -> Any:
"""
Login a user if they provide a matching email and password to one found in the database,
otherwise return exceptions.
"""
client_host = request.client.host
# Determine which database to use based on the user group
if user.user_group and user.user_group in db_functions:
db_generator = db_functions[user.user_group]()
db = next(db_generator)
else:
logger.info(
f"User '{user.email}' has failed to log in at {datetime.now()} from IP address {client_host}"
)
raise HTTPException(status_code=400, detail="Invalid user group.")

found_user = get_user_by_email(db, str(user.email))
if found_user is None:
logger.info(
f"User '{user.email}' has failed to log in at {datetime.now()} from IP address {client_host}"
)
raise HTTPException(
status_code=401, detail="Unable to retrieve a user with those credentials."
)

if not verify_password(found_user.hashed_password, user.password):
logger.info(
f"User '{user.email}' has failed to log in at {datetime.now()} from IP address {client_host}"
)
raise HTTPException(
status_code=401, detail="Username and password do not match."
)

token = generate_auth_token(data={"sub": found_user.email}, user_group=user.user_group)
logger.info(
f"User '{user.email}' has successfully logged in at {datetime.now()} from IP address {client_host}"
)

return UserLoginResponse(access_token=token)

0 comments on commit faa043f

Please sign in to comment.