[feat] negodata: 회원관리 / 최고관리자(OWNER)
- OWNER 권한 신설, 최고관리자가 자기 회사 소속 직원(USER) 계정 생성·수정·삭제 관리 - 회사 사용자 API(/v1/company/user/*), 회원관리 페이지·폼 - 로그인/프로필 흐름 정비, 무인증 계정생성(/auth/create) 제거 Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
7da1925365
commit
a40257ddc1
45 files changed
+1928
-150
No files matched your search
@@ -35,6 +35,7 @@ class ErrorType(Enum):
|
||||
INTERNAL_EXCEPTION = auto()
|
||||
|
||||
# http 에러 코드와 겹치지 않게 설정 - router 전용 예외 발생 옵션
|
||||
HTTP_FORBIDDEN = 403
|
||||
HTTP_INVALID_CLIENT_REQUEST = 419
|
||||
HTTP_TO_MANY_REQUEST = 429
|
||||
HTTP_INVALID_CLIENT_ACCESS = 433
|
||||
@@ -46,6 +47,8 @@ class ErrorType(Enum):
|
||||
ACCOUNT_INVALID_INFO = 1200
|
||||
ACCOUNT_ALREADY_EXIST = auto()
|
||||
ACCOUNT_BLOCKED_USER = auto()
|
||||
ACCOUNT_NOT_FOUND = auto()
|
||||
ACCOUNT_FORBIDDEN = auto() # 최고관리자 외 접근 / 다른 회사·최고관리자 대상 변경 시도
|
||||
|
||||
# 상품 관련 에러
|
||||
ITEM_NOT_FOUND = 1300
|
||||
@@ -71,8 +74,13 @@ class ErrorType(Enum):
|
||||
IMAGE_TOO_LARGE = auto()
|
||||
IMAGE_UPLOAD_FAILED = auto()
|
||||
|
||||
# 초청 메일 발송 관련 에러
|
||||
EMAIL_NOT_CONFIGURED = 1900 # ACS/SMTP 둘 다 미설정 — 발송 불가(설정 필요)
|
||||
EMAIL_SEND_FAILED = auto() # 발송 시도했으나 전부 실패(수신자 0 성공)
|
||||
|
||||
|
||||
# ErrorType 의 HTTP_* 값과 status_code 를 맞춰 router 단에서 raise 한다.
|
||||
EXCEPTION_FORBIDDEN = HTTPException(status_code=ErrorType.HTTP_FORBIDDEN.value, detail=ErrorType.HTTP_FORBIDDEN.name)
|
||||
EXCEPTION_INVALID_CLIENT_REQUEST = HTTPException(status_code=ErrorType.HTTP_INVALID_CLIENT_REQUEST.value, detail=ErrorType.HTTP_INVALID_CLIENT_REQUEST.name)
|
||||
EXCEPTION_TO_MANY_REQUEST = HTTPException(status_code=ErrorType.HTTP_TO_MANY_REQUEST.value, detail=ErrorType.HTTP_TO_MANY_REQUEST.name)
|
||||
EXCEPTION_INVALID_CLIENT_ACCESS = HTTPException(status_code=ErrorType.HTTP_INVALID_CLIENT_ACCESS.value, detail=ErrorType.HTTP_INVALID_CLIENT_ACCESS.name)
|
||||
@@ -105,10 +113,12 @@ class UserStatus(CodeEnum):
|
||||
|
||||
|
||||
class UserRole(CodeEnum):
|
||||
"""users.role 코드값."""
|
||||
"""users.role 코드값. negodata 유저는 전부 회사 직원(관리자측) —
|
||||
의미 있는 구분은 '직원 계정 관리 권한 유무' 하나뿐이라 2단계로 둔다.
|
||||
1=일반, 2=최고관리자(직원 계정 생성·관리)."""
|
||||
|
||||
USER = 1
|
||||
MANAGER = 2
|
||||
OWNER = 2 # 최고관리자: 자기 회사 유저(직원 계정)를 생성·관리
|
||||
|
||||
|
||||
class CompanyStatus(CodeEnum):
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
from abc import ABC, abstractmethod
|
||||
from typing import Tuple
|
||||
from typing import Optional, Tuple
|
||||
|
||||
from sqlalchemy import select, update
|
||||
from sqlalchemy import select, func, and_, or_, update
|
||||
from sqlalchemy.ext.asyncio import AsyncSession
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
@@ -35,6 +35,18 @@ class IUserCRUD(ABC):
|
||||
async def get_company(self, cdb: AsyncSession, company_id) -> Tuple[ErrorType, companies]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def list_by_company(self, cdb: AsyncSession, company_id, search, skip, limit) -> Tuple[ErrorType, list, int]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def get_by_user_id(self, cdb: AsyncSession, user_id) -> Tuple[ErrorType, users]:
|
||||
pass
|
||||
|
||||
@abstractmethod
|
||||
async def update_user(self, cdb: AsyncSession, user_id, data: dict) -> ErrorType:
|
||||
pass
|
||||
|
||||
|
||||
class UserCRUD(IUserCRUD):
|
||||
async def get_user_by_login_id(self, cdb: AsyncSession, login_id: str) -> Tuple[ErrorType, users]:
|
||||
@@ -90,3 +102,57 @@ class UserCRUD(IUserCRUD):
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def list_by_company(
|
||||
self, cdb: AsyncSession, company_id, search: Optional[str], skip: int, limit: int
|
||||
) -> Tuple[ErrorType, list, int]:
|
||||
try:
|
||||
conditions = [users.deleted == False, users.company_id == company_id] # noqa: E712
|
||||
if search:
|
||||
conditions.append(
|
||||
or_(
|
||||
users.id.ilike(f"%{search}%"),
|
||||
users.name.ilike(f"%{search}%"),
|
||||
users.email.ilike(f"%{search}%"),
|
||||
)
|
||||
)
|
||||
where = and_(*conditions)
|
||||
|
||||
cnt_err, cnt_rows = await DB_SESSION_MNG.execute(cdb, select(func.count()).select_from(users).where(where))
|
||||
if cnt_err != ErrorType.SUCCESS:
|
||||
return cnt_err, [], 0
|
||||
total = int(cnt_rows[0] or 0) if cnt_rows else 0
|
||||
|
||||
list_err, rows = await DB_SESSION_MNG.execute(
|
||||
cdb,
|
||||
select(users).where(where).order_by(users.created_at.desc()).offset(skip).limit(limit),
|
||||
)
|
||||
if list_err != ErrorType.SUCCESS:
|
||||
return list_err, [], 0
|
||||
return ErrorType.SUCCESS, list(rows), total
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, [], 0
|
||||
|
||||
async def get_by_user_id(self, cdb: AsyncSession, user_id) -> Tuple[ErrorType, users]:
|
||||
try:
|
||||
query = select(users).where(users.user_id == user_id, users.deleted == False).limit(1) # noqa: E712
|
||||
err_type, row_list = await DB_SESSION_MNG.execute(cdb, query)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
return err_type, None
|
||||
if len(row_list) != 1:
|
||||
return ErrorType.DB_INVALID_KEY, None
|
||||
return ErrorType.SUCCESS, row_list[0]
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED, None
|
||||
|
||||
async def update_user(self, cdb: AsyncSession, user_id, data: dict) -> ErrorType:
|
||||
try:
|
||||
if not data:
|
||||
return ErrorType.SUCCESS
|
||||
query = update(users).where(users.user_id == user_id).values(**data)
|
||||
return await DB_SESSION_MNG.add(cdb, query)
|
||||
except Exception as ex:
|
||||
LOG.e_no_callstack(ex)
|
||||
return ErrorType.DB_RUN_FAILED
|
||||
@@ -4,7 +4,7 @@ from fastapi.security import HTTPAuthorizationCredentials, HTTPBearer
|
||||
from common.models.gmodel import UserInfo
|
||||
from router.v1.validator.dependencies import IsValidAccessToken, IsValidRefreshToken, RemoveNoneResponse
|
||||
from services.auth_service import AuthService
|
||||
from .protocol import Req_CreateAccount, Req_Login, Res_CreateAccount, Res_Login, Res_Me, Res_RefreshToken
|
||||
from .protocol import Req_Login, Req_UpdateMe, Res_Login, Res_Me, Res_RefreshToken
|
||||
|
||||
security = HTTPBearer()
|
||||
|
||||
@@ -17,13 +17,6 @@ async def login(request: Request, req: Req_Login, service: AuthService = Depends
|
||||
return RemoveNoneResponse(await service.attempt_login(req.id, req.password, request.client.host))
|
||||
|
||||
|
||||
@router.post(path="/create", response_model=Res_CreateAccount, summary="계정 생성", description="새 계정을 생성한다.")
|
||||
async def create_account(req: Req_CreateAccount, service: AuthService = Depends()):
|
||||
return RemoveNoneResponse(
|
||||
await service.create_account(req.id, req.password, req.company_id, req.name, req.email, req.contact_number, req.role)
|
||||
)
|
||||
|
||||
|
||||
@router.post(
|
||||
path="/refresh_token",
|
||||
dependencies=[Depends(IsValidRefreshToken)],
|
||||
@@ -43,3 +36,13 @@ async def refresh_token(service: AuthService = Depends(), credentials: HTTPAutho
|
||||
)
|
||||
async def me(service: AuthService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
return RemoveNoneResponse(await service.get_me(user_info))
|
||||
|
||||
|
||||
@router.patch(
|
||||
path="/me",
|
||||
response_model=Res_Me,
|
||||
summary="내 정보 수정",
|
||||
description="본인 이름/이메일/연락처/비밀번호를 수정한다(권한·소속·ID 변경 불가).",
|
||||
)
|
||||
async def update_me(req: Req_UpdateMe, service: AuthService = Depends(), user_info: UserInfo = Depends(IsValidAccessToken)):
|
||||
return RemoveNoneResponse(await service.update_me(user_info, req))
|
||||
@@ -22,18 +22,12 @@ class Res_Login(Res_WebPacketProtocol):
|
||||
token_type: str = "bearer"
|
||||
|
||||
|
||||
class Req_CreateAccount(AuthProtocol):
|
||||
id: str = ""
|
||||
password: str = ""
|
||||
company_id: str = ""
|
||||
name: str = ""
|
||||
email: str = ""
|
||||
contact_number: str = ""
|
||||
role: int = UserRole.USER.value
|
||||
|
||||
|
||||
class Res_CreateAccount(Res_WebPacketProtocol):
|
||||
user_id: str = ""
|
||||
class Req_UpdateMe(AuthProtocol):
|
||||
# 본인 정보 수정. role·company·id 는 받지 않는다(자기 권한·소속 변경 불가).
|
||||
name: Optional[str] = None
|
||||
email: Optional[str] = None
|
||||
contact_number: Optional[str] = None
|
||||
password: Optional[str] = None # 비밀번호 변경(옵션). 비우면 유지
|
||||
|
||||
|
||||
class Res_RefreshToken(Res_WebPacketProtocol):
|
||||
|
||||
@@ -0,0 +1,58 @@
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
from typing import Optional
|
||||
|
||||
from pydantic import ConfigDict
|
||||
|
||||
from common.enums import UserRole, UserStatus
|
||||
from common.models.gmodel import Res_PageProtocol, Res_WebPacketProtocol, WebPacketProtocol
|
||||
|
||||
|
||||
# 최고관리자가 자기 회사 유저를 관리하는 도메인. company_id 는 토큰값으로 강제된다.
|
||||
class CompanyUserProtocol(WebPacketProtocol):
|
||||
pass
|
||||
|
||||
|
||||
class Req_CreateCompanyUser(CompanyUserProtocol):
|
||||
# role 은 받지 않는다 — 최고관리자가 만드는 계정은 항상 일반(USER) 로 서버에서 고정.
|
||||
id: str = ""
|
||||
password: str = ""
|
||||
name: str = ""
|
||||
email: str = ""
|
||||
contact_number: str = ""
|
||||
|
||||
|
||||
class Req_UpdateCompanyUser(CompanyUserProtocol):
|
||||
name: Optional[str] = None
|
||||
email: Optional[str] = None
|
||||
contact_number: Optional[str] = None
|
||||
status: Optional[UserStatus] = None # 활성/비활성 전환
|
||||
password: Optional[str] = None # 비밀번호 초기화(옵션)
|
||||
|
||||
|
||||
class CompanyUserData(WebPacketProtocol):
|
||||
model_config = ConfigDict(from_attributes=True)
|
||||
|
||||
user_id: uuid.UUID
|
||||
company_id: uuid.UUID
|
||||
id: str
|
||||
name: Optional[str] = None
|
||||
email: Optional[str] = None
|
||||
contact_number: Optional[str] = None
|
||||
status: UserStatus
|
||||
role: UserRole
|
||||
last_accessed_at: Optional[datetime] = None
|
||||
created_at: Optional[datetime] = None
|
||||
updated_at: Optional[datetime] = None
|
||||
|
||||
|
||||
class Res_CompanyUser(Res_WebPacketProtocol):
|
||||
user: Optional[CompanyUserData] = None
|
||||
|
||||
|
||||
class Res_CompanyUserList(Res_PageProtocol):
|
||||
users: list[CompanyUserData] = []
|
||||
|
||||
|
||||
class Res_DeleteCompanyUser(Res_WebPacketProtocol):
|
||||
pass
|
||||
@@ -0,0 +1,51 @@
|
||||
from uuid import UUID
|
||||
|
||||
from fastapi import APIRouter, Depends, Query
|
||||
|
||||
from common.models.gmodel import PageParams, UserInfo
|
||||
from router.v1.validator.dependencies import RemoveNoneResponse, RequireOwner
|
||||
from services.company_user_service import CompanyUserService
|
||||
from .protocol import (
|
||||
Req_CreateCompanyUser,
|
||||
Req_UpdateCompanyUser,
|
||||
Res_CompanyUser,
|
||||
Res_CompanyUserList,
|
||||
Res_DeleteCompanyUser,
|
||||
)
|
||||
|
||||
# 최고관리자(OWNER) 전용. 모든 엔드포인트가 RequireOwner 로 게이트되며 company_id 는 토큰값으로 스코프된다.
|
||||
router = APIRouter(prefix="/v1/company/user", tags=["CompanyUser"], responses={404: {"description": "Not found"}})
|
||||
|
||||
|
||||
@router.get(path="/list", response_model=Res_CompanyUserList, summary="회사 유저 목록(최고관리자)")
|
||||
async def list_users(
|
||||
service: CompanyUserService = Depends(),
|
||||
owner: UserInfo = Depends(RequireOwner),
|
||||
search: str | None = Query(None, description="로그인ID/이름/이메일 검색"),
|
||||
pg: PageParams = Depends(),
|
||||
):
|
||||
return RemoveNoneResponse(await service.list_users(owner.company_id, search, pg))
|
||||
|
||||
|
||||
@router.post(path="/create", response_model=Res_CompanyUser, summary="회사 유저 생성(일반 권한 고정)")
|
||||
async def create_user(
|
||||
req: Req_CreateCompanyUser, service: CompanyUserService = Depends(), owner: UserInfo = Depends(RequireOwner)
|
||||
):
|
||||
return RemoveNoneResponse(await service.create_user(owner.company_id, req))
|
||||
|
||||
|
||||
@router.get(path="/{user_id}", response_model=Res_CompanyUser, summary="회사 유저 조회")
|
||||
async def get_user(user_id: UUID, service: CompanyUserService = Depends(), owner: UserInfo = Depends(RequireOwner)):
|
||||
return RemoveNoneResponse(await service.get_user(owner.company_id, str(user_id)))
|
||||
|
||||
|
||||
@router.patch(path="/update/{user_id}", response_model=Res_CompanyUser, summary="회사 유저 수정")
|
||||
async def update_user(
|
||||
user_id: UUID, req: Req_UpdateCompanyUser, service: CompanyUserService = Depends(), owner: UserInfo = Depends(RequireOwner)
|
||||
):
|
||||
return RemoveNoneResponse(await service.update_user(owner.company_id, str(user_id), req))
|
||||
|
||||
|
||||
@router.delete(path="/delete/{user_id}", response_model=Res_DeleteCompanyUser, summary="회사 유저 삭제")
|
||||
async def delete_user(user_id: UUID, service: CompanyUserService = Depends(), owner: UserInfo = Depends(RequireOwner)):
|
||||
return RemoveNoneResponse(await service.delete_user(owner.company_id, str(user_id)))
|
||||
@@ -10,8 +10,10 @@ from jose import jwt, JWTError, ExpiredSignatureError
|
||||
|
||||
from common.enums import (
|
||||
EXCEPTION_ACCESS_TOKEN_EXPIRED,
|
||||
EXCEPTION_FORBIDDEN,
|
||||
EXCEPTION_INVALID_CLIENT_ACCESS,
|
||||
EXCEPTION_REFRESH_TOKEN_EXPIRED,
|
||||
UserRole,
|
||||
)
|
||||
from common.logger import LOG
|
||||
from common.models.gmodel import UserInfo
|
||||
@@ -98,6 +100,13 @@ async def IsValidRefreshToken(credentials: HTTPAuthorizationCredentials = Depend
|
||||
return DecodeRefreshToken(credentials.credentials)
|
||||
|
||||
|
||||
# 최고관리자 전용 엔드포인트 게이트. 액세스 토큰 검증 + role==OWNER 가 아니면 403.
|
||||
async def RequireOwner(user_info: UserInfo = Depends(IsValidAccessToken)) -> UserInfo:
|
||||
if user_info.role != UserRole.OWNER.value:
|
||||
raise EXCEPTION_FORBIDDEN
|
||||
return user_info
|
||||
|
||||
|
||||
# ---- ResponseNone 처리 -----------------------------------------------------
|
||||
# 응답 객체에서 값이 None 인 필드를 재귀적으로 제거하여 페이로드를 줄인다.
|
||||
# 모든 라우터는 return RemoveNoneResponse(await service....) 형태로 반환한다.
|
||||
|
||||
@@ -4,11 +4,11 @@ from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import users
|
||||
from common.enums import DBWRType, ErrorType, UserStatus, UserRole
|
||||
from common.enums import DBWRType, ErrorType, UserStatus
|
||||
from common.logger import LOG
|
||||
from common.models.gmodel import UserInfo
|
||||
from crud.user_crud import IUserCRUD, UserCRUD
|
||||
from router.v1.auth.protocol import CompanyData, Res_CreateAccount, Res_Login, Res_Me, Res_RefreshToken
|
||||
from router.v1.auth.protocol import CompanyData, Req_UpdateMe, Res_Login, Res_Me, Res_RefreshToken
|
||||
from router.v1.validator.dependencies import (
|
||||
CreateAccessToken,
|
||||
CreateRefreshToken,
|
||||
@@ -38,6 +38,7 @@ class AuthService:
|
||||
user_id=str(user.user_id),
|
||||
id=user.id,
|
||||
company_id=str(user.company_id),
|
||||
role=user.role,
|
||||
)
|
||||
|
||||
async def attempt_login(self, login_id: str, password: str, connect_ip: str) -> Res_Login:
|
||||
@@ -82,50 +83,6 @@ class AuthService:
|
||||
|
||||
return res
|
||||
|
||||
async def create_account(
|
||||
self, login_id: str, password: str, company_id: str, name: str, email: str, contact_number: str, role: int
|
||||
) -> Res_CreateAccount:
|
||||
LOG.i(f"CREATE : id={login_id}, company_id={company_id}")
|
||||
res = Res_CreateAccount()
|
||||
|
||||
# 1) 중복 ID 확인 (Read DB)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda(
|
||||
users.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.is_user(s, login_id),
|
||||
)
|
||||
if err_type == ErrorType.DB_ALREADY_SAME_KEY:
|
||||
res.result.SetResult(ErrorType.ACCOUNT_ALREADY_EXIST)
|
||||
return res
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 2) 계정 생성 (비밀번호는 bcrypt 해시로 저장)
|
||||
user = users(
|
||||
company_id=uuid.UUID(company_id),
|
||||
id=login_id,
|
||||
password=await GetHashedPW(password),
|
||||
name=name or None,
|
||||
email=email or None,
|
||||
contact_number=contact_number or None,
|
||||
role=role or UserRole.USER.value,
|
||||
)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[users.DBType()],
|
||||
[lambda s: self.user_crud.add_user(s, user)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
# 사전 검사와 INSERT 사이의 경쟁 조건에서 unique 위반이 나면 동일 코드로 매핑.
|
||||
if err_type == ErrorType.DB_ALREADY_SAME_KEY:
|
||||
res.result.SetResult(ErrorType.ACCOUNT_ALREADY_EXIST)
|
||||
else:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
res.user_id = str(user.user_id)
|
||||
return res
|
||||
|
||||
async def get_me(self, user_info: UserInfo) -> Res_Me:
|
||||
res = Res_Me()
|
||||
|
||||
@@ -159,6 +116,32 @@ class AuthService:
|
||||
res.company = company
|
||||
return res
|
||||
|
||||
async def update_me(self, user_info: UserInfo, req: Req_UpdateMe) -> Res_Me:
|
||||
res = Res_Me()
|
||||
data = req.model_dump(exclude_unset=True)
|
||||
|
||||
# 비밀번호: 값 있으면 해시 교체, 비었으면 변경 안 함.
|
||||
if data.get("password"):
|
||||
data["password"] = await GetHashedPW(data["password"])
|
||||
else:
|
||||
data.pop("password", None)
|
||||
# 빈 문자열은 NULL 로 저장(미입력 = 값 비움).
|
||||
for k in ("name", "email", "contact_number"):
|
||||
if k in data and data[k] == "":
|
||||
data[k] = None
|
||||
|
||||
if data:
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[users.DBType()],
|
||||
[lambda s: self.user_crud.update_user(s, uuid.UUID(user_info.user_id), data)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 갱신 후 최신 정보로 응답(프론트가 스토어 갱신에 사용).
|
||||
return await self.get_me(user_info)
|
||||
|
||||
async def refresh_token(self, refresh_token: str) -> Res_RefreshToken:
|
||||
res = Res_RefreshToken()
|
||||
# refresh 토큰 검증은 라우터 Depends(IsValidRefreshToken) 에서 1차 수행됨.
|
||||
|
||||
@@ -0,0 +1,158 @@
|
||||
import uuid
|
||||
|
||||
from fastapi import Depends
|
||||
|
||||
from common.database.db_session_manager import DB_SESSION_MNG
|
||||
from common.database.model.models import users
|
||||
from common.enums import DBWRType, ErrorType, UserRole, UserStatus
|
||||
from common.utils.gtime import GTime
|
||||
from crud.user_crud import IUserCRUD, UserCRUD
|
||||
from router.v1.company.protocol import (
|
||||
CompanyUserData,
|
||||
Req_CreateCompanyUser,
|
||||
Req_UpdateCompanyUser,
|
||||
Res_CompanyUser,
|
||||
Res_CompanyUserList,
|
||||
Res_DeleteCompanyUser,
|
||||
)
|
||||
from router.v1.validator.dependencies import GetHashedPW
|
||||
|
||||
|
||||
class CompanyUserService:
|
||||
"""최고관리자(OWNER)의 자기 회사 유저 관리 로직.
|
||||
|
||||
- 라우터에서 RequireOwner 로 1차 권한을 거른 뒤 호출된다.
|
||||
- company_id 는 토큰값만 쓴다(요청 body 무시) → 남의 회사 데이터 불가.
|
||||
- 변경 대상이 OWNER 면 거부한다(최고관리자는 앱에서 수정·삭제 불가).
|
||||
"""
|
||||
|
||||
def __init__(self, user_crud: IUserCRUD = Depends(UserCRUD)):
|
||||
self.user_crud = user_crud
|
||||
|
||||
async def _fetch_managed(self, company_uuid: uuid.UUID, user_id: uuid.UUID):
|
||||
"""대상 유저 조회 + 같은 회사 + 비-OWNER 확인. (ErrorType, user|None) 반환."""
|
||||
err_type, user = await DB_SESSION_MNG.execute_lambda(
|
||||
users.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.get_by_user_id(s, user_id),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS or user is None:
|
||||
return ErrorType.ACCOUNT_NOT_FOUND, None
|
||||
if user.company_id != company_uuid:
|
||||
return ErrorType.ACCOUNT_NOT_FOUND, None
|
||||
if user.role == UserRole.OWNER.value:
|
||||
return ErrorType.ACCOUNT_FORBIDDEN, None
|
||||
return ErrorType.SUCCESS, user
|
||||
|
||||
async def list_users(self, company_id: str, search, pg) -> Res_CompanyUserList:
|
||||
res = Res_CompanyUserList(page=pg.page, size=pg.size)
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
|
||||
err_type, rows, total = await DB_SESSION_MNG.execute_lambda(
|
||||
users.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.list_by_company(s, company_uuid, search, pg.skip, pg.size),
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.users = [CompanyUserData.model_validate(r) for r in rows]
|
||||
res.total = total
|
||||
return res
|
||||
|
||||
async def get_user(self, company_id: str, user_id: str) -> Res_CompanyUser:
|
||||
res = Res_CompanyUser()
|
||||
err_type, user = await self._fetch_managed(uuid.UUID(company_id), uuid.UUID(user_id))
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
res.user = CompanyUserData.model_validate(user)
|
||||
return res
|
||||
|
||||
async def create_user(self, company_id: str, req: Req_CreateCompanyUser) -> Res_CompanyUser:
|
||||
res = Res_CompanyUser()
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
|
||||
# 1) 로그인 ID 중복 확인 (id 는 전역 unique)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda(
|
||||
users.DBType(),
|
||||
DBWRType.DB_READ.value,
|
||||
lambda s: self.user_crud.is_user(s, req.id),
|
||||
)
|
||||
if err_type == ErrorType.DB_ALREADY_SAME_KEY:
|
||||
res.result.SetResult(ErrorType.ACCOUNT_ALREADY_EXIST)
|
||||
return res
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 2) 생성 — 회사는 토큰값, 권한은 항상 USER 로 고정.
|
||||
user = users(
|
||||
company_id=company_uuid,
|
||||
id=req.id,
|
||||
password=await GetHashedPW(req.password),
|
||||
name=req.name or None,
|
||||
email=req.email or None,
|
||||
contact_number=req.contact_number or None,
|
||||
role=UserRole.USER.value,
|
||||
)
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[users.DBType()],
|
||||
[lambda s: self.user_crud.add_user(s, user)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
if err_type == ErrorType.DB_ALREADY_SAME_KEY:
|
||||
res.result.SetResult(ErrorType.ACCOUNT_ALREADY_EXIST)
|
||||
else:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
# 서버 기본값(created_at 등)은 insert 후 객체에 안 실리므로 재조회.
|
||||
return await self.get_user(company_id, str(user.user_id))
|
||||
|
||||
async def update_user(self, company_id: str, user_id: str, req: Req_UpdateCompanyUser) -> Res_CompanyUser:
|
||||
res = Res_CompanyUser()
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
user_uuid = uuid.UUID(user_id)
|
||||
|
||||
err_type, _ = await self._fetch_managed(company_uuid, user_uuid)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
data = req.model_dump(exclude_unset=True)
|
||||
if data.get("status") is not None:
|
||||
s = data["status"] # pydantic 은 enum 멤버로 돌려준다 → SMALLINT 값으로 환원
|
||||
data["status"] = s.value if isinstance(s, UserStatus) else int(s)
|
||||
if data.get("password"):
|
||||
data["password"] = await GetHashedPW(data["password"])
|
||||
else:
|
||||
data.pop("password", None) # 빈 비밀번호는 변경하지 않음
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[users.DBType()],
|
||||
[lambda s: self.user_crud.update_user(s, user_uuid, data)],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
return await self.get_user(company_id, user_id)
|
||||
|
||||
async def delete_user(self, company_id: str, user_id: str) -> Res_DeleteCompanyUser:
|
||||
res = Res_DeleteCompanyUser()
|
||||
company_uuid = uuid.UUID(company_id)
|
||||
user_uuid = uuid.UUID(user_id)
|
||||
|
||||
err_type, _ = await self._fetch_managed(company_uuid, user_uuid)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
|
||||
err_type = await DB_SESSION_MNG.execute_lambda_run(
|
||||
[users.DBType()],
|
||||
[lambda s: self.user_crud.update_user(s, user_uuid, {"deleted": True, "updated_at": GTime.UTC()})],
|
||||
)
|
||||
if err_type != ErrorType.SUCCESS:
|
||||
res.result.SetResult(err_type)
|
||||
return res
|
||||
Reference in new issue
Block a user