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

added logging for user ip and email on log-in #133

Merged
merged 1 commit into from
Mar 18, 2024
Merged
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
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}' login attempt failed due to: invalid user group 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}' login attempt failed due to: no user found with those credentials 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}' login attempt failed due to: mismatched user and password 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)