-
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
045eace
commit 383994f
Showing
19 changed files
with
445 additions
and
5 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
migrations/versions/2023_08_12_1020-577aab14d99c_add_account_password_profile.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 password profile | ||
Revision ID: 577aab14d99c | ||
Revises: 8f2f6221d1de | ||
Create Date: 2023-08-12 10:20:29.332462+00:00 | ||
""" | ||
from alembic import op | ||
import sqlalchemy as sa | ||
|
||
|
||
# revision identifiers, used by Alembic. | ||
revision = "577aab14d99c" | ||
down_revision = "8f2f6221d1de" | ||
branch_labels = None | ||
depends_on = None | ||
|
||
|
||
def upgrade() -> None: | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.create_table( | ||
"accounts", | ||
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_hashes", | ||
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"], | ||
["accounts.id"], | ||
), | ||
sa.PrimaryKeyConstraint("id"), | ||
) | ||
op.create_table( | ||
"profiles", | ||
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"], | ||
["accounts.id"], | ||
), | ||
sa.PrimaryKeyConstraint("id"), | ||
) | ||
# ### end Alembic commands ### | ||
|
||
|
||
def downgrade() -> None: | ||
# ### commands auto generated by Alembic - please adjust! ### | ||
op.drop_table("profiles") | ||
op.drop_table("password_hashes") | ||
op.drop_table("accounts") | ||
# ### 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,82 @@ | ||
"""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__ = "accounts" | ||
|
||
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.""" | ||
accounts_with_same_email = await session.execute(select(Account).filter_by(email=account_data.email)) | ||
accounts_with_same_login = await session.execute(select(Account).filter_by(login=account_data.login)) | ||
if accounts_with_same_email.all(): | ||
raise DuplicateEntityException( | ||
action="create Account", | ||
details="Provided email address already exists.", | ||
) | ||
|
||
if accounts_with_same_login.all(): | ||
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_hashes" | ||
|
||
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) | ||
|
||
account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id")) | ||
|
||
@staticmethod | ||
async def create(session: AsyncSession, password: Password, account_id: int) -> None: | ||
"""Create a password hash object.""" | ||
password_hash = PasswordHash.create_password_hash(password) | ||
obj = PasswordHash(value=password_hash, account_id=account_id) | ||
session.add(obj) | ||
await session.flush() | ||
|
||
@staticmethod | ||
def create_password_hash(password: Password) -> bytes: | ||
"""Generate hash for password.""" | ||
salt = bcrypt.gensalt() | ||
byte_password = str(password).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,29 @@ | ||
"""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(session: AsyncSession, request_data: NewAccountWithProfile) -> schemas.AccountWithProfile: | ||
"""Create a new account with profile.""" | ||
account = await Account.create(session, request_data.account) | ||
profile_data = request_data.profile | ||
password = request_data.account.password | ||
profile = await Profile.create(session, profile_data, account_id=account.id) | ||
await PasswordHash.create(session, 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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,39 @@ | ||
"""Database models for profile.""" | ||
from __future__ import annotations | ||
|
||
from datetime import datetime | ||
from typing import TYPE_CHECKING | ||
|
||
from sqlalchemy import DateTime, ForeignKey, func, Integer, String | ||
from sqlalchemy.orm import Mapped, mapped_column | ||
|
||
from src.shared.database import Base | ||
|
||
|
||
if TYPE_CHECKING: | ||
from sqlalchemy.ext.asyncio import AsyncSession | ||
|
||
from src.auth.schemas import _NewProfile | ||
|
||
|
||
class Profile(Base): # pylint: disable=too-few-public-methods | ||
"""Profile database model.""" | ||
|
||
__tablename__ = "profiles" | ||
|
||
id: Mapped[int] = mapped_column(Integer, primary_key=True) # noqa: A003 | ||
avatar: Mapped[str | None] = mapped_column(String) | ||
created_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.now()) | ||
description: Mapped[String | None] = mapped_column(String) | ||
name: Mapped[str] = mapped_column(String, nullable=False) | ||
updated_at: Mapped[datetime] = mapped_column(DateTime, nullable=False, server_default=func.now()) | ||
|
||
account_id: Mapped[int] = mapped_column(ForeignKey("accounts.id")) | ||
|
||
@staticmethod | ||
async def create(session: AsyncSession, profile_data: _NewProfile, account_id: int) -> Profile: | ||
"""Create new profile object.""" | ||
profile = Profile(**profile_data.dict(), account_id=account_id) | ||
session.add(profile) | ||
await session.flush() | ||
return 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.