-
Notifications
You must be signed in to change notification settings - Fork 1
sqladmin админка #251
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
Open
petrCher
wants to merge
15
commits into
main
Choose a base branch
from
petr-sqladmin
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+325
−65
Open
sqladmin админка #251
Changes from all commits
Commits
Show all changes
15 commits
Select commit
Hold shift + click to select a range
4e6bb75
sqladmin
petrCher 9d1c1e9
sqladmin columns updated
petrCher 9051921
black format
petrCher ca80e48
small fix
petrCher 1069174
formatting sqladmin
petrCher afbf7cb
small fix
petrCher 45af672
user logic added for sqladmin
petrCher 6570f02
soft deletes added
petrCher c4cdd6b
logic for group sqladmin
petrCher 10c45f2
patch group logic and filtering
petrCher f721c9d
minor format fixes
petrCher ea58ec5
docs + default admin key
petrCher a047999
black stable
petrCher 0b5ef20
auth logic
petrCher 8f7631b
authorization correct logic added to sqladmin
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
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
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,136 @@ | ||
| from sqladmin import ModelView | ||
| from sqlalchemy import func, select | ||
| from sqlalchemy.sql.expression import Select | ||
| from starlette.requests import Request | ||
|
|
||
| from auth_backend.admin.filter import FilteredModelConverter | ||
| from auth_backend.models.db import Group, Scope, User | ||
| from auth_backend.routes.groups import create_group_logic, delete_group_id, patch_group_logic | ||
| from auth_backend.routes.scopes import create_scope_logic | ||
| from auth_backend.routes.user import patch_user_groups | ||
| from auth_backend.schemas.models import GroupPatch, GroupPost, ScopePost | ||
|
|
||
|
|
||
| class ScopeAdmin(ModelView, model=Scope): | ||
| name = "Scope" | ||
| name_plural = "Scopes" | ||
| column_list = ["id", "name", "comment"] | ||
| column_details_list = [ | ||
| "id", | ||
| "name", | ||
| "comment", | ||
| "creator_id", | ||
| "is_deleted", | ||
| ] | ||
| column_searchable_list = ["id", "name"] | ||
| column_sortable_list = ["id", "name"] | ||
| column_default_sort = [("id", False)] | ||
| form_excluded_columns = ["create_ts", "update_ts", "groups", "user_sessions", "is_deleted"] | ||
| form_converter = FilteredModelConverter | ||
|
|
||
| def list_query(self, request: Request) -> Select: | ||
| return select(Scope).where(Scope.is_deleted == False) | ||
|
|
||
| def count_query(self, request: Request) -> Select: | ||
| return select(func.count(Scope.id)).where(Scope.is_deleted == False) | ||
|
|
||
| async def insert_model(self, request: Request, data: dict): | ||
| user_id = request.session.get("user_id") | ||
| scope_inp = ScopePost(**data) | ||
| with self.session_maker(expire_on_commit=False) as session: | ||
| obj = create_scope_logic(scope_inp, session, user_id) | ||
| return Scope.get(obj.id, session=session) | ||
|
|
||
| async def update_model(self, request, pk, data): | ||
| with self.session_maker(expire_on_commit=False) as session: | ||
| scope_data = {k: v for k, v in data.items() if v is not None} | ||
| obj = Scope.update(int(pk), **scope_data, session=session) | ||
| session.commit() | ||
| return obj | ||
|
|
||
| async def delete_model(self, request, pk): | ||
| with self.session_maker(expire_on_commit=False) as session: | ||
| Scope.delete(session=session, id=int(pk)) | ||
| session.commit() | ||
|
|
||
|
|
||
| class GroupAdmin(ModelView, model=Group): | ||
| name = "Group" | ||
| name_plural = "Groups" | ||
| column_list = ["id", "name", "scopes", "users", "parent_id"] | ||
| column_details_list = [ | ||
| "id", | ||
| "name", | ||
| "parent_id", | ||
| "scopes", | ||
| "users", | ||
| "create_ts", | ||
| "update_ts", | ||
| "is_deleted", | ||
| ] | ||
| column_searchable_list = ["name"] | ||
| column_sortable_list = ["id", "name", "parent_id", "is_deleted"] | ||
| column_default_sort = [("id", False)] | ||
| form_excluded_columns = ["child", "users", "create_ts", "update_ts", "is_deleted"] | ||
| form_converter = FilteredModelConverter | ||
|
|
||
| def list_query(self, request: Request) -> Select: | ||
| return select(Group).where(Group.is_deleted == False) | ||
|
|
||
| def count_query(self, request: Request) -> Select: | ||
| return select(func.count(Group.id)).where(Group.is_deleted == False) | ||
|
|
||
| async def insert_model(self, request, data): | ||
| scope_ids = [int(s) for s in (data.pop("scopes", None) or [])] | ||
| parent_id = int(data["parent_id"]) if data.get("parent_id") else None | ||
| group_inp = GroupPost(name=data["name"], parent_id=parent_id, scopes=scope_ids) | ||
| with self.session_maker(expire_on_commit=False) as session: | ||
| result = create_group_logic(group_inp, session) | ||
| return Group.get(result["id"], session=session) | ||
|
|
||
| async def update_model(self, request, pk, data): | ||
| scope_ids = [int(s) for s in (data.pop("scopes", None) or [])] | ||
| parent_id = int(data["parent_id"]) if data.get("parent_id") else None | ||
| group_inp = GroupPatch( | ||
| name=data.get("name"), | ||
| parent_id=parent_id, | ||
| scopes=scope_ids, | ||
| ) | ||
| with self.session_maker(expire_on_commit=False) as session: | ||
| return patch_group_logic(int(pk), group_inp, session) | ||
|
|
||
| async def delete_model(self, request, pk): | ||
| with self.session_maker(expire_on_commit=False) as session: | ||
| delete_group_id(int(pk), session) | ||
|
|
||
|
|
||
| class UserAdmin(ModelView, model=User): | ||
| name = "User" | ||
| name_plural = "Users" | ||
| column_list = ["id", "scopes", "groups"] | ||
| column_details_list = ["id", "groups", "scopes", "is_deleted"] | ||
| column_searchable_list = ["id"] | ||
| column_sortable_list = ["id", "is_deleted"] | ||
| form_include_pk = False | ||
| form_columns = ["groups"] | ||
| can_create = False | ||
| can_delete = False | ||
| column_formatters = { | ||
| "scopes": lambda m, a: ", ".join(s.name for s in m.scopes), | ||
| } | ||
| column_formatters_detail = { | ||
| "scopes": lambda m, a: ", ".join(s.name for s in (m.scopes or set())), | ||
| } | ||
| form_converter = FilteredModelConverter | ||
|
|
||
| def list_query(self, request: Request) -> Select: | ||
| return select(User).where(User.is_deleted == False) | ||
|
|
||
| def count_query(self, request: Request) -> Select: | ||
| return select(func.count(User.id)).where(User.is_deleted == False) | ||
|
|
||
| async def update_model(self, request, pk, data): | ||
| group_ids = [int(group) for group in (data.pop("groups") or [])] | ||
| with self.session_maker(expire_on_commit=False) as session: | ||
| patch_user_groups(int(pk), group_ids, session) | ||
| return User.get(int(pk), session=session) |
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,51 @@ | ||
| from auth_lib.methods import AuthLib | ||
| from fastapi import Request | ||
| from sqladmin.authentication import AuthenticationBackend | ||
|
|
||
| from auth_backend.settings import get_settings | ||
| from typing import Any | ||
|
|
||
|
|
||
| settings = get_settings() | ||
|
|
||
| class AdminAuth(AuthenticationBackend): | ||
|
|
||
| async def login(self, request: Request) -> bool: | ||
| form = await request.form() | ||
| username = form.get("username") | ||
| token = form.get("password") | ||
| if username != settings.ADMIN_LOGIN: | ||
| return False | ||
| valid = await self._is_valid_token(token) | ||
| if valid is None: | ||
| return False | ||
| request.session["token"] = token | ||
| request.session["user_id"] = valid.get("id") | ||
| return True | ||
|
|
||
| async def authenticate(self, request: Request) -> bool: | ||
| token = request.session.get("token") | ||
| if not token: | ||
| return False | ||
| userdata = await self._is_valid_token(token) | ||
| return userdata is not None | ||
|
|
||
| async def logout(self, request: Request) -> bool: | ||
| request.session.clear() | ||
| return True | ||
|
|
||
| @staticmethod | ||
| async def _is_valid_token(token: str) -> dict[str, Any] | None: | ||
| try: | ||
| result = AuthLib(auth_url=settings.AUTH_URL).check_token(token) | ||
| if not result: | ||
| return None | ||
| session_scopes = { | ||
| scope["name"].lower() for scope in result.get("session_scopes", []) | ||
| } | ||
| required_scopes = "auth.sqladmin.admin" | ||
| if required_scopes not in session_scopes: | ||
| return None | ||
| return result | ||
| except Exception: | ||
| return 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,24 @@ | ||
| import anyio | ||
| from sqladmin.forms import ModelConverter | ||
| from sqladmin.helpers import is_async_session_maker | ||
| from sqlalchemy import select | ||
|
|
||
|
|
||
| class FilteredModelConverter(ModelConverter): | ||
| """ | ||
| A custom ModelConverter that filters out deleted objects from select options in form with create/update. | ||
| """ | ||
|
|
||
| async def _prepare_select_options(self, prop, session_maker): | ||
| target_model = prop.mapper.class_ | ||
| stmt = select(target_model) | ||
| if hasattr(target_model, "is_deleted"): | ||
| stmt = stmt.where(target_model.is_deleted == False) | ||
| if is_async_session_maker(session_maker): | ||
| async with session_maker() as session: | ||
| objects = await session.execute(stmt) | ||
| return [(str(self._get_identifier_value(obj)), str(obj)) for obj in objects.scalars().unique().all()] | ||
| else: | ||
| with session_maker() as session: | ||
| objects = await anyio.to_thread.run_sync(session.execute, stmt) | ||
|
petrCher marked this conversation as resolved.
|
||
| return [(str(self._get_identifier_value(obj)), str(obj)) for obj in objects.scalars().unique().all()] | ||
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
Oops, something went wrong.
Oops, something went wrong.
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.