Skip to content
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

How does inheritance work with ODMantic models? #508

Open
iBuitron opened this issue Nov 20, 2024 · 0 comments
Open

How does inheritance work with ODMantic models? #508

iBuitron opened this issue Nov 20, 2024 · 0 comments
Labels
bug Something isn't working

Comments

@iBuitron
Copy link

How does inheritance work with ODMantic models?

class UserBase(BaseModel, UserMixin):
    email: EmailStr
    password: SecretStr
    _engine: ClassVar[AIOEngine]

    model_config = {"arbitrary_types_allowed": True}
class User(Model, UserBase):
    email: EmailStr
    password: SecretStr
    _engine: ClassVar[AIOEngine] = engine_user

    model_config = {"collection": "qb_user"}

User inherits from UserBase, I have tried not to define the attributes in User in different ways (with pydanitc and without pydantic) but it forces me to redefine the attributes in User even though they already exist in UserBase


from typing import Any, ClassVar, Optional


from flask_login import UserMixin
from motor.motor_asyncio import AsyncIOMotorCollection
from odmantic import AIOEngine, Field, Model
from odmantic.model import _BaseODMModel
from pydantic import (
    BaseModel,
    EmailStr,
    SecretBytes,
    SecretStr,
    ValidationError,
    field_serializer,
)
from werkzeug.security import check_password_hash, generate_password_hash


class UserBase(BaseModel, UserMixin):
    email: EmailStr
    password: SecretStr
    _engine: ClassVar[AIOEngine]

    model_config = {"arbitrary_types_allowed": True}

    @classmethod
    def _collection(cls) -> AsyncIOMotorCollection:
        """Obtiene la colección asociada."""
        if not hasattr(cls, "_engine") or not cls._engine:
            raise ValueError("Cada subclase debe definir un engine.")
        return cls._engine.get_collection(cls)  # type: ignore

    def get_id(self):
        """The return of this method is stored in the session and use in the user_loader from flask_login"""
        return self.email

    #! ------------  EXTRA FIELDS -------------------------
    # projects: list[Project] = Field(default_factory=list)

    @field_serializer("password")
    def dump_secret_password(self, v: SecretStr) -> str:
        """User for serializer the password when uses _engine.save()"""
        return v.get_secret_value()

    def _encrypt_password(self) -> None:
        secret_pw = self.password.get_secret_value()
        self.password = generate_password_hash(secret_pw)  # type: ignore

    def _check_password(self, password: str) -> bool:
        return check_password_hash(
            pwhash=self.password.get_secret_value(),
            password=password,
        )

    @classmethod
    async def create_user(cls, email: str, password: str):
        collection = cls._collection()
        _user = await collection.find_one(
            {"email": email},
        )

        if _user:
            raise ValueError("User already exists")

        _new_user = cls(email=email, password=password)
        _new_user._encrypt_password()
        _stored_user = await cls._engine.save(_new_user)

        if _stored_user:
            return str(_stored_user.id)

        raise ValueError("User not created")

    @classmethod
    async def login_user(cls, email: str, password: str) -> "UserBase":
        user = await cls._engine.find_one(cls, cls.email == email)

        if user and user._check_password(password):
            return user

        raise ValueError("User not found or password incorrect")
if __name__ == "__main__":
    email = "[email protected]"
    password = "aa"
    user = User

    async def main():
        r = await user.create_user(email, password)
        print(r)

    import asyncio

    asyncio.run(main())

if comments

class User(Model, UserBase):
    # email: EmailStr
    # password: SecretStr
    _engine: ClassVar[AIOEngine] = engine_user

    model_config = {"collection": "qb_user"}

image

@iBuitron iBuitron added the bug Something isn't working label Nov 20, 2024
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug Something isn't working
Projects
None yet
Development

No branches or pull requests

1 participant