auth-module
auth-module copied to clipboard
setUser does not change the loggedIn state variable and requires a page reload to work.
Version
module: ^5.0.0-1624817847.21691f1 nuxt: 2.15.8
Nuxt configuration
mode:
- [x] universal
- [ ] spa
Nuxt configuration
auth: {
plugins: ['~/plugins/auth'],
rewriteRedirects: true,
fullPathRedirect: true,
strategies: {
cookie: {
cookie: {
name: "sessionid"
},
endpoints: {
login: {
url: `auth/login/`,
method: 'post',
//propertyName: false,
//withCredentials: true
},
logout: {
url: 'auth/logout/',
method: 'post'
},
user: {
url: `user`,
method: 'get',
},
},
tokenRequired: false,
tokenType: false,
user: {
autoFetch: true,
property: false,
withCredentials: true,
}
},
google: {
clientId: credentials.GoogleAuthCredentials.client_id,
redirectUri: isProd ? baseUrl : baseDevUrl,
logoutRedirectUri: isProd ? baseUrl : baseDevUrl,
codeChallengeMethod: "",
responseType: "code",
token: {
property: 'access_token',
type: 'Bearer',
},
refreshToken: {
property: 'refresh_token',
},
endpoints: {
token: `${baseApiUrl}auth/google/`,
refresh: {
url: `${baseApiUrl}auth/google/`,
method: 'post'
},
userInfo: `${baseApiUrl}user`,
},
autoLogout: false
}
},
redirect: {
login: '/',
logout: '/',
callback: '/',
home: '/'
}
}
Reproduction
:warning: without a minimal reproduction we won't be able to look into your issue
I'm signing in my users with cookies and google strategies, when I login a user with cookies strategy, it is necessary that i do a manual reload to make the plugin auth the user, if I don't do it, the app does not recognize the logged user and it continues as in logout, the problem is that i cannot reload the page, because the user is in the middle of a transaction that was started being signed out, so refreshing will cause the users to lost a lot of time and miss the data provided, I was to trying to use setUser in the followind way:
this.$auth.loginWith("cookie", {
data: {
username: this.userData.email,
password: this.userData.password,
},
}).then((authRes) => {
this.$axios.get("user").then((res) => {
if (res.status === 200) {
this.$auth.setUser(res.data); // this response is a JSON with all the user information
}
})
})
The request is done successfully, so it means that the cookies had been set successfuly, the problem is that when I set the user, it should force the $auth.loggedIn variable to be true and this is never happening.
By the other side, when I login with google, it is necessary for me to do a manual redirect too, and the problem is that I cannot figure out how to prompt a user login without being redirected to the google account selection page, it causes that the users lose all the data provided.
What is expected?
After the user call is done to the API to check the user validity, nuxt auth should refresh the storage variables and allow the users to use the data in realtime, using the reactivity of Vue.
What is actually happening?
After the login it is necessary to refresh the page to have the authentication working well, but it causes a lot of time spend and data lost in user transactions started in logout.
Steps to reproduce
Additional information
Just create a project with the package versions provided by me and try to sign in in a similar way than the strategies specified (cookies and google).
Checklist
- [x] I have tested with the latest Nuxt version and the issue still occurs
- [x] I have tested with the latest module version and the issue still occurs
- [x] I have searched the issue tracker and this issue hasn't been reported yet
i am seeing the same problem
Any updates on this?
i am seeing the same problem
Is this the same as https://github.com/nuxt-community/auth-module/issues/1061?
We're seeing the same behavior here, any updates?
Edit: Something that worked on our end was to commit the mutations manually via:
this.$store.commit('auth/SET', { key: 'user', value: user })
this.$store.commit('auth/SET', { key: 'loggedIn', value: true })
Not sure if there are unforeseen side-effects with this approach.
this.$store.commit('auth/SET', { key: 'user', value: user }) this.$store.commit('auth/SET', { key: 'loggedIn', value: true })
methods: {
async userLogin() {
try {
const form = new FormData();
form.append('username', this.login.username);
form.append('password', this.login.password);
let response = await this.$auth.loginWith('local', { data: form });
this.$store.commit('auth/SET', { key: 'user', value: this.$auth.user });
this.$store.commit('auth/SET', { key: 'loggedIn', value: true });
} catch (err) {
console.log(err);
}
},
},
tried your method but still didn't work🙄
Hi all,
Is there any update on this issue? We are experiencing the same problem here. Setting the loggedIn property manually also doesn't help.
No, but investigation and an answer into my question above would be helpful, and PRs fixing the issue are welcomed. Just add me as a reviewer when it's done.
Hy, Is there any update on this issue?
@zavvla Please read my last message. Pings like this are spam and not appreciated.
sad news, but we have the same problem =(
for those who have the same problem please note you can only use setUser after you have configured your user autoFetch to false just like how the docs metioned:
TIP: This function can be used to set the user using the login response after a successfully login, when user.autoFetch is disabled.
and the only way for this module to automatically set loggedIn to true when using setUser is you need to use this module loginWith function. as for why you need to do that, do your own research on this module.
for those who have similar problem, it is probably because you have to many unneeded or unavailable config, for cookie strategy this config should be sufficient
auth: {
strategies: {
cookie: {
cookie: {
name: "YOUR COOKIE NAME"
},
endpoints: {
login: {
url: `https://your-backend-api.url/path/to/login`,
method: 'post'
},
logout: {
url: `https://your-backend-api.url/path/to/logout`,
method: 'post'
},
user: {
url: `https://your-backend-api.url/path/to/user`,
method: 'get',
},
},
user: {
property: false, // set this to false if your user endpoint return user data directly
autoFetch: false // set this to false if you are using setUser function
}
}
}
}
how to handle your login if you are using setUser manually
--- file/where/you/handle/login-form.vue
<script>
...
method: {
...
async login() {
await this.$auth.loginWith('cookie', {
data: {
username: 'your user username input value',
password: 'your user password input value',
})
.then(async (res) => {
const data = res.data // use this if your login response contain user information
// or
const data = await this.$axios.$get('/alt-backend/api/user') // use this if your user login on different api route
this.$auth.setUser(data)
})
}
...
}
...
</script>
if you have tried above but still have the same problem please shares your auth config, auth plugins file, your api response, and how you use this module
Update
i also want to mention that this module only retrieving user data on login. at least that is what my project experienced.
in other to keep my user have updated logged in user data, you need to call this.$auth.fetch() to refetch the data from user endpoint, this function however can only be used only while the loggedIn state is true.
while it is sufficient to retrieved updated data after all you can only have 1 login data at a time. sometimes it is a problem for example: you have 2 login form, 1 in your backend where your admin panel probably is, and the other in your frontend. if you try to logged in from your backend after clearing your cookie, your frontend would not be able to retrieve currently logged in data from your backend api, because this this.$auth.fetch() function would not trigger.
So my solution is to call user api endpoint using axios directly probably from my layout every time my pages is re-rendered and set manually user loggedIn state by using this.$auth.$storage.setUniversal(key, val) function. however this is not persisted. because this module use localStorage or cookie to persisted the loggedIn state. and the only way to persisted the loggedIn state you need to use this.$auth.setUserToken function
for those who have the same problem please note you can only use
setUserafter you have configured your userautoFetchto false just like how the docs metioned:TIP: This function can be used to set the user using the login response after a successfully login, when user.autoFetch is disabled.
and the only way for this module to automatically set
loggedInto true when usingsetUseris you need to use this moduleloginWithfunction. as for why you need to do that, do your own research on this module.for those who have similar problem, it is probably because you have to many unneeded or unavailable config, for cookie strategy this config should be sufficient
auth: { strategies: { cookie: { cookie: { name: "YOUR COOKIE NAME" }, endpoints: { login: { url: `https://your-backend-api.url/path/to/login`, method: 'post' }, logout: { url: `https://your-backend-api.url/path/to/logout`, method: 'post' }, user: { url: `https://your-backend-api.url/path/to/user`, method: 'get', }, }, user: { property: false, // set this to false if your user endpoint return user data directly autoFetch: false // set this to false if you are using setUser function } } } }how to handle your login if you are using
setUsermanually--- file/where/you/handle/login-form.vue <script> ... method: { ... async login() { await this.$auth.loginWith('cookie', { data: { username: 'your user username input value', password: 'your user password input value', }) .then(async (res) => { const data = res.data // use this if your login response contain user information // or const data = await this.$axios.$get('/alt-backend/api/user') // use this if your user login on different api route this.$auth.setUser(data) }) } ... } ... </script>if you have tried above but still have the same problem please shares your auth config, auth plugins file, your api response, and how you use this module
Update
i also want to mention that this module only retrieving user data on login. at least that is what my project experienced.
in other to keep my user have updated logged in user data, you need to call
this.$auth.fetch()to refetch the data from user endpoint, this function however can only be used only while theloggedInstate is true.while it is sufficient to retrieved updated data after all you can only have 1 login data at a time. sometimes it is a problem for example: you have 2 login form, 1 in your backend where your admin panel probably is, and the other in your frontend. if you try to logged in from your backend after clearing your cookie, your frontend would not be able to retrieve currently logged in data from your backend api, because this
this.$auth.fetch()function would not trigger.So my solution is to call user api endpoint using axios directly probably from my layout every time my pages is re-rendered and set manually user
loggedInstate by usingthis.$auth.$storage.setUniversal(key, val)function. however this is not persisted. because this module use localStorage or cookie to persisted theloggedInstate. and the only way to persisted the loggedIn state you need to usethis.$auth.setUserTokenfunction
Thank you very much for the explanation, I will try. My problem is that because of the old code, I need to authorize by cookies, but at the same time keep the possibility of classic authorization by JWT
In my development environment I have a button to log in directly via my API.
There I set my user as follows and I am also automatically redirected:
// just my api call
const userSession = await this.$api.auth.devLogin();
this.$auth.setUser(userSession);
await this.$auth.setUserToken(true);