def _(orm_obj: DB_Comment) -> BaseModel: user = OutUser.from_orm(orm_obj.user) like_users: List[OutUser] = [] for user in orm_obj.likes: like_users.append(OutUser.from_orm(user)) return Comment(user=user, created_at=orm_obj.created_at, text=orm_obj.text, likes=like_users)
def _(orm_obj: DB_User) -> BaseModel: user_out = OutUser.from_orm(orm_obj) subscribers = _get_user_out_list(orm_obj.subscribers) subscriptions = _get_user_out_list(orm_obj.subscriptions) return UserInDetailOut(**user_out.dict(), subscriptions=subscriptions, subscribers=subscribers)
def _authenticate_user(username: str, password: str) -> Awaitable[OutUser]: message = Message.INCORRECT_USERNAME_OR_PASSWORD.value with create_session() as session: user: Optional[User] = session.query(User).filter( User.username == username).first() user = deepcopy(user) if user is None: raise DALError(HTTPStatus.UNAUTHORIZED.value, message) if _is_password_correct(password, user.password_hash): return OutUser.from_orm(user) # type: ignore raise DALError(HTTPStatus.UNAUTHORIZED.value, message)
def _(orm_obj: DB_Post) -> BaseModel: marked_users: List[OutUser] = [] for user in orm_obj.marked_users: marked_users.append(OutUser.from_orm(user)) comments: List[Comment] = [] for comment in orm_obj.comments: comments.append(serialize(comment)) likes = [] for user in orm_obj.likes: likes.append(user) return Post( id=orm_obj.id, user=OutUser.from_orm(orm_obj.user), comments=comments, description=orm_obj.description, likes=likes, created_at=orm_obj.created_at, marked_users=marked_users, location=orm_obj.location, )
async def like(post_id: int, user_id_who_likes: int) -> List[OutUser]: with create_session() as session: post = await PostDAL._get_post(post_id, session) likes = post.likes user = await PostDAL._get_user(user_id_who_likes, session) if PostDAL._is_user_has_like(likes, user): raise DALError( HTTPStatus.BAD_REQUEST.value, Message.USER_HAS_ALREADY_LIKE_THIS_POST.value, ) likes.append(user) return [OutUser.from_orm(user) for user in likes]
async def check_authorization(token: str = Depends(oauth_scheme), ) -> OutUser: ''' Обрабатывает jwt :raises HttpException со статусом 401 если произошла ошибка при обработке токена :return: user ''' user_id = _get_user_id(token) user = await _get_user_from_db(user_id) if _is_valid_token(token, user.access_token.decode()): return OutUser.from_orm(user) raise DALError(HTTPStatus.UNAUTHORIZED.value, Message.ACCESS_TOKEN_OUTDATED.value)
def _get_user_out_list(users: List[DB_User]) -> List[OutUser]: return [OutUser.from_orm(user) for user in users]
def out_user_second(second_in_user): return OutUser(id=2, username=second_in_user.username)
def out_user_first(in_user): return OutUser(id=1, username=in_user.username)