Home > OS >  How to set scope(or role) of nuxt $auth.user?
How to set scope(or role) of nuxt $auth.user?

Time:12-02

I am using nuxt-auth with google oauth2 config, here is my nuxt.config.js config:

auth: {
  scopeKey: 'scope',
  strategies: {
    google: {
      client_id: process.env.GOOGLE_KEY,
      codeChallengeMethod: '',
      scope: ['profile', 'email'],
      responseType: 'token id_token'
    }
  },
  redirect: {
    login: '/login',
    logout: '/logout',
    home: '/',
    callback: '/welcome'
  }
},
router: {
  middleware: ['auth']
},

I use this code to login

this.$auth.loginWith('google')

I want to setup a role for user (visit app database) after successful login, so I added this code to my welcome.vue (oauth2 callback page)

<script>
export default {
  mounted () {
    const user = this.$auth.user
    user['scope'] = 'some_role_from_db'
    this.$auth.setUser(user)
  }
}
</script>

but this code is never called, because application is immediately redirected to the page that user has selected before visiting login page (welcome.vue html markup is shown for 1 sec).

What is the correct way to set some attributes to this.$auth.user immediately after login? Is there some easy way to set role to user after OAUTH2 authentication?

CodePudding user response:

user roles must came from server and it wrong to define it from client side , but if that is importent you can do it like that :

this.$auth.loginWith('google').then(() => {
    const user = this.$auth.user
    user['scope'] = 'some_role_from_db'
    this.$auth.setUser(user)
})

CodePudding user response:

I've added this section to my auth object in nuxt.config.js

rewriteRedirects: false

and so my app always redirects me to home url, and on home page I can access auth object like

<script>
export default {
  mounted () {
    const user = this.$auth.user
    user['scope'] = 'some_role_from_db'
    this.$auth.setUser(user)
  }
}
</script>
  • Related