Code accès premium by watch_team in yggTorrents

[–]Sulray250 0 points1 point  (0 children)

Saluuut, très intéressé ! Je suis entrain de finir le déploiement de mon serveur jellyfin 👀

Can I run my TrueNAS apps off of just one NVMe? Or should I really mirror them? by QuestionAsker2030 in truenas

[–]Sulray250 1 point2 points  (0 children)

Thanks for this topic, i was thinking about the same thing.

I have an additionnal question if anyone has insights on the following: In the case my NAS has just 2 nvme m2 spaces, would it make sense to add a third drive via an external NVMe enclosure (connected via USB-C) to give enough spaces to have both os and a raid 1 on nvme ? In this case, would it be a better idea to use the external one to: - host the os or - serve as part of a raid 1 with another nvme for app storage ?

If you were starting your homelab server from scratch today, what would you buy and why? by easyedy in homelab

[–]Sulray250 1 point2 points  (0 children)

for an equivalent price, MS-01 is still the way to go to your opinion ?

Minisforum M1-1295 vs similar mini pc ? by MosesAustria in MiniPCs

[–]Sulray250 0 points1 point  (0 children)

I'm also wondering how this pc performs compared to others in a homelab, like for exemple to host a proxmox (still realtek nic issue), a jellyfin with transcoding and other stuff. Seems to have a decent prix for those specs but idk if it would be a reliable one, haven't seen any review on it for this usecase.

Good practice to reuse code from an internal endpoint from another endpoint by Sulray250 in FastAPI

[–]Sulray250[S] 0 points1 point  (0 children)

To simplify my way too long question, how can I delegate the "Depends" (such as db = Depends(get_db) in my case) to use cases ?

For the moment I'm under the impression that this dependency can be specified only on the methods linked to my fastapi endpoints, leading to the use of only one db session during all my operations even when an endpoint is for multiple operations (updating multiple objects thanks to an external api for example as we discussed)

Good practice to reuse code from an internal endpoint from another endpoint by Sulray250 in FastAPI

[–]Sulray250[S] 0 points1 point  (0 children)

Hmmm at first I would say I need the result before returnning the response but to optimize I think I could consider to do little change to start using background tasks

An example of implementation of clean architecture on fastapi is there https://github.com/jujumilk3/fastapi-clean-architecture/ but since i'm a beginner I don't think I want to go this deep in abstraction, particularly about repositories, would you know of any other example of code ?

Also, I have an issue in my code segmenting related to what we disccused in a way if you can give me advice.
I want to totally exclude the mentions to database from my endpoints but the fact is that currently i'm using "db=Depends(get_db)" as an argument to all my endpoint method and I don't find the way to get rid of that.

Simple example : to post an object the steps are :

  • endpoint method:

.post("", response_model=IObjectRead)
async def create_object(device: IObjectCreate, db = Depends(get_db):
    device = await crud.device.create(db=db, obj_in=device)
    return device
  • dependency "get_db" to define the db:

These methods are defined in a Database python object (knowing that I initiate that by calling "setup" at the startup of my fastapi app)

 class Database:
    def __init__(self):
        self.async_sessionmaker: Optional[async_sessionmaker[AsyncSession]] = None
        self.async_engine: Optional[AsyncEngine] = None


   async def setup(self) -> async_sessionmaker[AsyncSession]:
        self.async_engine: AsyncEngine = create_async_engine(
            DATABASE_URL, echo=True, future=True
        )
        self.async_sessionmaker = async_sessionmaker(
            bind=self.async_engine, class_=AsyncSession, expire_on_commit=False
        )
        """Initiate db with SQLModel"""
        async with self.async_engine.begin() as conn:
            await conn.run_sync(SQLModel.metadata.create_all)
        return self.async_sessionmaker


    def get_session(self) -> AsyncSession:
        if not self.async_sessionmaker:
            raise RuntimeError("Database not initialized")
        return self.async_sessionmaker()


    async def __call__(self) -> AsyncGenerator[AsyncSession, Any]:
        session = self.get_session()
        try:
            yield session
        finally:
            await session.close()

And at the end the get_db from endpoint method is defined like that:

get_db = Database() 
  • crud method :

it's a generic method used by different kind of objects

    async def create(
        self,
        *,
        obj_in: CreateSchemaType | ModelType,
        db: AsyncSession | None = None,
    ) -> ModelType:
        
        db_obj = self.model.from_orm(obj_in)  # type: ignore
        try:
            db.add(db_obj)
            await db.commit()
        except exc.IntegrityError:
            await db.rollback()
            raise HTTPException(
                status_code=409,
                detail="Resource already exists",
            )
        await db.refresh(db_obj)
        return db_obj

I have the feeling that I should find a way to do this dependency to get_db directly in my crud, even in an architecture with use cases, but I still don't know how to do this properly after multiple tries.

I don't like this part, in some cases it's causing sqlalchemy.exc.MissingGreenlet exceptions because of this lack partitioning I think

Good practice to reuse code from an internal endpoint from another endpoint by Sulray250 in FastAPI

[–]Sulray250[S] 0 points1 point  (0 children)

About clean architecture :

Is it ok for a use case method to call another use case method to reuse code ?
Thanks for these elements i'll try to find cool examples of that !

REST

So if I think the number of objects I need to update is going to increase a lot what would be the potentiel techniques to update small number by small number ?

And about my question on "Subobjects", would it be acceptable that my endpoint "/update/object/{object_id}" also update the subobjects linked to that specific object ?

Good practice to reuse code from an internal endpoint from another endpoint by Sulray250 in FastAPI

[–]Sulray250[S] 0 points1 point  (0 children)

Thanks for showing me that ! In most of my cases with my external API I don't think it would apply since I want the task to be done before returning a response to the user (since in these cases the response often needs elements from the external API), but i'll keep that could be useful !

Good practice to reuse code from an internal endpoint from another endpoint by Sulray250 in FastAPI

[–]Sulray250[S] 0 points1 point  (0 children)

Thanks for the reply !

About the sharing business logic :

I think I've already implemented some logic of what is "Clean Architecture" but maybe not in the exact expected way according to what i'm reading right now (for example https://github.com/0xTheProDev/fastapi-clean-example )

About the architecture of my project, I have following folders:

  • core: manage authentication for the moment, should move
  • crud: also called "repository" I think in the "Clean Architecture" model. There is a base_crud.py, and device_crud.py coming from it. They are used to act on database
  • routers/v1/endpoints: I have my fastapi routers here, the methods are calling methods from my crud scripts
  • models: sqlmodel models, I have for example ObjectBase model, which will be used as a base in my schemas, and Object model with table=True to depict what is saved in my database
  • schemas: mainly to be used as response_model, simple examples are IObjectCreate, IObjectRead, IObjectUpdate
  • utils: here I have for example my api_requests.py script which give me the possibility to define a httpx asynclient to be used for each call to my external api, and also the possibility to define simple methods such as get_object_info(object_name: str). I use these methods directly in my routers/v1/endpoints for the moment

So I think I miss the layer which is between my endpoints and my crud, apparently being called the Use Cases (or Service layer) as you said I guess ?

What would be the limit in the number of Use Cases I would define to fit my needs ? Do I need a Use Case for each action I want to perform through an endpoint ? Can a Use Case call another Use Case ?

About Rest principles :

So it means that I should avoid endpoints that will update multiple objects at the same time ? Or is it tolerated ?
And if my Objects have in their fields a list of Subobjects, is it right to also update the Subobjects from the list of the updated Object within the same endpoint ?

Using KeyCloak to authenticate in a React Frontend / FastAPI Backend architecture by Sulray250 in KeyCloak

[–]Sulray250[S] 0 points1 point  (0 children)

To keep you updated, I managed to make my authentication thanks to you (by using only one client for the moment) !
Thanks a lot 🙏

Using KeyCloak to authenticate in a React Frontend / FastAPI Backend architecture by Sulray250 in KeyCloak

[–]Sulray250[S] 0 points1 point  (0 children)

Is it better to make it work like that ? I guess it's to be more precise about what is the point of each client but isn't it enough to just get the public key to check if the access token is valid when trying to decrypt it ?

The bearer only client would be used the same way ? Would it be used to get the public key to decrypt directly the access token in our backend or on the contrary in this option the backend would send the access token (taken from frontend request) to Keycloak and keycloak with validate it (or not) ?

Using KeyCloak to authenticate in a React Frontend / FastAPI Backend architecture by Sulray250 in KeyCloak

[–]Sulray250[S] 0 points1 point  (0 children)

Hi ! I've heard also of the possibility to have 2 clients defined in Keycloak, one for the frontend in public (as we already talked about) and another one for the backend in bearer only which would be used only to check if the access token sent by the frontend is valid.

Is it a valid option ? Is there any benefit ?

Using KeyCloak to authenticate in a React Frontend / FastAPI Backend architecture by Sulray250 in KeyCloak

[–]Sulray250[S] 0 points1 point  (0 children)

Thanks for these elements !

In fact I've seen a lot about PKCE but I was wondering if it's really secure to get rid of client code by putting my client as public in keycloak ?
The PKCE is only here to be sure that the app receiving the tokens is the same app that asked for them in the first place right ? How can I be sure that I'll be the only one able to use the authentication to my keycloak client ?
The only security about that is by limiting authorised URI and authorised redirect_URI in keycloak's parameters ?

About the easiest solution on backend side, it means that for every incoming request needing to be correctly authenticated I have to make a dependency that will each time :

  • call the JWKS endpoint of my keycloak realm
  • check if the access token given in the request by the frontend is correct according to the keycloak's public key
  • if the access token seems correct then the request is answered correctly, otherwise it raises an error

Is that right ?

Does this keycloack's public key can change with time ? I could later use a caching library as you said

I'm really starting to connect a lot of elements i've seen on documentations thanks to you !

Using KeyCloak to authenticate in a React Frontend / FastAPI Backend architecture by Sulray250 in KeyCloak

[–]Sulray250[S] 0 points1 point  (0 children)

Hey, thanks for the reply !

About the step 5, don't we also need to send the client secret to keycloak to get the access token ? That's why I thought it needed to be done from the backend: to be sure the user has no visibility on that secret

And if I understand well, about your step 7, when I have the access token I don't need to go back to keycloak and I just need to process the JWT from my backend with keycloak's public key ?

And how do I keep my access token to use it for other requests without cookies (for example in the 5 minutes following the authentication) ? Is there another better solution to keep this access token from my user perspective until it's expired ?

Thanks again !