Replies: 2 comments 8 replies
-
@vetsinen You can try using the new Piccolo Admin feature and write custom validators for this purpose and pass them to TableConfig. Of course, the superuser can still do anything on the tables. Hope that helps. |
Beta Was this translation helpful? Give feedback.
0 replies
-
Yeah, as @sinisaos said - validators are probably the best approach. We just added support for async validators in Piccolo API - so make sure you upgrade to the latest version. You can then do something like this: from piccolo_api.crud.endpoints import PiccoloCRUD
from piccolo_api.session_auth.tables import SessionsBase as _SessionsBase
from piccolo.columns.column_types import Varchar, ForeignKey
from piccolo.apps.user.tables import BaseUser as _BaseUser
from piccolo.table import Table, create_db_tables_sync
from piccolo_admin.endpoints import create_admin, TableConfig
from piccolo_api.crud.validators import Validators
from piccolo.engine.sqlite import SQLiteEngine
from starlette.exceptions import HTTPException
from starlette.requests import Request
DB = SQLiteEngine()
class BaseUser(_BaseUser, db=DB):
pass
class SessionsBase(_SessionsBase, db=DB):
pass
class MyTable(Table, db=DB):
data = Varchar()
user = ForeignKey(BaseUser, null=False)
###############################
# The important bit
async def owner_only(piccolo_crud: PiccoloCRUD, request: Request):
row_id = request.path_params["row_id"]
if not await MyTable.exists().where(
MyTable.id == int(row_id),
MyTable.user == request.user.user
):
raise HTTPException('Only the owner can edit this row.')
app = create_admin(
tables=[
BaseUser,
TableConfig(MyTable, validators=Validators(patch_single=[owner_only])),
],
auth_table=BaseUser,
session_table=SessionsBase,
)
###############################
if __name__ == '__main__':
create_db_tables_sync(MyTable, BaseUser, SessionsBase, if_not_exists=True)
if not BaseUser.exists().where(BaseUser.username == 'piccolo').run_sync():
BaseUser.create_user_sync(
username='piccolo',
password='piccolo123',
email="[email protected]",
admin=True,
active=True,
superuser=True
)
if not BaseUser.exists().where(BaseUser.username == 'other_user').run_sync():
BaseUser.create_user_sync(
username='other_user',
password='other_user123',
email="[email protected]",
admin=True,
active=True,
superuser=True
)
import uvicorn
uvicorn.run(app) |
Beta Was this translation helpful? Give feedback.
8 replies
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
-
can i allow to edit records in tables only for record owners, if owners id is saved as foreign key?
Beta Was this translation helpful? Give feedback.
All reactions