Skip to content

Commit

Permalink
ruff linting
Browse files Browse the repository at this point in the history
  • Loading branch information
TawneeOwl committed Aug 27, 2024
1 parent f4a1f7b commit 2fcd5ad
Show file tree
Hide file tree
Showing 15 changed files with 171 additions and 82 deletions.
27 changes: 20 additions & 7 deletions app/auth/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,9 +19,11 @@

oauth2_scheme = OAuth2PasswordBearer(tokenUrl="token")


def verify_password(plain_password, hashed_password):
return argon2.verify(plain_password, hashed_password)


def get_password_hash(password):
"""
This function runs argon2 salting and hashing via passlib.
Expand All @@ -35,11 +37,13 @@ def get_password_hash(password):
"""
return argon2.hash(password)


def get_user(session, username: str):
user = session.get(Users, username)

return user


def authenticate_user(session, username: str, password: str) -> str | Users | bool:
"""
This function returns the user if they are authenticated against their
Expand All @@ -62,7 +66,10 @@ def authenticate_user(session, username: str, password: str) -> str | Users | bo
return False
return user

def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None) -> Token:

def create_access_token(
data: dict, expires_delta: Union[timedelta, None] = None
) -> Token:
"""
Creates the JWT access token with an expiry time.
Expand All @@ -81,13 +88,18 @@ def create_access_token(data: dict, expires_delta: Union[timedelta, None] = None
if expires_delta:
expire = datetime.now(timezone.utc) + expires_delta
else:
expire = datetime.now(timezone.utc) + timedelta(minutes=ACCESS_TOKEN_EXPIRE_MINUTES)
expire = datetime.now(timezone.utc) + timedelta(
minutes=ACCESS_TOKEN_EXPIRE_MINUTES
)
to_encode.update({"exp": expire})
encoded_jwt = jwt.encode(to_encode, SECRET_KEY, algorithm=ALGORITHM)
return encoded_jwt


async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)], session: Annotated[Session, Depends(get_session)]):
async def get_current_user(
token: Annotated[str, Depends(oauth2_scheme)],
session: Annotated[Session, Depends(get_session)],
):
"""
Checks the current user token to return a user.
Expand Down Expand Up @@ -118,12 +130,13 @@ async def get_current_user(token: Annotated[str, Depends(oauth2_scheme)], sessio
raise credentials_exception
return user


async def get_current_active_user(
current_user: Annotated[Users, Depends(get_current_user)]
current_user: Annotated[Users, Depends(get_current_user)],
):
if current_user.disabled:
raise HTTPException(
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User Disabled",
)
status_code=status.HTTP_401_UNAUTHORIZED,
detail="User Disabled",
)
return current_user
2 changes: 1 addition & 1 deletion app/config/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,4 +15,4 @@ class Config(object):

SENTRY_DSN = os.environ.get("SENTRY_DSN")

SECRET_KEY = os.environ.get("SECRET_KEY","TEST_KEY")
SECRET_KEY = os.environ.get("SECRET_KEY", "TEST_KEY")
2 changes: 1 addition & 1 deletion app/config/docs.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,5 +19,5 @@
"name": "MIT Licence",
"url": "https://github.com/ministryofjustice/laa-civil-case-api/blob/main/LICENSE",
},
"docs_url": "/"
"docs_url": "/",
}
6 changes: 2 additions & 4 deletions app/db/migrations/env.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
# this is the Alembic Config object, which provides
# access to the values within the .ini file in use.
config = context.config
config.set_main_option('sqlalchemy.url', db_url)
config.set_main_option("sqlalchemy.url", db_url)

# Interpret the config file for Python logging.
# This line sets up loggers basically.
Expand Down Expand Up @@ -71,9 +71,7 @@ def run_migrations_online() -> None:
)

with connectable.connect() as connection:
context.configure(
connection=connection, target_metadata=target_metadata
)
context.configure(connection=connection, target_metadata=target_metadata)

with context.begin_transaction():
context.run_migrations()
Expand Down
22 changes: 12 additions & 10 deletions app/db/migrations/versions/2a0a7fdef0f6_add_users_to_db.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
Create Date: 2024-08-19 12:17:26.026339
"""

from typing import Sequence, Union

from alembic import op
Expand All @@ -13,26 +14,27 @@


# revision identifiers, used by Alembic.
revision: str = '2a0a7fdef0f6'
down_revision: Union[str, None] = '806702adc8af'
revision: str = "2a0a7fdef0f6"
down_revision: Union[str, None] = "806702adc8af"
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('users',
sa.Column('username', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('hashed_password', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('email', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('full_name', sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column('disabled', sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint('username')
op.create_table(
"users",
sa.Column("username", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("hashed_password", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("email", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("full_name", sqlmodel.sql.sqltypes.AutoString(), nullable=True),
sa.Column("disabled", sa.Boolean(), nullable=True),
sa.PrimaryKeyConstraint("username"),
)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('users')
op.drop_table("users")
# ### end Alembic commands ###
47 changes: 36 additions & 11 deletions app/db/migrations/versions/806702adc8af_init.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
"""init
Revision ID: 806702adc8af
Revises:
Revises:
Create Date: 2024-07-22 12:54:12.318505
"""

from typing import Sequence, Union

from alembic import op
Expand All @@ -13,27 +14,51 @@


# revision identifiers, used by Alembic.
revision: str = '806702adc8af'
revision: str = "806702adc8af"
down_revision: Union[str, None] = None
branch_labels: Union[str, Sequence[str], None] = None
depends_on: Union[str, Sequence[str], None] = None


def upgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.create_table('case',
sa.Column('category', sa.Enum('aap', 'med', 'com', 'crm', 'deb', 'disc', 'edu', 'mat', 'fmed', 'hou', 'immas', 'mhe', 'pl', 'pub', 'wb', 'mosl', 'hlpas', name='categories'), nullable=False),
sa.Column('name', sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column('id', sa.Integer(), nullable=False),
sa.Column('time', sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint('id')
op.create_table(
"case",
sa.Column(
"category",
sa.Enum(
"aap",
"med",
"com",
"crm",
"deb",
"disc",
"edu",
"mat",
"fmed",
"hou",
"immas",
"mhe",
"pl",
"pub",
"wb",
"mosl",
"hlpas",
name="categories",
),
nullable=False,
),
sa.Column("name", sqlmodel.sql.sqltypes.AutoString(), nullable=False),
sa.Column("id", sa.Integer(), nullable=False),
sa.Column("time", sa.DateTime(), nullable=False),
sa.PrimaryKeyConstraint("id"),
)
op.create_index(op.f('ix_case_category'), 'case', ['category'], unique=False)
op.create_index(op.f("ix_case_category"), "case", ["category"], unique=False)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_index(op.f('ix_case_category'), table_name='case')
op.drop_table('case')
op.drop_index(op.f("ix_case_category"), table_name="case")
op.drop_table("case")
# ### end Alembic commands ###
2 changes: 1 addition & 1 deletion app/models/__init__.py
Original file line number Diff line number Diff line change
@@ -1,2 +1,2 @@
from .cases import Case # noqa: F401
from .users import Users # noqa: F401
from .users import Users # noqa: F401
2 changes: 1 addition & 1 deletion app/models/categories.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,4 @@ class Categories(str, Enum):
pub = "Public law"
wb = "Welfare benefits"
mosl = "Modern slavery"
hlpas = "Housing Loss Prevention Advice Service"
hlpas = "Housing Loss Prevention Advice Service"
6 changes: 6 additions & 0 deletions app/models/users.py
Original file line number Diff line number Diff line change
@@ -1,20 +1,26 @@
from typing import Union
from sqlmodel import Field, SQLModel


class Token(SQLModel):
"""JSON Web Token (JWT) provided to the user after authentication."""

access_token: str
token_type: str


class TokenData(SQLModel):
"""TokenData links the JWT token to the username"""

username: Union[str, None] = None


class Users(SQLModel, table=True):
"""
Users are required to be authenticated to use some functionality of the API.
Disabled users are unable to authenticate to receive a token.
"""

username: str = Field(primary_key=True)
hashed_password: Union[str, None] = None
email: Union[str, None] = None
Expand Down
11 changes: 8 additions & 3 deletions app/routers/case_information.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,7 +10,7 @@
prefix="/cases",
tags=["cases"],
responses={404: {"description": "Not found"}},
dependencies=[Depends(get_current_active_user)]
dependencies=[Depends(get_current_active_user)],
)


Expand All @@ -34,8 +34,13 @@ def generate_id():

@router.post("/", tags=["cases"], response_model=Case)
def create_case(request: CaseRequest, session: Session = Depends(get_session)):
case = Case(category=request.category, time=datetime.now(), name=request.name, id=generate_id())
case = Case(
category=request.category,
time=datetime.now(),
name=request.name,
id=generate_id(),
)
session.add(case)
session.commit()
session.refresh(case)
return case
return case
6 changes: 5 additions & 1 deletion app/routers/security.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,11 @@

from fastapi import APIRouter, Depends, HTTPException, status
from fastapi.security import OAuth2PasswordRequestForm
from app.auth.security import create_access_token, authenticate_user, ACCESS_TOKEN_EXPIRE_MINUTES
from app.auth.security import (
create_access_token,
authenticate_user,
ACCESS_TOKEN_EXPIRE_MINUTES,
)
from app.models.users import Token
from sqlmodel import Session

Expand Down
26 changes: 16 additions & 10 deletions bin/add_users.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,19 +2,20 @@
import os

# Add the parent directory to sys.path
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), '..')))
sys.path.append(os.path.abspath(os.path.join(os.path.dirname(__file__), "..")))

from app.db import get_session
from app.models.users import Users
from app.auth.security import get_password_hash
import logging


def add_users(users_list_dict: dict):
"""
This function creates new users in the spun up local database
Args:
users_list_dict: Should contain a list of dictionary
users_list_dict: Should contain a list of dictionary
usernames and plain text passwords for users
Logs:
Expand All @@ -24,12 +25,14 @@ def add_users(users_list_dict: dict):
"""
with next(get_session()) as session:
for user_info in users_list_dict:
username = user_info.get('username')
password = user_info.get('password')
disabled = user_info.get('disabled')
username = user_info.get("username")
password = user_info.get("password")
disabled = user_info.get("disabled")

if not username or not password:
logging.warning(f"Skipping user with missing username or password: {user_info}")
logging.warning(
f"Skipping user with missing username or password: {user_info}"
)
continue

# Check if the username already exists
Expand All @@ -39,14 +42,17 @@ def add_users(users_list_dict: dict):
continue

password = get_password_hash(password)
new_user = Users(username=username, hashed_password=password, disabled=disabled)
new_user = Users(
username=username, hashed_password=password, disabled=disabled
)
session.add(new_user)

session.commit()


users_to_add = [
{'username': 'cla_admin', 'password': 'cla_admin', 'disabled': False},
{'username': 'janedoe', 'password': 'password', 'disabled': True}
{"username": "cla_admin", "password": "cla_admin", "disabled": False},
{"username": "janedoe", "password": "password", "disabled": True},
]

add_users(users_to_add)
add_users(users_to_add)
Loading

0 comments on commit 2fcd5ad

Please sign in to comment.