Skip to content

Commit

Permalink
Fix linting errors in domain/accounts
Browse files Browse the repository at this point in the history
  • Loading branch information
shrir committed Dec 7, 2024
1 parent 9d7ce89 commit 75c443d
Show file tree
Hide file tree
Showing 7 changed files with 28 additions and 81 deletions.
4 changes: 2 additions & 2 deletions src/app/domain/accounts/controllers/access.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,11 @@

from __future__ import annotations

from typing import Annotated
from datetime import timedelta
from typing import Annotated

from advanced_alchemy.utils.text import slugify
from litestar import Controller, Request, Response, get, post, patch
from litestar import Controller, Request, Response, get, patch, post
from litestar.di import Provide
from litestar.enums import RequestEncodingType
from litestar.params import Body
Expand Down
13 changes: 4 additions & 9 deletions src/app/domain/accounts/controllers/tenant.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,29 +2,24 @@

from __future__ import annotations

from typing import Annotated, TYPE_CHECKING
from typing import TYPE_CHECKING, Annotated

from advanced_alchemy.utils.text import slugify
from litestar import Controller, Request, Response, get, post, patch, delete
from litestar import Controller, delete, get, patch, post
from litestar.di import Provide
from litestar.enums import RequestEncodingType
from litestar.params import Body
from litestar.security.jwt import OAuth2Login

from app.db.models import User as UserModel # noqa: TCH001
from app.domain.accounts import urls
from app.domain.accounts.dependencies import provide_tenants_service
from app.domain.accounts.guards import auth, requires_active_user, requires_superuser
from app.domain.accounts.guards import requires_active_user, requires_superuser
from app.domain.accounts.schemas import Tenant, TenantCreate, TenantUpdate
from app.domain.accounts.services import TenantService

if TYPE_CHECKING:
from uuid import UUID

from advanced_alchemy.service.pagination import OffsetPagination
from litestar.params import Dependency, Parameter
from litestar.params import Parameter

from app.lib.dependencies import FilterTypes


class TenantController(Controller):
Expand Down
51 changes: 4 additions & 47 deletions src/app/domain/accounts/dependencies.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,11 @@

from typing import TYPE_CHECKING, Any

from sqlalchemy.orm import joinedload, load_only, selectinload
from sqlalchemy.orm import joinedload, selectinload

from app.db.models import Role, Team, TeamMember, UserRole
from app.db.models import Role, UserRole
from app.db.models import User as UserModel
from app.domain.accounts.services import RoleService, UserRoleService, UserService, TenantService
from app.domain.accounts.services import RoleService, TenantService, UserRoleService, UserService

if TYPE_CHECKING:
from collections.abc import AsyncGenerator
Expand All @@ -34,50 +34,7 @@ async def provide_users_service(db_session: AsyncSession) -> AsyncGenerator[User
"""Construct repository and service objects for the request."""
async with UserService.new(
session=db_session,
load=[
"""
TODO: Enable when oauth is implemented
selectinload(UserModel.oauth_accounts),
"""
"""
TODO: Enable when roles are fully implemented
selectinload(UserModel.roles).options(joinedload(UserRole.role, innerjoin=True)),
selectinload(UserModel.teams).options(
joinedload(TeamMember.team, innerjoin=True).options(load_only(Team.name)),
),
""",
],
) as service:
yield service


async def provide_roles_service(db_session: AsyncSession | None = None) -> AsyncGenerator[RoleService, None]:
"""Provide roles service.
Args:
db_session (AsyncSession | None, optional): current database session. Defaults to None.
Returns:
RoleService: A role service object
"""
async with RoleService.new(
session=db_session,
load=selectinload(Role.users).options(joinedload(UserRole.user, innerjoin=True)),
) as service:
yield service


async def provide_user_roles_service(db_session: AsyncSession | None = None) -> AsyncGenerator[UserRoleService, None]:
"""Provide user roles service.
Args:
db_session (AsyncSession | None, optional): current database session. Defaults to None.
Returns:
UserRoleService: A user role service object
"""
async with UserRoleService.new(
session=db_session,
load=[],
) as service:
yield service

Expand Down
10 changes: 4 additions & 6 deletions src/app/domain/accounts/repositories.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,14 @@
from __future__ import annotations

from typing import TYPE_CHECKING, Any
from uuid import UUID
from uuid import UUID # noqa: TCH003

from advanced_alchemy.repository import SQLAlchemyAsyncRepository, SQLAlchemyAsyncSlugRepository
from advanced_alchemy.repository import SQLAlchemyAsyncSlugRepository
from sqlalchemy import ColumnElement, select
from sqlalchemy.orm import joinedload, InstrumentedAttribute
from sqlalchemy import select

from app.db.models import Role, User, UserRole, Tenant
from app.db.models import Role, Tenant, User, UserRole

if TYPE_CHECKING:
from advanced_alchemy.filters import FilterTypes
from advanced_alchemy.repository._util import LoadSpec


Expand Down
4 changes: 2 additions & 2 deletions src/app/domain/accounts/schemas.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,8 +6,8 @@
import msgspec

from app.db.models.team_roles import TeamRoles
from app.lib.schema import CamelizedBaseStruct
from app.domain.accounts.utils import get_signed_user_profile_pic_url
from app.lib.schema import CamelizedBaseStruct

__all__ = (
"AccountLogin",
Expand Down Expand Up @@ -74,7 +74,7 @@ class User(CamelizedBaseStruct):
avatar_url: str | None = None
recently_viewed_opportunity_ids: list[UUID] = []

def __post_init__(self):
def __post_init__(self) -> None:
"""Build a profile pic url from company url."""
self.avatar_url = get_signed_user_profile_pic_url(self.id)

Expand Down
15 changes: 4 additions & 11 deletions src/app/domain/accounts/services.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,15 +14,14 @@
from litestar.exceptions import PermissionDeniedException

from app.config import constants
from app.db.models import Role, User, UserRole, Tenant
from app.db.models import Role, Tenant, User, UserRole
from app.lib import crypt

from .repositories import RoleRepository, UserRepository, UserRoleRepository, TenantRepository
from .repositories import RoleRepository, TenantRepository, UserRepository, UserRoleRepository

if TYPE_CHECKING:
from collections.abc import Iterable

from advanced_alchemy.repository._util import LoadSpec
from sqlalchemy.orm import InstrumentedAttribute


Expand All @@ -41,16 +40,14 @@ async def get_user(
user_id: UUID,
tenant_id: UUID,
**kwargs: Any,
) -> tuple[list[User], int]:
) -> User:
"""Get user details."""
return await self.repository.get_user(user_id=user_id, tenant_id=tenant_id, **kwargs)

async def create(
self,
data: ModelDictT[User],
*,
load: LoadSpec | None = None,
execution_options: dict[str, Any] | None = None,
auto_commit: bool | None = None,
auto_expunge: bool | None = None,
auto_refresh: bool | None = None,
Expand All @@ -63,8 +60,6 @@ async def create(
data.roles.append(UserRole(role_id=role_id, assigned_at=datetime.now(timezone.utc))) # noqa: UP017
return await super().create(
data=data,
load=load,
execution_options=execution_options,
auto_commit=auto_commit,
auto_expunge=auto_expunge,
auto_refresh=auto_refresh,
Expand All @@ -76,13 +71,12 @@ async def update(
item_id: Any | None = None,
*,
id_attribute: str | InstrumentedAttribute[Any] | None = None,
load: LoadSpec | None = None,
execution_options: dict[str, Any] | None = None,
attribute_names: Iterable[str] | None = None,
with_for_update: bool | None = None,
auto_commit: bool | None = None,
auto_expunge: bool | None = None,
auto_refresh: bool | None = None,
execution_options: dict[str, Any] | None = None,
) -> User:
if isinstance(data, dict):
role_id: UUID | None = data.pop("role_id", None)
Expand All @@ -98,7 +92,6 @@ async def update(
auto_expunge=auto_expunge,
auto_refresh=auto_refresh,
id_attribute=id_attribute,
load=load,
execution_options=execution_options,
)

Expand Down
12 changes: 8 additions & 4 deletions src/app/domain/accounts/utils.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,10 @@
import os
from typing import cast
from uuid import UUID

import boto3
import structlog
from uuid import UUID
from botocore.exceptions import BotoCoreError, ClientError

app_s3_bucket_name = os.environ["APP_S3_BUCKET_NAME"]

Expand All @@ -16,7 +19,8 @@ def get_signed_user_profile_pic_url(user_id: UUID, extension: str = "webp", expi
Params={"Bucket": app_s3_bucket_name, "Key": f"tenants/users/avatars/{user_id}.webp"},
ExpiresIn=expiration,
)
return signed_url
except Exception as e:
logger.error("Error getting signed user profile pic url", user_id=user_id, exc_info=e)
return cast(str, signed_url)
except (BotoCoreError, ClientError) as e:
error_msg = "Error getting signed user profile pic url"
logger.exception(error_msg, user_id=user_id, exc_info=e)
return None

0 comments on commit 75c443d

Please sign in to comment.