Skip to content

Commit

Permalink
✨ feat: dia dos namorados
Browse files Browse the repository at this point in the history
  • Loading branch information
FelipeHardmann committed Jun 12, 2024
1 parent 1e9a700 commit 1426a9f
Show file tree
Hide file tree
Showing 9 changed files with 286 additions and 2 deletions.
7 changes: 7 additions & 0 deletions app/db/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -52,3 +52,10 @@ class Product(Base):
'category_id', ForeignKey('categories.id'), nullable=False
)
category = relationship('Category', back_populates='products')


class User(Base):
__tablename__ = 'users'
id = Column('id', Integer, primary_key=True, autoincrement=True)
username = Column('username', String, nullable=False, unique=True)
password = Column('password', String, nullable=False)
30 changes: 30 additions & 0 deletions app/migrations/versions/04e3ebe91adc_add_user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
"""add user
Revision ID: 04e3ebe91adc
Revises: bd7c85fac8d2
Create Date: 2024-06-12 03:16:23.993363
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = '04e3ebe91adc'
down_revision: Union[str, None] = 'bd7c85fac8d2'
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! ###
pass
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
pass
# ### end Alembic commands ###
36 changes: 36 additions & 0 deletions app/migrations/versions/bd7c85fac8d2_add_user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,36 @@
"""add user
Revision ID: bd7c85fac8d2
Revises: f484be150f6e
Create Date: 2024-06-04 20:26:11.474601
"""
from typing import Sequence, Union

from alembic import op
import sqlalchemy as sa


# revision identifiers, used by Alembic.
revision: str = 'bd7c85fac8d2'
down_revision: Union[str, None] = 'f484be150f6e'
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('id', sa.Integer(), autoincrement=True, nullable=False),
sa.Column('username', sa.String(), nullable=False),
sa.Column('password', sa.String(), nullable=False),
sa.PrimaryKeyConstraint('id'),
sa.UniqueConstraint('username')
)
# ### end Alembic commands ###


def downgrade() -> None:
# ### commands auto generated by Alembic - please adjust! ###
op.drop_table('users')
# ### end Alembic commands ###
14 changes: 14 additions & 0 deletions app/schemas/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
from app.schemas.base import CustomBaseModel
from pydantic import validator
import re


class User(CustomBaseModel):
username: str
password: str

@validator('username')
def validate_username(cls, v):
if not re.match('^([a-z]|[A-Z]|[0-9]|-|_|@)+$', v):
raise ValueError('Invalid Username')
return v
21 changes: 21 additions & 0 deletions app/test/schemas/test_user_schema.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
import pytest
from app.schemas.user import User


def test_user_schema():
user = User(
username='Felipe',
password='pass#'
)
assert user.dict() == {
'username': 'Felipe',
'password': 'pass#'
}


def test_user_schema_invalid_username():
with pytest.raises(ValueError):
user = User(
username='João#',
password='pass#'
)
50 changes: 50 additions & 0 deletions app/test/use_cases/test_user_use_cases.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,50 @@
import pytest
from passlib.context import CryptContext
from app.schemas.user import User
from app.db.models import User as UserModel
from app.use_cases.user import UserUseCases
from fastapi.exceptions import HTTPException


crypt_context = CryptContext(schemes=['sha256_crypt'])


def test_register_user(db_session):
user = User(
username='Felipe',
password='pass#'
)

uc = UserUseCases(db_session)
uc.register_user(user=user)

user_on_db = db_session.query(UserModel).first()
assert user_on_db is not None
assert user_on_db.username == user.username
assert crypt_context.verify(user.password, user_on_db.password)

db_session.delete(user_on_db)
db_session.commit()


def test_register_user_username_already_exists(db_session):
user_on_db = UserModel(
username='Felipe',
password=crypt_context.hash('pass#')
)

db_session.add(user_on_db)
db_session.commit()

uc = UserUseCases(db_session)

user = User(
username='Felipe',
password=crypt_context.hash('pass#')
)

with pytest.raises(HTTPException):
uc.register_user(user=user)

db_session.delete(user_on_db)
db_session.commit()
32 changes: 32 additions & 0 deletions app/use_cases/user.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
from sqlalchemy.orm import Session
from passlib.context import CryptContext
from sqlalchemy.exc import IntegrityError
from fastapi.exceptions import HTTPException
from fastapi import status
from app.schemas.user import User
from app.db.models import User as UserModel


crypt_context = CryptContext(schemes=['sha256_crypt'])


class UserUseCases:
def __init__(self, db_session: Session) -> None:
self.db_session = db_session

def register_user(self, user: User):
user_on_db = UserModel(
username=user.username,
password=crypt_context.hash(user.password)
)

self.db_session.add(user_on_db)

try:
self.db_session.commit()
except IntegrityError:
self.db_session.rollback()
raise HTTPException(
status_code=status.HTTP_400_BAD_REQUEST,
detail='Username already exists'
)
96 changes: 94 additions & 2 deletions poetry.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,8 @@ pytest = "^7.4.4"
alembic = "^1.13.1"
python-decouple = "^3.8"
httpx = "^0.26.0"
passlib = "^1.7.4"
python-jose = "^3.3.0"


[build-system]
Expand Down

0 comments on commit 1426a9f

Please sign in to comment.