Skip to content

Commit

Permalink
Merge pull request #130 from mekanix/feature/ormar
Browse files Browse the repository at this point in the history
Update to newer ormar
  • Loading branch information
mekanix committed Apr 3, 2024
2 parents 0928b65 + 63d8fd5 commit 0108590
Show file tree
Hide file tree
Showing 12 changed files with 72 additions and 63 deletions.
4 changes: 3 additions & 1 deletion bin/devel.sh
Original file line number Diff line number Diff line change
@@ -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
Expand Down
42 changes: 27 additions & 15 deletions bin/freenit.sh
Original file line number Diff line number Diff line change
Expand Up @@ -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<<EOF
{
"useTabs": false,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"semi": false,
}
EOF

case `uname` in
*BSD)
${SED_CMD} '' -e "s/export default defineConfig/const config = defineConfig/g" vite.config.ts
${SED_CMD} '' -e "s/export default defineConfig/const config = defineConfig/" vite.config.ts
${SED_CMD} '' -e "s/^}//" package.json
${SED_CMD} '' -e 's/"type": "module"/"type": "module",/' package.json
${SED_CMD} '' -e "s/adapter-auto/adapter-node/" svelte.config.js
;;
*)
${SED_CMD} -e "s/export default defineConfig/const config = defineConfig/g" vite.config.ts
${SED_CMD} -e "s/export default defineConfig/const config = defineConfig/" vite.config.ts
${SED_CMD} -e "s/^}//" package.json
${SED_CMD} -e 's/"type": "module"/"type": "module",/' package.json
${SED_CMD} -e "s/adapter-auto/adapter-node/" svelte.config.js
;;
esac
cat >>vite.config.ts<<EOF
Expand All @@ -433,6 +426,25 @@ if (process.env.BACKEND_URL) {
export default config
EOF

cat >>package.json<<EOF
"overrides": {
"rollup": "npm:@rollup/wasm-node"
}
}
EOF
cat >.prettierrc<<EOF
{
"useTabs": false,
"singleQuote": true,
"trailingComma": "all",
"printWidth": 80,
"semi": false,
}
EOF
npm install
frontend_common
npm install --save-dev @zerodevx/svelte-toast @freenit-framework/svelte-base @sveltejs/adapter-node @mdi/js

rm -rf src/lib
rm -rf src/routes/about src/routes/sverdle src/routes/*.svelte

Expand Down
4 changes: 2 additions & 2 deletions freenit/api/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,9 +25,9 @@ async def get(
perpage: int = Header(default=10),
_: User = Depends(user_perms),
) -> 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)
Expand Down
8 changes: 4 additions & 4 deletions freenit/app.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
18 changes: 9 additions & 9 deletions freenit/auth.py
Original file line number Diff line number Diff line change
Expand Up @@ -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

Expand All @@ -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)
Expand All @@ -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")


Expand All @@ -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")
Expand All @@ -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


Expand Down
6 changes: 0 additions & 6 deletions freenit/base_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -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}>"
Expand Down
16 changes: 16 additions & 0 deletions freenit/models/ormar/base.py
Original file line number Diff line number Diff line change
@@ -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()
Expand All @@ -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,
)
11 changes: 3 additions & 8 deletions freenit/models/ormar/role.py
Original file line number Diff line number Diff line change
@@ -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()
9 changes: 2 additions & 7 deletions freenit/models/ormar/theme.py
Original file line number Diff line number Diff line change
@@ -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)
Expand Down
9 changes: 2 additions & 7 deletions freenit/models/ormar/user.py
Original file line number Diff line number Diff line change
Expand Up @@ -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:
Expand All @@ -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)

Expand Down
4 changes: 2 additions & 2 deletions freenit/models/pagination.py
Original file line number Diff line number Diff line change
Expand Up @@ -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"))
Expand Down
4 changes: 2 additions & 2 deletions freenit/models/safe.py
Original file line number Diff line number Diff line change
@@ -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"})
Expand All @@ -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()
Expand Down

0 comments on commit 0108590

Please sign in to comment.