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

Why isnt expire set in useStrapiToken and setToken in useStrapiAuth? #364

Closed
tobiasb4c opened this issue Oct 13, 2023 · 6 comments
Closed
Labels
question Further information is requested

Comments

@tobiasb4c
Copy link

tobiasb4c commented Oct 13, 2023

No Expire Date set when setting auth Cookie (strapi_jwt)

My Problem is that the cookie is gone after Reloading the Page because the Cookie expires on Session

The token is getting fetched in useStrapiAuth

const { jwt }: StrapiAuthenticationResponse = await client('/auth/local', { method: 'POST', body: data })
setToken(jwt)

And then set in setToken

 const setToken = (value: string | null) => {
    token.value = value
  }

But only the value is asigned

Also in useStrapiToken only the name and value is set but no expires:


export const useStrapiToken = () => {
  const nuxt = useNuxtApp()
  const config = process.server ? useRuntimeConfig() : useRuntimeConfig().public

  nuxt._cookies = nuxt._cookies || {}
  if (nuxt._cookies[config.strapi.cookieName]) {
    return nuxt._cookies[config.strapi.cookieName]
  }

  const cookie = useCookie<string | null>(config.strapi.cookieName, config.strapi.cookie)
  nuxt._cookies[config.strapi.cookieName] = cookie
  return cookie
}
@tobiasb4c tobiasb4c added the question Further information is requested label Oct 13, 2023
@tobiasb4c tobiasb4c changed the title Why isnt expire set in useStrapiToken and setToken in in useStrapiAuth? Why isnt expire set in useStrapiToken and setToken in useStrapiAuth? Oct 13, 2023
@tobiasb4c
Copy link
Author

OK I just noticed that i can define the maxAge of the cookie in nuxt config. Now my cookie does get a expire date but on Page reload the cookie is gone

@watzon
Copy link

watzon commented Nov 5, 2023

I'm having this issue as well. Doesn't matter what I do, something is deleting the cookie. If I change the name of the cookie before a refresh it stays, so that rules out anything having to do with the cookie itself.

@watzon
Copy link

watzon commented Nov 5, 2023

Ahh this appears to have been fixed in #354

@tobiasb4c
Copy link
Author

Does this work for you? The Nuxt Module didnt work out for me, no matter what hostname the cookie gets. When I changed the domain name from the to cookie from 'domain.com' to '.domain.com' the cookie stayed persitent.
I just wrote my own Nuxt Composable. It doesnt use types though but it works for me!

@tobiasb4c
Copy link
Author

tobiasb4c commented Nov 13, 2023

idk if that helps someone. All I change was how the cookie is set + Remember me Function

// ./compoeables/useAuth.ts
import { useAuthStore } from "../stores/authStore"

export const useAuth = () => {
    //Auth
    const authStore = useAuthStore()
    const runtimeConfig = useRuntimeConfig()
    const url = runtimeConfig.public.strapiUrl + runtimeConfig.public.strapiApiBase;

    const setToken = (token: string | null, rememberMe: boolean = true) => {
        let maxAge: number | undefined = (24 * 60 * 60) * 365
        authStore.setToken(token)
        if(!rememberMe){
          maxAge = undefined
        }
        const jwt = useCookie<string | null>('jwt', {
          maxAge: maxAge,
          secure: true,
        })
        jwt.value = token
    }

    const setUser = (user: any) => {
        authStore.setUser(user)
    }

    const initAuth = () => {
      const jwt = useCookie<string | null>('jwt')
      setToken(jwt.value)

      return authStore.getToken
    }

    const fetchUser = async () => {
      if (authStore.getToken) {
        try {
          let tempUser = await client('/users/me', { method: 'GET', headers: {Authorization: 'Bearer ' + authStore.getToken}})
          setUser(tempUser)
          return tempUser
        } catch (e) {
          setToken(null)
          return null
        }
      }
    }

    const client = async (path: any, fetchOptions: any) => {
      const headers = {Authorization: ''};
      if (authStore.token) {
        headers.Authorization = `Bearer ${authStore.getToken}`;
      }
      if (fetchOptions.params) {
        const params = JSON.stringify(fetchOptions.params);
        if (params) {
          path = `${path}?${params}`;
        }
        delete fetchOptions.params;
      }
      try {
        
        return await $fetch(url + path, {
          retry: 0,
          url,
          ...fetchOptions,
          headers: {
            ...headers,
            ...fetchOptions.headers
          }
        });
      }
      catch(e){

      }
    }

    //AUTH Functions
    const login = async (data: {}, rememberMe: boolean = false) => {
      setToken(null)
      const authResult: any = await client('/auth/local', { method: 'POST', body: data })
      const jwt = authResult.jwt;
      setToken(jwt, rememberMe)

      await fetchUser()
    }

    const logout = () => {
      setToken(null)
      setUser(null)
    }

    const register = async (data: {}) => {
      setToken(null)
  
      const authResult: any = await client('/auth/local/register', { method: 'POST', body: data })
      const jwt = authResult.jwt;
      setToken(jwt)
  
      await fetchUser()
    }

    const forgotPassword = async (data: {}) => {
      setToken(null)
  
      await client('/auth/forgot-password', { method: 'POST', body: data })
    }

    const resetPassword = async (data: {}) => {
      setToken(null)
  
      const authResult: any = await client('/auth/reset-password', { method: 'POST', body: data })
      const jwt = authResult.jwt
      setToken(jwt)
  
      await fetchUser()
    }

    const changePassword = async (data: {}) => {
      setToken(null)
      const authResult: any = await client('/auth/change-password', { method: 'POST', body: data })
      const jwt = authResult.jwt
      setToken(jwt)
  
      await fetchUser()
    }

    const sendEmailConfirmation = async (data: {}) => {
      await client('/auth/send-email-confirmation', { method: 'POST', body: data })
    }
  
    // CRUD CMS Functions
    
    const find = async (contentType: string, params?: any) => {
      return await client(`/${contentType}`, { method: 'GET', params })
    }

    const findOne = async (contentType: string, id?: string | number, params?: any) => {
      if (typeof id === 'object') {
        params = id
        // @ts-ignore
        id = undefined
      }
  
      const path = [contentType, id].filter(Boolean).join('/')
  
      return await client(path, { method: 'GET', params })
    }

    const create = async (contentType: string, data: any) => {
      return await client(`/${contentType}`, { method: 'POST', body: { data } })
    }

    const update = async (contentType: string, id: string | number, data?: any) => {
      if (typeof id === 'object') {
        data = id
        // @ts-ignore
        id = undefined
      }
  
      const path = [contentType, id].filter(Boolean).join('/')
  
      return await client(path, { method: 'PUT', body: { data } })
    }

    const _delete = async (contentType: string, id?: string | number) => {
      const path = [contentType, id].filter(Boolean).join('/')

      return await client(path, { method: 'DELETE' })
    }

    // CMS Media Functions
    const strapiLoadImage = async (imageName: string) => {
      const imageUrl = url + '/' + imageName + '?populate=*'

    const image = await $fetch(imageUrl);
    return null
  }

    return {
        setToken,
        setUser,
        login,
        logout,
        register,
        client,
        forgotPassword,
        resetPassword,
        changePassword,
        sendEmailConfirmation,
        fetchUser,
        initAuth,
        find,
        findOne,
        create,
        update,
        delete: _delete,
        strapiLoadImage,
    }
}

@tobiasb4c
Copy link
Author

This is how my auth middleware looks like:

export default defineNuxtRouteMiddleware(async (to, _from) => {
  const auth = useAuth()
  const router = useRouter()

  auth.initAuth()

  if (!await auth.fetchUser()){
    return router.push('/login')
  }
})

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
question Further information is requested
Projects
None yet
Development

No branches or pull requests

2 participants