Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

14 скрытие части юзердаты от пользователя #23

Merged
Show file tree
Hide file tree
Changes from 10 commits
Commits
Show all changes
32 commits
Select commit Hold shift + click to select a range
e2e618a
f
gitfresnel Apr 2, 2024
0bf9ecc
f
gitfresnel Apr 2, 2024
43ce24b
f
gitfresnel Apr 3, 2024
5a05385
f
gitfresnel Apr 3, 2024
bf7774a
f
gitfresnel May 12, 2024
1d41a14
f
gitfresnel May 12, 2024
756e75b
f
gitfresnel May 12, 2024
fcb865c
f
gitfresnel Jul 18, 2024
1e40c58
f
gitfresnel Jul 18, 2024
5819ffd
f
gitfresnel Jul 18, 2024
b29ffd4
f
gitfresnel Jul 18, 2024
1821048
f
gitfresnel Aug 21, 2024
3c84010
Merge remote-tracking branch 'origin/main'
gitfresnel Aug 21, 2024
53a7ec9
f
gitfresnel Aug 22, 2024
054c8f9
Merge branch 'main' into 14-скрытие-части-юзердаты-от-пользователя
gitfresnel Aug 22, 2024
6af51d3
f
gitfresnel Aug 22, 2024
085b3f9
Merge branch '14-скрытие-части-юзердаты-от-пользователя' of https://g…
gitfresnel Aug 22, 2024
2200b97
f
gitfresnel Aug 22, 2024
d847f04
f
gitfresnel Sep 1, 2024
1ed868d
f
gitfresnel Sep 2, 2024
9b970c2
Merge branch 'main' of https://github.com/profcomff/userdata-api
gitfresnel Sep 3, 2024
868e134
Merge branch 'main' into 14-скрытие-части-юзердаты-от-пользователя
gitfresnel Sep 3, 2024
4f6fb56
f
gitfresnel Sep 3, 2024
9156cbc
f
gitfresnel Sep 4, 2024
6882a2f
f
gitfresnel Sep 4, 2024
c17ab8c
Remove .idea directory from repository and add to .gitignore
gitfresnel Sep 12, 2024
9c6aa4c
f
gitfresnel Sep 12, 2024
1529804
f
gitfresnel Sep 21, 2024
d9f2be4
f
gitfresnel Sep 27, 2024
5c462da
f
gitfresnel Sep 27, 2024
1ae9510
f
gitfresnel Sep 28, 2024
93a3f4a
Merge branch 'main' into 14-скрытие-части-юзердаты-от-пользователя
gitfresnel Oct 17, 2024
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 3 additions & 0 deletions .idea/.gitignore
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/inspectionProfiles/profiles_settings.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

7 changes: 7 additions & 0 deletions .idea/misc.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

8 changes: 8 additions & 0 deletions .idea/modules.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

15 changes: 15 additions & 0 deletions .idea/userdata-api.iml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 6 additions & 0 deletions .idea/vcs.xml

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
"""Add visible_in_user_response field to Param table

Revision ID: ea9459426db1
Revises: f8c57101c0f6
Create Date: 2024-05-12 20:27:45.549332

"""

import sqlalchemy as sa
from alembic import op


# revision identifiers, used by Alembic.
revision = 'ea9459426db1'
down_revision = 'f8c57101c0f6'
branch_labels = None
depends_on = None


def upgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.add_column('param', sa.Column('visible_in_user_response', sa.Boolean(), nullable=False, server_default='0'))
# ### end Alembic commands ###


def downgrade():
# ### commands auto generated by Alembic - please adjust! ###
op.drop_column('param', 'visible_in_user_response')
# ### end Alembic commands ###
1 change: 1 addition & 0 deletions migrations/versions/f8c57101c0f6_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
Create Date: 2023-05-09 12:48:25.550608

"""

import sqlalchemy as sa
from alembic import op

Expand Down
1 change: 1 addition & 0 deletions userdata_api/models/db.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@ class Param(BaseDbModel):
а параметры эти могут лежать в категории "контакты"
"""

visible_in_user_response: Mapped[bool] = mapped_column(Boolean, default=True)
name: Mapped[str] = mapped_column(String)
category_id: Mapped[int] = mapped_column(Integer, ForeignKey(Category.id))
is_required: Mapped[bool] = mapped_column(Boolean, default=False)
Expand Down
12 changes: 8 additions & 4 deletions userdata_api/routes/user.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from typing import Any

from auth_lib.fastapi import UnionAuth
from fastapi import APIRouter, Depends
from fastapi import APIRouter, Depends, Query

from userdata_api.schemas.response_model import StatusResponseModel
from userdata_api.schemas.user import UserInfoGet, UserInfoUpdate
Expand All @@ -14,12 +14,15 @@

@user.get("/{id}", response_model=UserInfoGet)
async def get_user_info(
id: int, user: dict[str, Any] = Depends(UnionAuth(scopes=[], allow_none=False, auto_error=True))
id: int,
additional_data: list[str] = Query(default=[]),
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
user: dict[str, Any] = Depends(UnionAuth(scopes=[], allow_none=False, auto_error=True)),
) -> UserInfoGet:
"""
Получить информацию о пользователе
\f
:param id: Айди овнера информации(пользователя)
:additional_data: список невидимых по дефолту параметров
:param user: Аутентфикация
:return: Словарь, ключи - категории на которые хватило прав(овнеру не нужны права, он получает всё).
Значения - словари, ключи которых - имена параметров,
Expand All @@ -30,7 +33,8 @@ async def get_user_info(
...
}
"""
return UserInfoGet.model_validate(await get(id, user))

return UserInfoGet.model_validate(await get(id, user, additional_data))


@user.post("/{id}", response_model=StatusResponseModel)
Expand All @@ -53,7 +57,7 @@ async def update_user(
Чтобы обновить от имени админиа, надо иметь скоуп `userdata.info.admin`
Чтобы обновить неизменяемую информацию надо обладать скоупом `userdata.info.update`
Для обновления своей информации(источник `user`) не нужны скоупы на обновление соответствующих категорий
Для обновления чужой информации от имени админа(источник `admin`)
Для обновления чужой информации от имени админа(источник `admin`)
нужны скоупы на обновление всех указанных в теле запроса категорий пользовательских данных данных
\f
:param request: Запрос из fastapi
Expand Down
2 changes: 2 additions & 0 deletions userdata_api/schemas/param.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,13 +6,15 @@


class ParamPost(Base):
visible_in_user_response: bool = True
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
name: constr(min_length=1)
is_required: bool
changeable: bool
type: ViewType


class ParamPatch(Base):
visible_in_user_response: bool = True
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
name: constr(min_length=1) | None = None
is_required: bool | None = None
changeable: bool | None = None
Expand Down
19 changes: 16 additions & 3 deletions userdata_api/utils/user.py
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
from __future__ import annotations

from fastapi_sqlalchemy import db
from sqlalchemy import not_
from sqlalchemy import String, cast, func, not_, or_

from userdata_api.exceptions import Forbidden, ObjectNotFound
from userdata_api.models.db import Category, Info, Param, Source, ViewType
Expand Down Expand Up @@ -90,7 +90,9 @@ async def patch_user_info(new: UserInfoUpdate, user_id: int, user: dict[str, int
continue


async def get_user_info(user_id: int, user: dict[str, int | list[dict[str, str | int]]]) -> UserInfoGet:
async def get_user_info(
user_id: int, user: dict[str, int | list[dict[str, str | int]]], additional_data: list[str]
) -> UserInfoGet:
"""
Возвращает информауию о пользователе в соотетствии с переданным токеном.

Expand All @@ -100,13 +102,24 @@ async def get_user_info(user_id: int, user: dict[str, int | list[dict[str, str |

:param user_id: Айди пользователя
:param user: Сессия выполняющего запрос данных
:additional_data: Список невидимых по дефолту параметров
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
:return: Список словарей содержащих категорию, параметр категории и значение этого параметра у польщователя
"""
infos: list[Info] = (
Info.query(session=db.session)
.join(Param)
.join(Category)
.filter(Info.owner_id == user_id, not_(Param.is_deleted), not_(Category.is_deleted))
.filter(
gitfresnel marked this conversation as resolved.
Show resolved Hide resolved
Info.owner_id == user_id,
not_(Param.is_deleted),
not_(Category.is_deleted),
or_(
Param.visible_in_user_response,
func.concat('category', cast(Category.id, String), '.field', cast(Param.id, String)).in_(
additional_data
),
),
)
.all()
)
if not infos:
Expand Down
Loading