ScopeKey fails to function properly within the Nuxt.js auth module

As I delved into learning the ins and outs of Nuxt.js, I encountered a challenge while working with its Auth module.

After successfully logging in, my goal was to verify the scope of the accounts. I attempted to achieve this by utilizing the "scopeKey" property of "Auth". The backend provides the "scope" from the database, which can either be "user" or "admin".

I experimented with setting the scope using

scopeKey: 'scope'

However, I found that the scope returned as "undefined"/"null" when checking with

this.$auth.hasScope('admin') / this.$auth.hasScope('user')

or "this.$auth.hasScope(admin)" yielded an empty result when configuring "scopeKey" as

scopeKey: 'data.scope'

or

scopeKey: 'user.scope'

Here is my current auth strategy:

auth: {
    strategies: {
      local: {
        scopeKey: 'scope',
        endpoints: {
          login: {
            url: 'api/auth/login',
            method: 'post',
            propertyName: 'token',
          },
          logout: {
            url: 'api/auth/logout',
            method: 'get'
          },
          user: {
            url: 'api/me',
            method: 'get',
            propertyName: data
          }
        }
      }
    },
    redirect: {
      login: '/auth/login',
      logout: '/',
      callback: '/auth/login',
      home: '/dash/'
    }
  }

Additionally, here is a snippet of the JSON structure that the auth module references upon login:

"data": {
        "id": 2,
        "name": "test1",
        "email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="86f2e3f5f2c6f2e3f5f2a8e5e9eb">[email protected]</a>",
        "email_verified_at": null,
        "scope": "admin",
        "created_at": "2019-08-01 13:11:49",
        "updated_at": "2019-08-01 13:11:49"
    },

While I am able to access the scope value on the frontend page with

$auth.user.scope

or

$auth.$state.user.scope

The challenge remains in assigning the "scope" to the "scopeKey" property within the nuxt.config.js file when defining the "auth" properties/strategy.

Edit:

I have explored moving it inside the auth object or removing the property altogether, yet I continue to receive false results for $auth.hasScope('admin') and $auth.hasScope('user'), indicating that scopeKey remains undefined, leaving me puzzled.

Answer №1

The default scopeKey is 'scope', so there's no need to set it again.

In my case, making a server-side change solved the issue for me.

It seems that when I tried putting a string value in scope, it didn't work as expected.

$data['scope'] = "admin";

However, when I changed it to an array, using $auth.hasScope('admin') worked perfectly;

$data['scope'] = array("admin", "test");

I hope this information proves helpful.

Answer №2

The placement of scopeKey: 'scope' within the strategies object is incorrect.

Instead, it should be directly placed in the auth object.

To see an example, refer to the default configuration file.

Additionally, you can remove this property from your auth configuration because the default value for scopeKey is 'scope'.

Answer №3

For some reason, I found that hasScope() isn't working for me either. Instead, I directly checked the user object and confirmed that I have a token in my response. I've included a type variable in my response that indicates whether the user is an admin or someone else.

You can integrate this into your middleware:

export default function ({ $auth, redirect }) {

    if (!$auth.loggedIn) {
        return redirect('/')
    }
    if ($auth.user.type != 'Super Admin') {  // Replace 'Super Admin' with the specific user type you want to check
        return redirect('/')
    }
}

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered: _moment2.default.date is not a recognized function within the React application

I keep encountering an issue when attempting to utilize a date from Moment.js in the constructor, componentWillMount, or componentDidMount. The error message I receive is: Uncaught TypeError: _moment2.default.date is not a function It's worth noting ...

Tips for transferring information from a C++ program to JavaScript

Currently, I am in the process of creating a jQuery-based pivot table for a desktop application using C++. The application will retrieve data from a database, pass it to an HTML page, and display it using a pivot table plugin. Since there is no web server ...

When using `JSON.stringify`, the resulting data may vary from the original object

Here is the code snippet in question: console.log("444444: ", profile, JSON.stringify(profile)) Upon checking the log output: https://i.stack.imgur.com/LzalV.png I am trying to understand why I cannot see the value: [0] present Additionally, ...

Employ the useEffect hook to make a constant post request

I have encountered a perplexing issue while working on a basic To-Do list web application that utilizes a MongoDB database. Despite having the functionality in place, I noticed that my useEffect hook is continuously sending an excessive number of post requ ...

Tips for sending functions from client to server in Node.js

I'm working with this code snippet: const http = require('http'); const fs = require('fs'); const handleRequest = (request, response) => { response.writeHead(200, { 'Content-Type': 'text/html' ...

Best practices for bulk inserting sequences in Node.js using MySQL

I have a dataset ready to be inserted into a MySQL database using nodejs. Here is the code I've written: con.connect(function (err) { myArray.forEach((el)=>{ con.query(1stQuery,1stValue,(error,result)=>{ //do something with ...

Is it possible to update the version of NPM?

Having an issue with installing packages for my React-Native project due to a NPM version error. How can I upgrade it? Currently using version 4 ...

Vue Transition for collapsing elements

I'm trying to incorporate Vue's collapse feature into my code, but I'm encountering an error. [Vue warn]: <transition-group> children must be keyed: <p> The component in question: <template xmlns:v-model="http://www.w3.org ...

How can aframe be integrated and utilized in Vue applications?

Trying to integrate aframe with vue-cli has been a challenge for me. I've experimented with adding aframe directly in the index.html file, as well as importing it in my top level main.js file, but I haven't had any success in getting Vue to recog ...

Utilizing TypeORM to selectively choose data in OneToMany relationships

I am looking to create a TypeORM query that pulls data from the database. Specifically, I want to retrieve all clients who have made a purchase but have not initiated a return. Here is the structure of the database: Clients: Id (Int, primary column) Purc ...

The issue encountered while attempting to utilize jspdf for exporting data

Currently, I am working on developing a web application using angularJS in combination with asp.net. My main goal is to export data into a PDF file, but unfortunately, I am facing some challenges in achieving this. While browsing on StackOverflow, I came ...

The utilization of conditional expression necessitates the inclusion of all three expressions at the conclusion

<div *ngFor="let f of layout?.photoframes; let i = index" [attr.data-index]="i"> <input type="number" [(ngModel)]="f.x" [style.border-color]="(selectedObject===f) ? 'red'" /> </div> An error is triggered by the conditional ...

activate the button once valid input has been provided

How can I enable a button based on the amount entered? Let's say there is a minimum of 100 and a maximum of 200. If the user enters an amount below 100, display an error message and keep the button disabled. If the user enters an amount above 200, ...

What is preventing the specific value in React state from being updated?

Starting off as a beginner, but I'm giving it a shot: In my React project, users input landing pages and I aim to extract data from these pages using JQuery and RegEx, then update the state with the extracted value. The issue I'm facing is that ...

What location is optimal for storing ng-templates within an Angular/Django single-page application?

My project involves using Django and AngularJS to create a single-page application. I have numerous ng-templates structured like this: <script type="text/ng-template" id="item.html"> // content </script> Currently, all these templates are l ...

Retrieve properties from parent components at a higher level and pass them down to their nested children components

I'm currently working on a project that relies on access to a property injected at the top level of a VueJS application. To retrieve this property, I've been using: this.$parent.$attrs.propertyname While this method works effectively, I now fin ...

Error with WooCommerce checkout causing input values to disappear upon clicking or submitting

I am facing an issue where I need to set #billing-postcode to a specific value using a JS script. When I input jQuery('#billing-postcode').val('2222') on the checkout page, the input displays the value 2222 with the Postcode label abov ...

The alignment issue persists when attempting to set 'relative' on the parent and 'absolute' on the inner element in a Bootstrap column for bottom alignment

Here is a snippet of my basic HTML code: <div class = "row"> <div class = "col-xs-8"> <p>long long long long text that generates a taller column</p> </div> <div class = "col-xs-4"> <p> ...

"Step-by-step guide on adding a new row to a table using a child controller in AngularJS

I have a table where I can insert new rows by opening a dialog window and entering the data. The dialog window contains a child controller called addNewTaskCtrl. Inside this dialog, there is a form that inserts data into the table when the "Add" button is ...

Is there a way to stop vue-panZoom from functioning temporarily?

I am working with a Grid that includes the use of vue-panZoom. Within the Grid, there is a section that utilizes vue-draggable-resizable, similar to what is depicted in the image below: Image When I drag the gray square (vue-draggable-resizable), the bl ...