loggedIn is always true under all circumstances

begueradj
40
begueradj
commented 9 months ago

Version

v4.5.1

Reproduction link

https://auth.nuxtjs.org/

Steps to reproduce

Perform the normal settings suggested by the official documentation

What is expected ?

loggedIn must not be true when the user is not logged in.

What is actually happening?

I just launch the server, loggedIn gets set to true even if I did not authenticate the user and , even when I clear the browser's cache, history, data … even when my REST API server is off.

Additional comments?

I saw similar issues related to this. I applied every single solution I found in vain.
I am not using sessions, cookies or whatever. I just want to store my JWT token in localStorage. Whether this JWT is stored or not, loggedIn is always true.
This bug made me loosing trust in this module because almost all other functionalities depend on this famous loggedIn flag

bug
0
cristijora
5
cristijora
commented 9 months ago

Facing same issue

0
Artkoch
0
Artkoch
commented 8 months ago

Same here. Is there a workaround?

0
janslu
0
janslu
commented 8 months ago

Have you tried downgrading nuxt to 2.4.5? This helped with my issue. Google login through nuxt-auth stopped working properly ( if (!app.$auth || !app.$auth.loggedIn) { ) was actually returning true (so loggedIn was false after successful login).

0
Artkoch
0
Artkoch
commented 8 months ago

Have you tried downgrading nuxt to 2.4.5? This helped with my issue. Google login through nuxt-auth stopped working properly ( if (!app.$auth || !app.$auth.loggedIn) { ) was actually returning true (so loggedIn was false after successful login).

Downgrading? I use "nuxt": "^2.4.0".
Any ideas how can I fix the main problem?

0
janslu
0
janslu
commented 8 months ago

Sorry, no idea about the root cause of this issue. I just wanted to signal, that there's something wrong with google login with nuxt @2.5.x and simply downgrading to 2.4.5 fixed my issue.
npm i [email protected]

0
begueradj
40
begueradj
commented 8 months ago

I did not try to downgrade because in my particular case that is not a good option. But thank you for the feedback.

0
mehrunrasoli
0
mehrunrasoli
commented 7 months ago

Also, $auth.loggedIn will not be synced with Vuex!

If I use $auth.loggedIn after user sign-in and router push, It still gives me the state of false, while it is expected to be true.

There's no problem when using $store.state.auth.loggedIn

Unfortunately, I don't have enough time till the weekend, so could anyone report this bug??

0
begueradj
40
begueradj
commented 7 months ago

@mehrunrasoli $store.state.auth.loggedIn is always true, and that is a problem.

0
ineedbots
0
ineedbots
commented 7 months ago

Think I found the issue:
https://github.com/nuxt-community/auth-module/blob/8c1567a9fd77bcebb5af41a1be31740dfded95a8/lib/schemes/local.js#L75

When the user endpoint is disabled, it'll always set the user to {}, thus setting loggedIn to true.

You can see the two if statements reversed here:
https://github.com/nuxt-community/auth-module/blob/8c1567a9fd77bcebb5af41a1be31740dfded95a8/lib/schemes/oauth2.js#L90

0
begueradj
40
begueradj
commented 7 months ago

Interesting. I will check that. Thank you @ineedbots
(I found a workaround to make it work, but I will share it when I will do a full investigation about it)

0
begueradj
40
begueradj
commented 7 months ago

Indeed, it seems the default behavior is to set up the user endpoint

0
cschweda
5
cschweda
commented 7 months ago

I stumbled on that as well. I ditched the out-of-the-box local scheme and went with a custom scheme that's essentially a (slightly) edited version of 'local'. I could never get the local scheme working.

I'm using an API created by Strapi, so, for example, there's no logout endpoint. And the user endpoint is /users/me. I also added a bunch of event emitters to figure out what the heck the scheme was actually doing -- and when it was doing it. I listen for the events on a debugger component that just logs everything out to the console.

I created a schemes folder and then a file called strapi.js:

import { EventBus } from '~/event-bus'

export default class LocalScheme {
  constructor(auth, options) {
    this.$auth = auth
    this.name = options._name

    this.options = Object.assign({}, DEFAULTS, options)
  }

  _setToken(token) {
    if (this.options.globalToken) {
      // Set Authorization token for all axios requests
      this.$auth.ctx.app.$axios.setHeader(this.options.tokenName, token)
      EventBus.$emit('debug', ` _setToken(): ${token}`)
    }
  }

  _clearToken() {
    if (this.options.globalToken) {
      // Clear Authorization token for all axios requests
      this.$auth.ctx.app.$axios.setHeader(this.options.tokenName, false)
      EventBus.$emit('debug', ` _clearToken(): ${this.options.tokenName}`)
    }
  }

  mounted() {
    if (this.options.tokenRequired) {
      const token = this.$auth.syncToken(this.name)
      this._setToken(token)
      EventBus.$emit('debug', ` mounted() => this._setToken(${token})`)
    }
    EventBus.$emit('debug', ` mounted() => this.$auth.fetchUserOnce()`)
    return this.$auth.fetchUserOnce()
  }

  async login(endpoint) {
    if (!this.options.endpoints.login) {
      return
    }

    // Ditch any leftover local tokens before attempting to log in
    await this._logoutLocally()
    try {
      const result = await this.$auth.request(
        endpoint,
        this.options.endpoints.login
      )
      EventBus.$emit('debug', `login(): ${result}`)
      if (this.options.tokenRequired) {
        const token = this.options.tokenType
          ? this.options.tokenType + ' ' + result
          : result

        this.$auth.setToken(this.name, token)
        this._setToken(token)
      }

      return this.fetchUser()
    } catch (e) {
      EventBus.$emit('error', e.response.data)
      EventBus.$emit('debug', `Error: ${JSON.stringify(e.response.data)}`)
      console.log(e)
    }
  }

  async setUserToken(tokenValue) {
    // Ditch any leftover local tokens before attempting to log in
    await this._logoutLocally()

    if (this.options.tokenRequired) {
      const token = this.options.tokenType
        ? this.options.tokenType + ' ' + tokenValue
        : tokenValue

      this.$auth.setToken(this.name, token)
      this._setToken(token)
    }
    EventBus.$emit('debug', `setUserToken(): ${token}`)
    return this.fetchUser()
  }

  async fetchUser(endpoint) {
    // User endpoint is disabled.
    // if (!this.options.endpoints.user) {
    //   this.$auth.setUser({})
    //   return
    // }

    // Token is required but not available
    if (this.options.tokenRequired && !this.$auth.getToken(this.name)) {
      return
    }

    // Try to fetch user and then set
    try {
      const user = await this.$auth.requestWith(
        this.name,
        endpoint,
        this.options.endpoints.user
      )
      this.$auth.setUser(user)
      EventBus.$emit('debug', `fetchUser(): ${JSON.stringify(user)}`)
    } catch (e) {
      EventBus.$emit('debug', `fetchUser() error: ${e}`)
    }
  }

  async logout(endpoint) {
    // Only connect to logout endpoint if it's configured
    if (this.options.endpoints.logout) {
      await this.$auth
        .requestWith(this.name, endpoint, this.options.endpoints.logout)
        .catch(() => {})
    }

    // But logout locally regardless
    return this._logoutLocally()
  }

  async _logoutLocally() {
    if (this.options.tokenRequired) {
      this._clearToken()
    }
    EventBus.$emit('debug', '_logoutLocally() => this.$auth.reset()')
    return this.$auth.reset()
  }
}

const DEFAULTS = {
  tokenRequired: true,
  tokenType: 'Bearer',
  globalToken: true,
  tokenName: 'Authorization'
}

Then in my nuxt.config.js I use the strapi scheme:

auth: {
    plugins: ['~/plugins/auth.js'],
    cookie: true,
    resetOnError: true,
    redirect: {
      login: '/login',
      logout: '/',
      callback: '/login',
      home: '/'
    },
    strategies: {
      // local: false,

      strapi: {
        _scheme: '~/schemes/strapi.js',
        endpoints: {
          login: {
            url: '/auth/local',
            method: 'post',
            propertyName: 'jwt'
          },

          user: {
            url: '/users/me',
            method: 'get'
          }
        }
      }
    }
  },

And in login.vue, my authenticate method looks like this:

methods: {
    authenticate() {
      this.$auth.loginWith('strapi', {
        data: {
          identifier: this.$refs['identifier'].value,
          password: this.$refs['password'].value
        }
      })
    },

I also had issues with redirecting after authenticating. I ended up using the auth plugin here referenced here: https://github.com/nuxt-community/auth-module/issues/134

Anyway, I think -- think -- I have it working now. I'm using it in a new project w/Nuxt 2.6.3, and it works as I expect -- no issues.

0
begueradj
40
begueradj
commented 7 months ago

@cschweda So you set the user endpoint as @ineedbots suggested.
Thank you both.

0
begueradj
40
begueradj
commented 5 months ago

In fact setting the user endpoint as suggested above by @ineedbots does not work either. After I implemented it, I remembered finally I tried this option before complaining here (and after using a trick of my own which is not too clean to share). I also found some bloggers who set this user endpoint but logging out does not protect the authenticated routes.

0
begueradj
40
begueradj
commented 3 months ago

Just in case this be helpful for someone: I do not face this issue with some other Nuxt.js versions I tested.

0
BabyDino
0
BabyDino
commented a month ago

I do confirm that we experience the same issue. When setting user to false an empty object is set, which sets loggedIn to true.

https://github.com/nuxt-community/auth-module/blob/e21de05cdf65deea67dbc1215ccb08673a7232bb/lib/core/auth.js#L251

This function is responsible for that. The Boolean on an empty object ({}) returns true.

0
begueradj
40
begueradj
commented a month ago

Which Nuxt.s version are you using ? @BabyDino

0
BabyDino
0
BabyDino
commented a month ago

@begueradj v2.10.1

0
Informations
Bug ReportOpen
#c299 - Created 9 months ago