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

Add support for login #3

Open
wants to merge 7 commits into
base: main
Choose a base branch
from
Open
Changes from 1 commit
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
Prev Previous commit
Next Next commit
Authenticate user
  • Loading branch information
Dinika committed Jul 29, 2024
commit 78eface89aa1f67d5f46a78267b8702f5de5ef89
37 changes: 36 additions & 1 deletion expenses_server/main.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,23 @@
from fastapi import APIRouter, FastAPI
from http import HTTPStatus
from fastapi import APIRouter, Depends, FastAPI, HTTPException
from fastapi.responses import FileResponse
from fastapi.security import OAuth2PasswordRequestForm
from fastapi.staticfiles import StaticFiles
from passlib.context import CryptContext
from typing import Annotated
from sqlalchemy.orm import Session

from expenses_server.db_models.user import User
from expenses_server.dtos.users import UserToken
from expenses_server.utils import hash_password, verify_password

from .settings import settings

from .routes.accounts import router as account_router
from .routes.expenses import router as expense_router
from .routes.users import router as user_router
from expenses_server.db import get_db
from sqlalchemy.exc import NoResultFound

password_context = CryptContext(schemes=["bcrypt"], deprecated="auto")

@@ -20,6 +30,31 @@ async def root() -> FileResponse:
return response


@app.post("/token")
async def login(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
db_session: Session = Depends(get_db),
) -> UserToken:
try:
user = (
db_session.query(User)
.where(
User.username == form_data.username,
)
.one()
)
if not verify_password(form_data.password, user.password_hash):
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST,
detail="Incorrect username or password",
)
return UserToken(access_token=user.username, token_type="bearer")
except NoResultFound:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="Incorrect username or password"
)


base_router = APIRouter(prefix="/api")


21 changes: 0 additions & 21 deletions expenses_server/routes/users.py
Original file line number Diff line number Diff line change
@@ -20,24 +20,3 @@ async def read_user_current(
) -> User:
# TODO: Only accounts for user should be sent
return current_user


@router.post("/token")
async def login(
form_data: Annotated[OAuth2PasswordRequestForm, Depends()],
db_session: Session = Depends(get_db),
) -> UserToken:
try:
user = (
db_session.query(User)
.where(
User.username == form_data.username,
User.password_hash == hash_password(form_data.password),
)
.one()
)
return UserToken(access_token=user.username, token_type="bearer")
except NoResultFound as e:
raise HTTPException(
status_code=HTTPStatus.BAD_REQUEST, detail="Incorrect username or password"
)
11 changes: 5 additions & 6 deletions expenses_server/utils.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,16 @@
from getpass import getpass
import hashlib

from expenses_server.db import get_db
from expenses_server.db_models.user import User
from expenses_server.settings import settings
from expenses_server import main


def hash_password(password: str) -> str:
# TODO: Rename m
m = hashlib.sha256() # TODO: This should be consistent with settings.hash_algorithm
m.update((settings.password_seed + password).encode("utf8"))
return f"{settings.hash_algorithm}:{m.hexdigest()}"
return main.password_context.hash(password)


def verify_password(plain_password: str, hashed_password: str) -> bool:
return main.password_context.verify(plain_password, hashed_password)


def create_user(username: str) -> None: