atinux / nuxt-auth-utils

Add Authentication to Nuxt applications with secured & sealed cookies sessions.
MIT License
974 stars 91 forks source link

Add method to set user session on the client #199

Open tobiasdiez opened 1 month ago

tobiasdiez commented 1 month ago

The playground contains the following logic to login a user: https://github.com/atinux/nuxt-auth-utils/blob/e0396255b2ebc6b3ef89b9dd62f0eb0fbf345389/playground/components/AuthLogin.vue#L10-L17

This triggers two requests: one for the login, the other one to get the session data. If there were a method setSession or loggedIn then one could return the session information as part of the login response.

atinux commented 1 month ago

This would mean to add hooks to $fetch that can bring side-effects actually, I rather keep it separated ad this applied only for email/password kind of login.

tobiasdiez commented 1 month ago

What I had in mind was to add a method

setSessionState(value) {
   useSessionState().value = value
   const authReadyState = useAuthReadyState()
   if (!authReadyState.value) {
    authReadyState.value = true
  }
}

that then can be used in the login flow as follows:

await $fetch('/api/login', { 
     method: 'POST', 
     body: { 
       email: target.email.value, 
       password: target.password.value, 
     }, 
   }).then((value) => { 
      setSessionState(value)
     // previously this was fetch() 
   })

And perhaps expose the server-side helper that currently sets the fetch return, so that one can use this to return the same value in the login api.