From 63d8fd59b1162cef109fd86e616878ba081db057 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Goran=20Meki=C4=87?= Date: Sun, 31 Mar 2024 17:17:06 +0200 Subject: [PATCH] Update to newer ormar --- bin/devel.sh | 4 +++- bin/freenit.sh | 42 ++++++++++++++++++++++------------- freenit/api/user.py | 4 ++-- freenit/app.py | 8 +++---- freenit/auth.py | 18 +++++++-------- freenit/base_config.py | 6 ----- freenit/models/ormar/base.py | 16 +++++++++++++ freenit/models/ormar/role.py | 11 +++------ freenit/models/ormar/theme.py | 9 ++------ freenit/models/ormar/user.py | 9 ++------ freenit/models/pagination.py | 4 ++-- freenit/models/safe.py | 4 ++-- 12 files changed, 72 insertions(+), 63 deletions(-) diff --git a/bin/devel.sh b/bin/devel.sh index e0c0b0a..216dbe3 100755 --- a/bin/devel.sh +++ b/bin/devel.sh @@ -1,13 +1,15 @@ #!/bin/sh BIN_DIR=`dirname $0` -export FREENIT_ENV="dev,all" +export FREENIT_ENV="all" export OFFLINE=${OFFLINE:="no"} . ${BIN_DIR}/common.sh setup +export FREENIT_ENV="dev" + if [ ! -e "alembic/versions" ]; then mkdir -p alembic/versions alembic revision --autogenerate -m initial diff --git a/bin/freenit.sh b/bin/freenit.sh index 8f995c2..6b0076a 100755 --- a/bin/freenit.sh +++ b/bin/freenit.sh @@ -397,25 +397,18 @@ EOF svelte() { npm create svelte@latest "${NAME}" cd "${NAME}" - npm install - frontend_common - npm install --save-dev @zerodevx/svelte-toast @freenit-framework/svelte-base - cat >.prettierrc<>vite.config.ts<>package.json<.prettierrc< Page[UserSafe]: - if User.Meta.type == "ormar": + if User.dbtype() == "ormar": return await paginate(User.objects, page, perpage) - elif User.Meta.type == "bonsai": + elif User.dbtype() == "bonsai": import bonsai client = bonsai.LDAPClient(f"ldap://{config.ldap.host}", config.ldap.tls) diff --git a/freenit/app.py b/freenit/app.py index 232b307..8c91ee4 100644 --- a/freenit/app.py +++ b/freenit/app.py @@ -9,12 +9,12 @@ @asynccontextmanager -async def lifespan(app: FastAPI): - if config.database.is_connected: - await config.database.disconnect() - yield +async def lifespan(_: FastAPI): if not config.database.is_connected: await config.database.connect() + yield + if config.database.is_connected: + await config.database.disconnect() app = FastAPI(lifespan=lifespan) diff --git a/freenit/auth.py b/freenit/auth.py index 0b44667..c68b029 100644 --- a/freenit/auth.py +++ b/freenit/auth.py @@ -15,7 +15,7 @@ async def decode(token): pk = data.get("pk", None) if pk is None: raise HTTPException(status_code=403, detail="Unauthorized") - if User.Meta.type == "ormar": + if User.dbtype() == "ormar": import ormar import ormar.exceptions @@ -24,7 +24,7 @@ async def decode(token): return user except ormar.exceptions.NoMatch: raise HTTPException(status_code=403, detail="Unauthorized") - elif User.Meta.type == "bonsai": + elif User.dbtype() == "bonsai": import bonsai client = bonsai.LDAPClient(f"ldap://{config.ldap.host}", config.ldap.tls) @@ -49,10 +49,10 @@ async def decode(token): def encode(user): config = getConfig() payload = {} - if user.Meta.type == "ormar": - payload = {"pk": user.pk, "type": user.Meta.type} - elif user.Meta.type == "bonsai": - payload = {"pk": user.dn, "type": user.Meta.type} + if user.dbtype() == "ormar": + payload = {"pk": user.pk, "type": "ormar"} + elif user.dbtype() == "bonsai": + payload = {"pk": user.dn, "type": "bonsai"} return jwt.encode(payload, config.secret, algorithm="HS256") @@ -61,7 +61,7 @@ async def authorize(request: Request, roles=[], allof=[], cookie="access"): if not token: raise HTTPException(status_code=403, detail="Unauthorized") user = await decode(token) - if user.Meta.type == "ormar": + if user.dbtype() == "ormar": await user.load_all() if not user.active: raise HTTPException(status_code=403, detail="Permission denied") @@ -84,8 +84,8 @@ async def authorize(request: Request, roles=[], allof=[], cookie="access"): if role.name not in allof: raise HTTPException(status_code=403, detail="Permission denied") return user - # elif user.Meta.type == "bonsai": - # pass + elif user.dbtype() == "bonsai": + pass return user diff --git a/freenit/base_config.py b/freenit/base_config.py index c99b02e..d38aa43 100644 --- a/freenit/base_config.py +++ b/freenit/base_config.py @@ -83,12 +83,6 @@ def __init__(self): self.database = databases.Database(self.dburl) self.engine = sqlalchemy.create_engine(self.dburl) - class Meta: - database = self.database - metadata = self.metadata - - self.meta = Meta - def __repr__(self): return ( f"<{self.envname()} config: {self.name}({self.version}) on {self.hostname}>" diff --git a/freenit/models/ormar/base.py b/freenit/models/ormar/base.py index a92d4e3..f5abc9e 100644 --- a/freenit/models/ormar/base.py +++ b/freenit/models/ormar/base.py @@ -1,8 +1,17 @@ import ormar import pydantic +from freenit.config import getConfig + + +config = getConfig() + class OrmarBaseModel(ormar.Model): + @classmethod + def dbtype(cls): + return 'ormar' + async def patch(self, fields): result = {} data = fields.dict() @@ -23,3 +32,10 @@ class OrmarUserMixin: class OrmarRoleMixin: id: int = ormar.Integer(primary_key=True) name: str = ormar.Text(unique=True) + + +ormar_config = ormar.OrmarConfig( + database=config.database, + metadata=config.metadata, + engine=config.engine, +) diff --git a/freenit/models/ormar/role.py b/freenit/models/ormar/role.py index 228ab2f..7b72111 100644 --- a/freenit/models/ormar/role.py +++ b/freenit/models/ormar/role.py @@ -1,15 +1,10 @@ -from freenit.config import getConfig - from ..metaclass import AllOptional -from .base import OrmarBaseModel, OrmarRoleMixin - -config = getConfig() +from .base import OrmarBaseModel, OrmarRoleMixin, ormar_config class Role(OrmarBaseModel, OrmarRoleMixin): - class Meta(config.meta): - pass + ormar_config = ormar_config.copy() class RoleOptional(Role, metaclass=AllOptional): - pass + ormar_config = ormar_config.copy() diff --git a/freenit/models/ormar/theme.py b/freenit/models/ormar/theme.py index b4e02c4..3845c3c 100644 --- a/freenit/models/ormar/theme.py +++ b/freenit/models/ormar/theme.py @@ -1,16 +1,11 @@ import ormar -from freenit.config import getConfig - from ..metaclass import AllOptional -from .base import OrmarBaseModel - -config = getConfig() +from .base import OrmarBaseModel, ormar_config class Theme(OrmarBaseModel): - class Meta(config.meta): - pass + ormar_config = ormar_config.copy() id: int = ormar.Integer(primary_key=True) name: str = ormar.Text(unique=True) diff --git a/freenit/models/ormar/user.py b/freenit/models/ormar/user.py index 60da799..b09cf30 100644 --- a/freenit/models/ormar/user.py +++ b/freenit/models/ormar/user.py @@ -5,13 +5,10 @@ from fastapi import HTTPException from freenit.auth import verify -from freenit.config import getConfig from freenit.models.metaclass import AllOptional -from freenit.models.ormar.base import OrmarBaseModel, OrmarUserMixin +from freenit.models.ormar.base import OrmarBaseModel, OrmarUserMixin, ormar_config from freenit.models.role import Role -config = getConfig() - class BaseUser(OrmarBaseModel, OrmarUserMixin): def check(self, password: str) -> bool: @@ -29,9 +26,7 @@ async def login(cls, credentials) -> BaseUser: class User(BaseUser, OrmarUserMixin): - class Meta(config.meta): - type = "ormar" - tablename = "users" + ormar_config = ormar_config.copy() roles = ormar.ManyToMany(Role, unique=True) diff --git a/freenit/models/pagination.py b/freenit/models/pagination.py index 954ea2e..9776df2 100644 --- a/freenit/models/pagination.py +++ b/freenit/models/pagination.py @@ -2,12 +2,12 @@ from typing import Generic, List, TypeVar from fastapi import HTTPException -from pydantic import Field, generics +from pydantic import Field, BaseModel T = TypeVar("T") -class Page(generics.GenericModel, Generic[T]): +class Page(BaseModel, Generic[T]): total: int = Field(0, description=("Total number of items in DB")) page: int = Field(0, description=("Current page")) pages: int = Field(0, description=("Total number of pages")) diff --git a/freenit/models/safe.py b/freenit/models/safe.py index 73c9d1b..4ac7ce7 100644 --- a/freenit/models/safe.py +++ b/freenit/models/safe.py @@ -1,7 +1,7 @@ from freenit.models.role import Role from freenit.models.user import User -if User.Meta.type == "ormar": +if User.dbtype() == "ormar": from ormar.queryset.field_accessor import FieldAccessor RoleSafe = Role.get_pydantic(exclude={"users__password"}) @@ -13,7 +13,7 @@ include_fields.add(attr) UserSafe = User.get_pydantic(exclude={"password"}, include=include_fields) -elif User.Meta.type == "bonsai": +elif User.dbtype() == "bonsai": from freenit.config import getConfig config = getConfig()