Exploring Nuxt Auth Module: Retrieve a user using their id or username

I'm currently in the process of incorporating the 'Nuxt Auth Module' into my Nuxt App.

After setting up my Proxy & Auth Modules and establishing the 'Local Strategy,' I encountered some confusion.

Although my 'Login' endpoint is functioning correctly, with the 'propertyName' set to 'access_token' where the token value resides, I am puzzled by the workings of the 'User' endpoint.

The provided example is as follows:

auth: {
  strategies: {
    local: {
      endpoints: {
        login: { url: '/api/auth/login', method: 'post', propertyName: 'token' },
        logout: { url: '/api/auth/logout', method: 'post' },
        user: { url: '/api/auth/user', method: 'get', propertyName: 'user' }
      },
      tokenRequired: true,
      tokenType: 'bearer'
    }
  }
}

My configuration aligns closely with this setup. How does the 'User' endpoint identify the logged-in user?

In my case, I am using a third-party authentication system for integration purposes. Their REST 'User' endpoint necessitates an 'ID' or 'UserName' to fetch user details.

Given that my 'Login' response includes a 'UserName,' I believe it can be utilized to call the subsequent User endpoint if I comprehend the process.

If anyone has insights on how the User endpoint functions, I could greatly benefit from guidance:

          user: {
            url: '/users/${userId}',
            method: 'get',
            propertyName: 'data'
          }

Answer №1

Dealing with this issue as well.

This is how I resolved it:

  1. Adjust the user property of the auth endpoint to false
auth: { 
    strategies: {
      local: {
        endpoints: {
          // login API
          login: {  
            url: '/api/v1/users/login',
            method: 'post',
            propertyName: 'token'
          },
          // logout API
          logout: {
            url: '/api/v1/users/logout',
            method: 'post'
          },
          user: false // set user fetch API to false
        },
        redirect: {
          login: '/login',
          logout: '/login',
          callback: '/login',
          home: '/'
        },
      }
    }
  },

  1. After performing loginWith(), utilize the function setUniversal(key, value, isJson) to store the fetched user and retrieve it using the function getUniversal(key)
  async login(user) {
    await this.$auth.loginWith('local', {
      data: user
    }).then(res => {

      let user = res.data.data.user // retrieve user (may vary)
      this.$auth.$storage.setUniversal('user', user, true) // store user in Vuex, cookies, and local storage

      user = this.$auth.$storage.getUniversal('user') // retrieve user (usable throughout app)
      console.log(user) // verify user

      this.$router.push('/') // redirect after login
    }).catch(err => {
      console.log(err.response)
    })
  }
  1. That's it, you now have your user accessible in Vuex, cookies, and local storage; access it in computed like this:
computed: {
  user() {
    return this.$auth.$storage.getUniversal('user');
  }
}

P.S: for logging out, utilize the logout() function, and for cleanup use

this.$auth.$storage.removeUniversal('user')
to clear it from all sources

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

Seeking advice on resolving issues when utilizing a router in React and encountering errors

Error: Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined. You likely forgot to export your component from the file it's defined in, or you might have mixed up default ...

Converting javascript html object lowercase

Is there a way to dynamically adjust the height of specific letters in my label? Right now, I am overriding the text for the elements: let element = document.getElementById('xxx') element.textContent = 'Label' I attempted using <sup ...

Tips for resolving an issue with mongoose Model.create becoming unresponsive indefinitely

I'm having trouble understanding why my mongoose Model.create operation isn't completing successfully. The same connection is working well with other controller functions. vscode postman I am attempting to create a new document, but my code s ...

React does not accept objects as valid children

Currently, I am working on developing a stopwatch using reactive js. Here is the code snippet that I have been working on: <div id="root"></div> <script src="https://unpkg.com/library/react.development.js"></script> <script sr ...

Troubleshoot: Why is fs.createReadStream in node.js only reading the last line of

Hello, I am currently facing some frustrating issues while trying to stream the contents of my CSV file. Below is the code snippet I am using, and my struggles are hidden in the comments. var fileReadStream = fs.createReadStream(inFile); // I&a ...

Preserving Foreign Key Relationships in Django Rest Framework Serializers

Within my project, I have two interconnected models named Task and Batch, linked through a Foreign Key field. My goal is to verify the existence of a Batch Object in the database before creating a new Task Object. The Batch object represents the current da ...

Steps to ensure a dropdown menu remains expanded when its nested menu is selected

Check out this dropdown list here, but the issue arises when clicking on a nested menu item such as "Books Registration". Once that page loads, the dropdown menu collapses like shown here. Here's a snippet of the dropdown code: <ul class="nav nav- ...

Exploring Nuxt.js internationalization (i18n) features: A step-by-step guide

I recently came across an example of internationalization (i18n) in the Nuxt.Js documentation. While I understand most of it, I am curious about how clicking on the Language option in the Navbar menu can switch the locale from 'en' to 'fr&ap ...

Reset ng-model when ng-show is not active in AngularJS

Hey there, I'm facing a little issue. I have an input field that sometimes needs to be displayed in a form and sometimes not. I'm worried that if someone enters data, hides it, and then hits send, the data will still be sent. That's why I w ...

Click on a button to initiate the download of a collection of images

In my simple HTML structure, there is a button designed for downloading purposes: <div id="getImageWrapper"> <div class="image"> <p class="image-name">{{imageName}}</p> <button class="download-btn" @click="ge ...

Implementing Conditional Display of Span Tags in React Based on Timer Duration

In my current React project, I am facing an issue with displaying a span tag based on a boolean value. I need assistance in figuring out how to pass a value that can switch between true and false to show or hide the span tag. I tried two different methods ...

Step-by-step guide to utilizing instance functions in AngularJS

Recently I started working with angular in my project but I'm struggling to figure out how to access instance functions from the original code. Here is a snippet of my function: $scope.collapsedrow = true; $scope.PlusClick = function(event) ...

Error: Unable to set value on Vuejs key - the target is read-only

Currently, I am utilizing a combination of Laravel9 with Vuejs3. In one of my blade views, I pass PHP variables to a Vue component like so: <subscription-form location="{{ $props['location'] }}" orientation="{{ $props['ori ...

Unable to trigger Daterangepicker on click event within Vue component

Just starting out with JS and Vue, facing a challenge here: Check out this Fiddle I'm not seeing the popup, however when I move $('.date-range-picker').daterangepicker(...) outside of the Vue instance, everything works fine and the picker ...

Getting the Text Field Value in Material UI: A Step-by-Step Guide

I am struggling to retrieve the user's value from the text field component. Despite my efforts using material ui, hooks, and useEffect, I have not been able to achieve the desired outcome. <TextField variant="outlined" ma ...

Performing Jquery functions on several elements at once

Looking at the code snippet below, there are two buttons and an input in each container. The input calculates and adds up the number of clicks on the 2 buttons within the same container. However, it currently only works for the first container. How can thi ...

Viewing an immutable concealed field in Angular

My situation is quite unique as I have an Angular app embedded within a legacy ASP.NET webforms app (specifically in the header and footer). Authentication still happens through Webforms without any token service in place. The challenge arises when Angula ...

Is there a way to transfer the submitted data to a different page without being redirected to it using #php and #ajaxjquery?

Hey there, I could use a little assistance. How can I send data to page update.page.php when submitting a form on index.php without being redirected? I want the functionality of sending a message from one page to another without having to refresh the ent ...

Maintain the functionality, but disable all stylesheets and scripts

I have 4 separate pages, each with their own distinct stylesheets and scripts that I switch between using ajax and historyPopState. The issue is that downloading them repeatedly can be inefficient. I am seeking a solution to keep the stylesheets and scri ...

Type inference in TypeScript with transitivity

Consider this code snippet for illustration: function foo(t: "number"): number function foo(t: "string"): string function foo(t: "boolean"): boolean function foo(t: "number" | "string ...