How do I make the parameters in the user auth be dynamic? - vue.js

My auth in nuxt.config.js like this :
auth: {
redirect: {
login: '/',
home: '/home',
logout: '/'
},
strategies: {
local: {
endpoints: {
login: {
url: '/api/token',
method: 'post',
propertyName: 'response.token'
},
user: {
url: '/api/references?number=1122334433221&name=chelsea&birthDate=1995-03-18',
method: 'get',
propertyName: 'data'
},
logout: {
url: '/api/logout',
method: 'post'
}
},
tokenRequired: true,
tokenType: 'Bearer '
}
},
token: {
name: 'token'
},
cookie: {
name: 'token'
}
}
In endpoint user, I put number, name and birthDate statically. How do I make it dynamic? So the parameter is taken from the data
data () {
return {
auth: {
name: '',
number: '',
birthday: null
}
}
}
When submit login, it will call this :
methods: {
submit () {
this.$auth.loginWith('local', {
data: {
username: 'mycompany',
password: '123123123'
}
}).then((resp) => {
this.SET_IS_AUTH(true)
this.$router.push('/home')
}).catch(() => {
console.log('error')
})
}
}
Update (Using try catch)
methods: {
...mapMutations(['SET_IS_AUTH']),
async fetchUserInfo () {
const user = await this.$axios.$get(`/api/references?number=${this.auth.number}&name=${this.auth.name}&birthDate=${this.auth.birthday}`)
this.$auth.setUser(user)
},
submit () {
if (this.$refs.form.validate()) {
try {
this.$auth.loginWith('local', {
data: {
username: process.env.USERNAME,
password: process.env.PASSWORD
}
}).then((resp) => {
this.fetchUserInfo()
this.SET_IS_AUTH(true)
this.$router.push('/home')
})
} catch(err) {
commit('SET_ERROR', err)
}
}
}
}

Since you are setting the user endpoint in nuxt.config.js you won't be able to dynamically pass in the endpoint URL. However, you can achieve the outcome by passing false to the user endpoint like so:
auth: {
redirect: {
login: '/',
home: '/home',
logout: '/'
},
strategies: {
local: {
endpoints: {
login: {
url: '/api/token',
method: 'post',
propertyName: 'response.token'
},
user: false,
logout: {
url: '/api/logout',
method: 'post'
}
},
tokenRequired: true,
tokenType: 'Bearer '
}
},
token: {
name: 'token'
},
cookie: {
name: 'token'
}
}
Then you can use axios to make the request to get the user details manually passing in your dynamic values and then setting the user values for the auth module. For example perhaps when the user logs in, you can then have a method called fetchUserInfo and it would look like so:
export default {
data () {
return {
auth: {
name: '',
number: '',
birthday: null
}
}
},
methods: {
async fetchUserInfo() {
const user = await this.$axios.$get(`/api/references?number=${this.auth.number}&name=${this.auth.name}&birthDate=${this.auth.birthDate}`)
// Sets the user info using the setUser method on the auth module
this.$auth.setUser(user)
}
}
}
Here is a link to the setUser method usage. Perhaps this would help you: https://auth.nuxtjs.org/api/auth.html#setuser-user

Related

How can I log in as a user with nuxt.auth?

I currently have the following nuxt.auth configuration.
auth: {
strategies: {
cookie: {
endpoints: {
login: { url: '/api/login', method: 'post' },
},
},
},
},
When login is ok, the response is in json format with the following data
{'user': 'Tlaloc-Es'}
On the login page I have the following code:
this.$auth
.loginWith('cookie', {
data: {
email: this.user_email,
password: this.user_password,
remember: this.remember,
},
})
.then((data) => {
const response = data.data.data;
this.$auth.setUser(response.user);
console.log(response.user);
console.log(this.$auth.loggedIn);
});
The problem is this.$auth.loggedIn always returns false.
I guess that auth doesn't set the user as logged, but I don't know any other steps I need part of:
this.$auth.setUser(response.user);
After a call, logging in browser stores the following cookies:
auth._token.cookie -> true
session -> session token
auth.strategy -> 'cookie'
auth._token_expiration.cookie -> false
How can I set the user as logged?
EDIT
If I execute the logout this value
auth._token.cookie
turn to false, but the session still is stored and anyway
this.$auth.loggedIn
return false.
EDIT
Another try:
auth: {
redirect: {
login: '/login',
logout: '/login',
home: '/',
},
strategies: {
cookie: {
cookie: {
name: 'session',
},
user: {
property: false,
autoFetch: false,
},
endpoints: {
login: { url: '/api/login', method: 'post' },
logout: { url: '/api/logout', method: 'post' },
},
},
},
},
async signIn() {
const succesfulLogin = await this.$auth.loginWith('cookie', {
data: {
email: this.user_email,
password: this.user_password,
remember: this.remember,
},
});
if (succesfulLogin) {
const response = succesfulLogin.data.data;
await this.$auth.setUser({ user: response.user });
console.log(this.$auth.loggedIn);
//await this.$auth.logout();
}
},
This is after login:
reponse cookie
Thanks.
you should try setting set this.$auth.loggedIn = true to true after receiving the data
this.$auth
.loginWith('cookie', {
data: {
email: this.user_email,
password: this.user_password,
remember: this.remember,
},
})
.then((data) => {
const response = data.data.data;
this.$auth.setUser(response.user);
this.$auth.loggedIn = true
console.log(response.user);
console.log(this.$auth.loggedIn);
});
Finally works with the following configuration:
auth: {
redirect: {
login: '/login',
logout: '/login',
home: '/',
},
strategies: {
cookie: {
options: {
httpOnly: true,
path: '/',
},
user: {
property: false,
autoFetch: false,
},
endpoints: {
login: { url: '/api/login', method: 'post' },
logout: { url: '/api/logout', method: 'post' },
},
},
},
},

Nuxt.js auth user is set but loggedIn is still false

js app with Nuxt Auth and when I want to log in. User is not set and loggedIn is false
const response = await this.$auth.loginWith('local', { data: {
email: this.form.email.value,
password: this.form.password.value,
} });
this.$auth.setUser(response.data.user);
this.$auth.strategy.token.set(response.data.jwt.access_token)
this.$auth.strategy.refreshToken.set(response.data.jwt.refresh_token)
so I wrote this and after that user is set but loggedIn is still false. Here my nuxt.config.js.
auth: {
strategies: {
local: {
scheme: 'refresh',
token: {
property: 'access_token',
maxAge: 1800,
required: true,
type: 'Bearer',
},
refreshToken: {
property: 'refresh_token',
data: 'refresh_token',
maxAge: 60 * 60 * 24 * 30,
},
user: {
property: 'user',
autoFetch: true,
},
endpoints: {
login: { url: '/login', method: 'post' },
refresh: { url: '/refresh', method: 'post', propertyName: false },
logout: { url: '/logout', method: 'post' },
user: { url: '/refresh', method: 'post', propertyName: false },
},
},
},
},
Can you help me with it please?
I found solution to my answer. I wrote my own scheme
import { RefreshScheme } from '~auth/runtime'
export default class CustomScheme extends RefreshScheme {
// Override `fetchUser` method of `local` scheme
async fetchUser (endpoint) {
this.options.endpoints.user = {
...this.options.endpoints.user,
data: {
token: this.$auth.strategy.refreshToken.get()
}
}
// Token is required but not available
if (!this.check().valid) {
return
}
// User endpoint is disabled.
if (!this.options.endpoints.user) {
this.$auth.setUser({})
return
}
// Try to fetch user and then set
return this.$auth.requestWith(
this.name,
endpoint,
this.options.endpoints.user
).then((response) => {
const user = response.data.user
// Transform the user object
const customUser = {
...user,
fullName: user.name,
roles: ['user']
}
// Set the custom user
// The `customUser` object will be accessible through `this.$auth.user`
// Like `this.$auth.user.fullName` or `this.$auth.user.roles`
this.$auth.setUser(customUser)
return response
}).catch((error) => {
this.$auth.callOnError(error, { method: 'fetchUser' })
})
}
}
Apparently was the problem by getting user from propertyName. I replace code with my own response const user = response.data.user and now it seems working :)

How to retrieve token property in Nuxt Auth

I am developing my first NuxtJs application with the following technologies.
For Backend APIs Laravel 7.3 (Passport)
Nuxt v2.15.2
Rendering mode: Universal (SSR / SSG)
NuxtAxios v5.13.1
NuxtAuth v5
My login API response is as follows:
{
"status": true,
"code": 200,
"data": [
{
"id": 3,
"nick_name": "johndoe",
"full_name": "John Doe",
"email": "johndoe#mail.com",
"access_token": "eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNWE5MjFmMGMyMDBlZjkxYWQxY2QyNGI3NDEyYmI1OWY4ZGEyZjg2Yzc0Y2M1ZDAwOTRhOWIyZTU4MGY3MmZmODRmNGI5N2QwYjJmYjA5NjMiLCJpYXQiOjE2MTQwMzE1MDMsIm5iZiI6MTYxNDAzMTUwMywiZXhwIjoxNjQ1NTY3NTAzLCJzdWIiOiIzIiwic2NvcGVzIjpbXX0.clQslt3CdTLoVDHzQFwQyrRLjzjTOSeipCyQAl07gzmwXFKr542hR3MUCRr8CTjueWDTNbwd-iKkQztvB7Z-0N1zaptq67UEwj3iPEEtnbV2gMOSlVdAUu0q4OPJKYI9RwJKHnK-q1bTCOUOitfLrnYOq3Lb1T8B-3en5_S7xb9ln-iOtwVc3vW1OnEbEIsn3ELeTro1zQ9IKdlHhQ50CnGU45LipzKeadtVGkm9qm467XOqlVPZdulMJTCkvunETo23hQsTsn_Fxy0IYLUA0v-_C-ARB0N672fAuHF2a8MIYHv066Omm-6WsPrCNtfOkoIgyuMLl0gaua04IJfHrDbh7CJSEUqootKTsIVvFG4OjqR3yDN2PdhjJkPYWNTMeLbKV3ewSsjCS1aMOtXYvhrVFjrunn5M74pDBzn3kW9VMFIh2BbIfUDO_ziDrsn7KAVyOm-p7gdBN_gVKcl_Hx9x4EagixWRL7GGUqEZ2AbxRkpIO4HKwqMm7WxKatSt5hkmPZ6Zt-jfMTfrj7KuF6WhhjCh1TOFJSy9BTqp9_a2eKP-YL2M6JIJXFDHwovToC96JBptbumPvB2i2KDU_XoXF2WFx_I4iNJpZVFN0u12MeyMbXlnpf4X2t79_I7QklxSfZ5LgsOdsnt9dAm9QBbSvf8AdZZNOS4p59DuQls",
}
],
"error": null,
"errors": null
}
nuxt.config.js
auth: {
strategies: {
local: {
token: {
// property: 'access_token'
// property: 'data[0].access_token'
// property: 'data.data[0].access_token'
property: false
},
user: {
property: 'data',
autoFetch: true
},
endpoints: {
login: { url: '/en/signin', method: 'post' },
logout: { url: '/user/logout', method: 'get' },
user: { url: '/en/user/profile', method: 'get' },
}
}
}
},
Login.vue
export default {
data() {
return {
login: {
email: 'johndoe#mail.com',
password: 'welcome'
}
}
},
methods: {
async userLogin() {
try {
let response = await this.$auth.loginWith('local', { data: this.login })
console.log(response)
} catch (err) {
console.log(err)
}
}
}
}
When I am setting local.property: false, auth._token.local is being set as complete json object instead of "access_token" and then the second hit goes to '/en/user/profile' with Unauthenticated Request result.
I think an alternate way would be to set local.token.required:false , and then set the user token after your login attempt was successful. Something like this:
nuxt.config.js
auth: {
strategies: {
local: {
token: {
required: false
},
user: {
property: 'data',
autoFetch: true
},
endpoints: {
login: { url: '/en/signin', method: 'post' },
logout: { url: '/user/logout', method: 'get' },
user: { url: '/en/user/profile', method: 'get' },
}
}
}
},
Login.vue
methods: {
async userLogin() {
try {
let response = await this.$auth.loginWith('local', { data: this.login })
.then((response)=>{
this.$auth.setUserToken(response.data[0].access_token,'refreshToken');
});
console.log(response);
} catch (err) {
console.log(err)
}
}
}

Nuxt JS Login route is still accessible after successful login

I am trying to resolve this issue past few weeks. I followed couple of series. One on youtube, and one on codecourse. Both of them showed the right way to authenticate user, but once the user is logged in. Login route is still accessible. I will try to give as much information i can.
This is my nuxt.config.js
auth: {
plugins: ["~plugins/auth.js"],
strategies: {
local: {
endpoints: {
login: {
url: "auth/login",
method: "post",
propertyName: "meta.token"
},
user: {
url: "auth/me",
method: "get",
propertyName: "data"
},
logout: {
url: "auth/logout",
method: "post"
},
redirect: {
login: "/auth/login",
logout: "/",
home: "/",
callback: "/"
},
watchLoggedIn: true,
rewriteRedirects: true
}
}
}
},
Here is my login.vue
export default {
middleware: ["guest"],
auth: "guest",
name: "login",
data() {
return {
form: {
email: "",
password: ""
}
};
},
methods: {
async login() {
await this.$auth.loginWith("local", {
data: this.form
});
this.$router.push({
path: this.$route.query.redirect || "/dashboard"
});
}
}
};
It's still accessible after login.
Your configured it wrong. Its all described in the docs. For example middleware
There is no such thing as
middleware: ["guest"],
as in your code. Middleware called auth as you can see in docs. So you need to set it either
Setting per route:
export default {
middleware: 'auth'
}
Globally setting in nuxt.config.js:
router: {
middleware: ['auth']
}

Nuxt Auth - User Data not set

I try to do a login via nuxt-auth module. As a response I get the token and then the user data is delivered. However, this.$Auth.loggedIn is false and this.$Auth.user is undefined. I have been fighting for 3 days and can not get any further. Hope somebody can help me.
login
await this.$auth.login({
data: {
email: this.email,
password: this.password
}
}).then(() => {
this.$router.push('/dashboard')
}).catch(err => {
this.snackbar.show = true;
})
nuxt.config.js
auth: {
strategies: {
local: {
endpoints: {
login: {
url: '/auth/login',
method: 'post',
propertyName: 'access_token'
},
logout: {
url: '/auth/logout',
method: 'post'
},
user: {
url: '/auth/me',
method: 'post'
},
tokenRequired: true
}
}
}
}
response login
{
"access_token": "xxxxxxxxxxxxx.eyJpc3MiOiJodHRwczpcL1wvYXBpLmFwcHJlexxxxxxxcxXRoXC9sb2dpbiIsImlhdCI6MTUzODI5NTczMywiZXhwIjoxNTM4Mjk5MzMzLCJuYmYiOjE1MzgyOTU3MzMsImp0aSI6ImdtWWVyZTViQjk1cU5BRG8iLCJzdWIiOjIsInBydiI6IjYwODM2NzQ0MzQ4ZDQzMTk4NzE4N2ZjMWM2YzIzMjYxMDcyMWE5ZjAifQ.JhOiwIg7StzZR71aqYyI9rJpPXVclmddzPSIwqCIUN4",
"token_type": "bearer",
"expires_in": 3600
}
response user
{
"id": 2,
"name": "Dominik Dummy",
"email": "dummy#andreas-pabst.de",
"created_at": {
"date": "2018-09-28 09:11:31.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"updated_at": {
"date": "2018-09-28 09:11:31.000000",
"timezone_type": 3,
"timezone": "UTC"
},
"self": "https:\/\/api.apprex.de\/api\/users\/2"
}
Ok after a long try, I finally solved it. The problem was that auth.fetchUser() requires a property user in the user response, which is not present in my user response. I set the propertyName to false in the nuxt.config.js and now it works
*nuxt.config.js
auth: {
strategies: {
local: {
endpoints: {
login: {
url: '/auth/login',
method: 'post',
propertyName: 'access_token'
},
logout: {
url: '/auth/logout',
method: 'post'
},
user: {
url: '/auth/me',
method: 'post',
propertyName: false // <--- Default "user"
}
}
}
}
}
Currently I am not sure if this is a fault in the module
Update for auth-next": "^5.0.0"
You will have to set property: false instead of propertyName.
So your nuxt.config.js might be as follows:
auth: {
strategies: {
local: {
token: {
property: 'access_token',
required: true,
type: 'Bearer'
},
user: {
property: false, // <--- Default "user"
autoFetch: true
},
endpoints: {
login: { url: 'api/login', method: 'post' },
logout: { url: 'api/auth/logout', method: 'post' },
user: { url: 'api/user', method: 'get' }
}
}
}
},
You should call the this.$auth.fetchUser() for fills user data and loggedIn in the auth store Docs