alex-oleshkevich / starsessions

Advanced sessions for Starlette and FastAPI frameworks
MIT License
98 stars 11 forks source link

Proposal: Support dynamic set cookies lifetime for each session when save #73

Closed trisduong closed 4 weeks ago

trisduong commented 5 months ago

Like Django, we can use the function set_expiry to set the lifetime for the session. It will be helpful when we implement the remember_me function. Thanks in advance.

alex-oleshkevich commented 5 months ago

You should store your own cookie in the browser and use it to restore/start a session. There is nothing to do with this library.

trisduong commented 5 months ago

@alex-oleshkevich Currently, I do that. But if I want cookies to expire based on the browser session, the library needs to change a little.

hasansezertasan commented 5 months ago

@alex-oleshkevich Currently, I do that. But if I want cookies to expire based on the browser session, the library needs to change a little.

Can you elaborate a bit more? Maybe bring a MRE?

alex-oleshkevich commented 5 months ago

what exactly is your use case?

trisduong commented 5 months ago

@alex-oleshkevich I'm working on implementing a "remember me" function for user logins. Here's how it should work:

If the user selects "remember me," the session will remain available even after they close the browser. This is currently working as expected with the library I'm using.
If the user doesn't select "remember me," the session should expire after they close the browser. This will work if we set the session's lifetime to 0 for that specific login.

The issue I'm facing is that the library only allows us to set the session lifetime when initializing the middleware. We can't dynamically set it for each user login session.

trisduong commented 5 months ago

@alex-oleshkevich Currently, I do that. But if I want cookies to expire based on the browser session, the library needs to change a little.

Can you elaborate a bit more? Maybe bring a MRE?

Thanks. I will.

alex-oleshkevich commented 5 months ago

all you need is

  1. on login set long-living signed cookie "remember me" with user id
  2. add a custom authorization backend which will read the cookie and initialize a new session for user id

See here - https://github.com/alex-oleshkevich/kupala/blob/master/kupala/authentication.py#L46

You don't need to deal with sessions at all.