-
Notifications
You must be signed in to change notification settings - Fork 0
Информация о пользователе для админки тех. поддержки #52
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
Merged
Merged
Changes from all commits
Commits
Show all changes
11 commits
Select commit
Hold shift + click to select a range
7881a43
Информация о пользователе от лк мгу
petrCher adb809f
small changes
petrCher 9085119
small fix
petrCher ab0aeb6
Создание админки
petrCher a05192d
добавил получение информации о пользователе для админки
petrCher 32ba774
small fix
petrCher 9bed589
изменил get_user_info
petrCher 7dc3d73
black isort
petrCher 7a2191f
small changes and fixes
petrCher bf9e196
linting fixed
petrCher 4a03062
добавил проверку на существование пользователя
petrCher File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Some comments aren't visible on the classic Files Changed page.
There are no files selected for viewing
This file contains hidden or 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 hidden or 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 |
|---|---|---|
| @@ -1,5 +1,3 @@ | ||
| from time import sleep | ||
|
|
||
| import pytest | ||
|
|
||
| from userdata_api.models.db import Info, Param | ||
|
|
||
This file contains hidden or 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,43 @@ | ||
| from typing import Any | ||
|
|
||
| from auth_lib.fastapi import UnionAuth | ||
| from fastapi import APIRouter, Depends | ||
|
|
||
| from userdata_api.schemas.admin import UserCardGet, UserCardUpdate | ||
| from userdata_api.schemas.response_model import StatusResponseModel | ||
| from userdata_api.utils.admin import get_user_info, patch_user_info | ||
|
|
||
|
|
||
| admin = APIRouter(prefix="/admin", tags=["Admin"]) | ||
|
|
||
|
|
||
| @admin.get("/user/{user_id}", response_model=UserCardGet) | ||
| async def get_user_card( | ||
| user_id: int, | ||
| user: dict[str, Any] = Depends(UnionAuth(scopes=["userdata.info.admin"], allow_none=False, auto_error=True)), | ||
| ): | ||
| """ | ||
| Получает профсоюзную информацию пользователя. | ||
|
|
||
| Скоупы: `["userdata.info.admin"]` | ||
| """ | ||
|
|
||
| return await get_user_info(user_id, user) | ||
|
|
||
|
|
||
| @admin.patch("/user/{user_id}", response_model=StatusResponseModel) | ||
| async def update_user_card( | ||
| new_info: UserCardUpdate, | ||
| user_id: int, | ||
| user: dict[str, Any] = Depends(UnionAuth(scopes=["userdata.info.admin"], allow_none=False, auto_error=True)), | ||
| ) -> StatusResponseModel: | ||
| """ | ||
| Обновить данные в профсоюзной информации пользователя. | ||
|
|
||
| Скоупы: `["userdata.info.admin"]` | ||
|
|
||
| - **user_id**: id пользователя. | ||
| """ | ||
|
|
||
| await patch_user_info(new_info, user_id, user) | ||
| return StatusResponseModel(status="Success", message="User patch succeeded", ru="Изменение успешно") |
This file contains hidden or 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 hidden or 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 hidden or 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,14 @@ | ||
| from .base import Base | ||
|
|
||
|
|
||
| class UserCardGet(Base): | ||
| user_id: int | ||
| full_name: str | None = None | ||
| student_card_number: str | None = None | ||
| union_card_number: str | None = None | ||
| is_union_member: str | ||
|
|
||
|
|
||
| class UserCardUpdate(Base): | ||
| full_name: str | None = None | ||
| student_card_number: str | None = None |
This file contains hidden or 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,86 @@ | ||
| from __future__ import annotations | ||
|
|
||
| from fastapi_sqlalchemy import db | ||
|
|
||
| from userdata_api.exceptions import ObjectNotFound | ||
| from userdata_api.models.db import Info, Param | ||
| from userdata_api.schemas.admin import UserCardGet, UserCardUpdate | ||
| from userdata_api.schemas.user import UserInfo, UserInfoUpdate | ||
|
|
||
| from .user import patch_user_info as user_patch | ||
|
|
||
|
|
||
| async def patch_user_info(new: UserCardUpdate, user_id: int, user: dict[str, int | list[dict[str, str | int]]]) -> None: | ||
| """ | ||
| Обновить информацию о пользователе в соотетствии с переданным токеном. | ||
|
|
||
| Метод обновляет только информацию из источников `admin`. | ||
|
|
||
| Для обновления от имени админа нужен скоуп `userdata.info.admin` | ||
|
|
||
| :param new: модель запроса, в ней то, на что будет изменена информация о пользователе | ||
| :param user_id: Айди пользователя | ||
| :param user: Сессия пользователя выполняющего запрос | ||
| :return: get_user_info для текущего пользователя с переданными правами | ||
| """ | ||
| update_info = [] | ||
| if new.full_name is not None: | ||
| update_info.append(UserInfo(category="Личная информация", param="Полное имя", value=new.full_name)) | ||
| if new.student_card_number is not None: | ||
| update_info.append( | ||
| UserInfo(category="Учёба", param="Номер студенческого билета", value=new.student_card_number) | ||
| ) | ||
morozov-tech marked this conversation as resolved.
Show resolved
Hide resolved
|
||
| if update_info: | ||
| update_request = UserInfoUpdate(items=update_info, source="admin") | ||
| await user_patch(update_request, user_id, user) | ||
|
|
||
|
|
||
| async def get_user_info(user_id: int, user: dict[str, int | list[dict[str, str | int]]]) -> UserCardGet: | ||
| """ | ||
| Получить профсоюзную информацию пользователя для админки. | ||
|
|
||
| :param user_id: Айди пользователя, информацию о котором запрашиваем | ||
| :param user: Сессия пользователя, выполняющего запрос (должен иметь права администратора) | ||
| :return: Словарь с данными пользователя: | ||
| - user_id: ID пользователя | ||
| - full_name: Полное имя (из параметра "Полное имя") | ||
| - student_card_number: Номер студенческого билета (из параметра "Номер студенческого билета") | ||
| - union_card_number: Номер профсоюзного билета (из параметра "Номер профсоюзного билета") | ||
| - is_union_member: Статус мэтчинга (из параметра "Членство в профсоюзе") | ||
| - last_check_timestamp: Дата последней проверки | ||
| """ | ||
| users = db.session.query(Info).filter(Info.owner_id == user_id).first() | ||
| if not users: | ||
| raise ObjectNotFound(Info, user_id) | ||
| full_name = ( | ||
| db.session.query(Info) | ||
| .join(Info.param) | ||
| .filter(Info.owner_id == user_id, Param.name == "Полное имя") | ||
| .one_or_none() | ||
| ) | ||
| is_union_member = ( | ||
| db.session.query(Info) | ||
| .join(Info.param) | ||
| .filter(Info.owner_id == user_id, Param.name == "Членство в профсоюзе") | ||
| .one_or_none() | ||
| ) | ||
| student_card_number = ( | ||
| db.session.query(Info) | ||
| .join(Info.param) | ||
| .filter(Info.owner_id == user_id, Param.name == "Номер студенческого билета") | ||
| .one_or_none() | ||
| ) | ||
| union_card_number = ( | ||
| db.session.query(Info) | ||
| .join(Info.param) | ||
| .filter(Info.owner_id == user_id, Param.name == "Номер профсоюзного билета") | ||
| .one_or_none() | ||
| ) | ||
| result = { | ||
| "user_id": user_id, | ||
| "full_name": full_name.value if full_name else None, | ||
| "student_card_number": student_card_number.value if student_card_number else None, | ||
| "union_card_number": union_card_number.value if union_card_number else None, | ||
| "is_union_member": is_union_member.value if is_union_member else "false", | ||
| } | ||
| return result | ||
This file contains hidden or 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
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.