-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Реализовать эндпоинт регистрации #88
Добавлены модели базы данных - Акканут, Профиль, Хэш пароля и базовый функционал по созданию сущностей.
- Loading branch information
1 parent
9179c0f
commit 4c35daa
Showing
20 changed files
with
451 additions
and
8 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
68 changes: 68 additions & 0 deletions
68
...ons/versions/2023_09_13_1747-e5b03d5c76f9_add_account_profile_and_password_hash_tables.py
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,68 @@ | ||
"""add account, profile and password_hash tables | ||
Revision ID: e5b03d5c76f9 | ||
Revises: 8f2f6221d1de | ||
Create Date: 2023-09-13 17:47:54.104460+00:00 | ||
""" | ||
from alembic import op | ||
import sqlalchemy as sa | ||
|
||
|
||
# revision identifiers, used by Alembic. | ||
revision = "e5b03d5c76f9" | ||
down_revision = "8f2f6221d1de" | ||
branch_labels = None | ||
depends_on = None | ||
|
||
|
||
def upgrade() -> None: | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.create_table( | ||
"account", | ||
sa.Column("id", sa.Integer(), nullable=False), | ||
sa.Column("created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False), | ||
sa.Column("email", sa.String(), nullable=False), | ||
sa.Column("login", sa.String(), nullable=False), | ||
sa.Column("updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False), | ||
sa.PrimaryKeyConstraint("id"), | ||
sa.UniqueConstraint("email"), | ||
sa.UniqueConstraint("login"), | ||
) | ||
op.create_table( | ||
"password_hash", | ||
sa.Column("id", sa.Integer(), nullable=False), | ||
sa.Column("created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False), | ||
sa.Column("updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False), | ||
sa.Column("value", sa.LargeBinary(), nullable=False), | ||
sa.Column("account_id", sa.Integer(), nullable=False), | ||
sa.ForeignKeyConstraint( | ||
["account_id"], | ||
["account.id"], | ||
), | ||
sa.PrimaryKeyConstraint("id"), | ||
) | ||
op.create_table( | ||
"profile", | ||
sa.Column("id", sa.Integer(), nullable=False), | ||
sa.Column("avatar", sa.String(), nullable=True), | ||
sa.Column("created_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False), | ||
sa.Column("description", sa.String(), nullable=True), | ||
sa.Column("name", sa.String(), nullable=False), | ||
sa.Column("updated_at", sa.DateTime(), server_default=sa.text("now()"), nullable=False), | ||
sa.Column("account_id", sa.Integer(), nullable=False), | ||
sa.ForeignKeyConstraint( | ||
["account_id"], | ||
["account.id"], | ||
), | ||
sa.PrimaryKeyConstraint("id"), | ||
) | ||
# ### end Alembic commands ### | ||
|
||
|
||
def downgrade() -> None: | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.drop_table("profile") | ||
op.drop_table("password_hash") | ||
op.drop_table("account") | ||
# ### end Alembic commands ### |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,89 @@ | ||
"""Database models for account.""" | ||
|
||
from __future__ import annotations | ||
|
||
from datetime import datetime | ||
from typing import TYPE_CHECKING | ||
|
||
import bcrypt | ||
from sqlalchemy import DateTime, ForeignKey, func, Integer, LargeBinary, select, String | ||
from sqlalchemy.orm import Mapped, mapped_column | ||
|
||
from src.shared.database import Base | ||
from src.shared.exceptions import DuplicateEntityException | ||
|
||
|
||
if TYPE_CHECKING: | ||
from sqlalchemy.ext.asyncio import AsyncSession | ||
|
||
from src.auth.fields import Password | ||
from src.auth.schemas import NewAccount | ||
|
||
|
||
class Account(Base): # pylint: disable=too-few-public-methods | ||
"""Account database model.""" | ||
|
||
__tablename__ = "account" | ||
|
||
id: Mapped[int] = mapped_column(Integer, primary_key=True) # noqa: A003 | ||
|
||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.now()) | ||
email: Mapped[str] = mapped_column(String, nullable=False, unique=True) | ||
login: Mapped[str] = mapped_column(String, nullable=False, unique=True) | ||
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.now()) | ||
|
||
@staticmethod | ||
async def create(session: AsyncSession, account_data: NewAccount) -> Account: | ||
"""Create new account object.""" | ||
query = select(Account).where(Account.email == account_data.email) | ||
account_with_same_email = (await session.execute(query)).first() | ||
if account_with_same_email is not None: | ||
raise DuplicateEntityException( | ||
action="create Account", | ||
details="Provided email address already exists.", | ||
) | ||
|
||
query = select(Account).where(Account.login == account_data.login) | ||
account_with_same_login = (await session.execute(query)).first() | ||
if account_with_same_login is not None: | ||
raise DuplicateEntityException( | ||
action="create Account", | ||
details="Provided login already exists.", | ||
) | ||
|
||
account = Account(**account_data.dict(exclude={"password"})) | ||
session.add(account) | ||
await session.flush() | ||
return account | ||
|
||
|
||
class PasswordHash(Base): | ||
"""Password hash database model.""" | ||
|
||
__tablename__ = "password_hash" | ||
|
||
id: Mapped[int] = mapped_column(Integer, primary_key=True) # noqa: A003 | ||
|
||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.now()) | ||
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.now()) | ||
value: Mapped[bytes] = mapped_column(LargeBinary, nullable=False) | ||
|
||
# TODO: add uniqueness constraint since one account cannot have more than one password hash | ||
# and check other kind of constraints for other models | ||
account_id: Mapped[int] = mapped_column(ForeignKey("account.id")) | ||
|
||
@staticmethod # TODO: we cannot use this create method due to Password is a field and cannot be used outside of the schema | ||
async def create(session: AsyncSession, password: Password, account_id: int) -> None: | ||
"""Create a password hash object.""" | ||
hash_value = PasswordHash._generate_hash(password) | ||
password_hash = PasswordHash(value=hash_value, account_id=account_id) | ||
session.add(password_hash) | ||
await session.flush() | ||
return password_hash | ||
|
||
@staticmethod | ||
def _generate_hash(password: Password) -> bytes: | ||
"""Generate hash for password.""" | ||
salt = bcrypt.gensalt() | ||
byte_password = password.get_secret_value().encode("utf-8") | ||
return bcrypt.hashpw(byte_password, salt) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,28 @@ | ||
"""Controllers functions for account entity.""" | ||
|
||
from __future__ import annotations | ||
|
||
from typing import TYPE_CHECKING | ||
|
||
from src.account import schemas as account_schemas | ||
from src.account.models import Account, PasswordHash | ||
from src.auth import schemas | ||
from src.profile import schemas as profile_schemas | ||
from src.profile.models import Profile | ||
|
||
|
||
if TYPE_CHECKING: | ||
from sqlalchemy.ext.asyncio import AsyncSession | ||
|
||
from src.auth.schemas import NewAccountWithProfile | ||
|
||
|
||
async def create_account(request_data: NewAccountWithProfile, session: AsyncSession) -> schemas.AccountWithProfile: | ||
"""Create a new account with profile.""" | ||
account = await Account.create(session, request_data.account) | ||
profile = await Profile.create(session, request_data.profile, account_id=account.id) | ||
await PasswordHash.create(session, request_data.account.password, account_id=account.id) | ||
return schemas.AccountWithProfile( | ||
account=account_schemas.Account.from_orm(account), | ||
profile=profile_schemas.Profile.from_orm(profile), | ||
) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.