I have an API api/auth that is used to log users in. It expects to receive an access_token (as URL query, from Headers, or from request body), a username, and a password. I've been using the Vue Chrome Developer Tool and even though I get a 201 response from the server, the auth.loggedIn state is still false. I think that might be the reason why my redirect paths on the nuxt.config.js isn't working as well. Can anyone point me to the right direction on why it doesn't work?
This is a screenshot of the Vue Chrome Developer Tool
This is the JSON response of the server after logging in. The token here is different from the access_token as noted above.
{
"token": "XXXXXXXXXXXXXXXXXXXXXXXXXXXXX",
"user": {
"user_name": "xxxxxxxxxxxxxxxxxx",
"uid": "xxxxxxxxxxxxxxxxxx",
"user_data": "XXXXXXXXXXXXXXXXXXXXXXXXX"
}
}
Here is the relevant part of nuxt.config.js
export default {
modules: [
'#nuxtjs/axios',
'#nuxtjs/auth',
['bootstrap-vue/nuxt', { css: false }]
],
router: {
middleware: [ 'auth' ]
},
auth: {
strategies: {
local: {
endpoints: {
login: {
url: '/api/auth?access_token=XXXXXXXXXXXXXXXXXXXXXX',
method: 'post',
propertyName: 'token'
},
logout: {
url: '/api/auth/logout',
method: 'post'
},
user: {
url: '/api/users/me',
method: 'get',
propertyName: 'user'
}
}
}
},
redirect: {
login: '/',
logout: '/',
home: '/home'
},
token: {
name: 'token'
},
cookie: {
name: 'token'
},
rewriteRedirects: true
},
axios: {
baseURL: 'http://localhost:9000/'
}
}
And my store/index.js
export const state = () => ({
authUser: null
})
export const mutations = {
SET_USER: function (state, user) {
state.authUser = user
}
}
export const actions = {
nuxtServerInit ({ commit }, { req }) {
if (req.session && req.user) {
commit('SET_USER', req.user)
}
},
async login ({ commit }, { username, password }) {
const auth = {
username: username,
password: password
}
try {
const { user } = this.$auth.loginWith('local', { auth })
commit('SET_USER', user)
} catch (err) {
console.error(err)
}
}
}
The login action in the store is triggered by this method in the page:
export default {
auth: false,
methods: {
async login () {
try {
await this.$store.dispatch('login', {
username: this.form.email,
password: this.form.password
})
} catch (err) {
this.alert.status = true
this.alert.type = 'danger'
this.alert.response = err
}
}
}
}
P.S. I realize I'm explicitly including the access_token in the URL. Currently, I don't know where a master_key or the like can be set in the Nuxt Auth Module.
Try this in your store/index.js
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
const store = () => new Vuex.Store({
state: {
authUser: null
},
mutations: {
SET_USER: function (state, user) {
state.authUser = user
}
},
actions: {
CHECK_AUTH: function(token, router) {
if (token === null) {
router.push('/login')
}
}
}
})
export default store
And for the router, this should work globally:
$nuxt._router.push('/')
Related
I have a problem with the authenticate with my Nuxt application (static SSR).
I'm using Sanctum. But the $auth variable is emptied after a refresh. So the user is disconnected.
login.vue
await axios.get(`${process.env.apiUrl}/sanctum/csrf-cookie`)
const res = await this.$auth.loginWith('laravelSanctum', {
data: {
email: this.userLogin.login.email,
password: this.userLogin.login.password,
}
})
.catch((error) => {
this.userLogin.messageError = 'Wrong credentials'
[ ... stop process code ...]
})
await this.$auth.$storage.setUniversal('_auth.user', JSON.stringify(res.data.user))
await this.$auth.setUser(res.data.user)
store/index.js
export const actions = {
async nuxtServerInit({ commit, dispatch }) {
const user = this.$auth.$storage.getUniversal('_auth.user')
if (user) {
await this.$auth.setUser(user)
}
}
}
nuxt.config.js
auth: {
strategies: {
laravelSanctum: {
provider: 'laravel/sanctum',
url: process.env.apiUrl,
endpoints: {
csrf: { url: '/sanctum/csrf-cookie', methods: 'GET' },
login: { url: '/api/login', method: 'POST' },
logout: { url: '/api/logout', method: 'POST' },
user: false
},
user: {
property: false,
autoFetch: false
},
cookie: false
}
},
redirect: {
login: '/mon-compte/login',
logout: '/mon-compte/login',
//home: '/mon-compte/mon-espace',
register: '/mon-compte/register'
}
}
I am trying to create login page. SO for this, I am making a call. After I get the response, I am storing cookie and with the cookie I am getting the user info. What I am trying to do is store this user info in Vuex store. Here is whole of my logic for this:
export default {
name: 'Login',
mounted() {
EventBus.$on(GENERAL_APP_CONSTANTS.Events.CheckAuthentication, () => {
this.authenticated = authHelper.validAuthentication();
if (this.authenticated) {
this.email = this.password = "";
this.authenticationFailed = false;
}
});
EventBus.$on(GENERAL_APP_CONSTANTS.Events.LoginFailed, () => {
this.authenticationFailed = true
});
},
data () {
return {
authenticated: false,
authenticationFailed: false,
email: '',
password: '',
rememberMe: false,
cookieName: "_token",
cookie: "",
cookieValue: "",
}
},
validations: {
email: {
required,
email,
},
password: {
required,
minLength: minLength(0)
},
},
methods: {
signIn: function () {
authHelper.signIn(this.email, this.password, () => {
this.$router.push({name: 'home'});
});
this.cookie = cookieHelper.getCookie(this.cookieName);
this.cookieValue = cookieHelper.getCookieValue(this.cookie);
this.storeUser();
},
storeUser: function () {
apiHelper.getRequest(
`/users/${cookieHelper.parseJwt(this.cookie).user_id}`,
(response) => {
this.$store.dispatch('storeUser', {
user: response.data,
})
}
)
},
}
}
So, as you see below, my user in Vuex store is still empty:
my mutation is:
export const STORE_USER = (state, {user}) => {
state.user = user;
}
my action is:
export const storeUser = ({commit}, {user}) => {
commit('STORE_USER', {user});
}
Could you have a look and let me know, where do you think I am making something wrong.
I'm using nuxt.js, after I send a login request with email and password to the backend I get a response which contains a message, token and user informations, how can I access user informations in the response and save it inside some state in store.js after a successful login?
I wanted to save user object in user state down in store/index.js using an action saveUserAction which might be dispatched after a successful login, i dont know if thats right or not, any advise would be very helpful
Response
{
"message":"success",
"token":"eyJ0eXAiOiJKV1QiLCJhbGciOiJSUzI1NiJ9.eyJhdWQiOiIxIiwianRpIjoiNzFkYjA1MWM2MTYxMmE4YzAyNWI2YjU3N2xMzJiNzJjMjI0MzRlY2IzNzYwNTg2N2NjOWQ5ZWEwY2MiMJM3uYEiZ8GSlPlQhIctVErO2KzwXOBxifWWoM7et_qT-mgvfsk3ljwiQF9iPQw-WeekBx8J8lcmxDLESa3tfE1Re1Xk2flkcBLmiI4JN2YHh08U1U",
"user":{
"id":1,
"role_id":4587,
"firstname":"Hans",
"lastname":"newman",
"email":"newman#gmail.com",
"email_verified_at":null,
"phone":"89498",
"skype":"gdgdfg",
"birthdate":"2021-05-02",
"address":"asdfaf",
"postalcode":14984,
"city":"jisf",
"country":"isfisf",
"status":"mfof",
"created_at":"2021-06-16T09:33:08.000000Z",
"updated_at":"2021-06-16T09:39:41.000000Z",
"image":"1623835988-carlsen.png",
"description":"sfdgg",
"geo_lat":5.5,
"geo_lng":8.1
}
}
login.vue
<script>
import { mapActions } from 'vuex'
export default {
data() {
return {
auth: false,
email: '',
password: '',
}
},
methods: {
async login() {
const succesfulLogin = await this.$auth.loginWith('local', {
data: {
email: this.email,
password: this.password,
},
})
if (succesfulLogin) {
await this.$auth.setUser({
email: this.email,
password: this.password,
})
this.$router.push('/profile')
}
},
},
}
</script>
store/index.js
export const state = () => ({
user:{}
})
export const mutations = {
saveUser(state, payload) {
state.user=payload;
}
}
export const actions = {
saveUserAction({commit}, UserObject){
commit('saveUser');
}
}
Go to your vue devtools, vuex tab and look for auth, it should already be available. This answer may help you during your debugging: https://stackoverflow.com/a/68081536/8816585
Since you do have your user object in the response, this kind of configuration should do it, as shown in the documentation. No need to make some other vuex actions.
auth: {
strategies: {
local: {
token: {
property: 'token',
global: true,
},
user: {
property: 'user', // the name of your object in your backend response payload
},
endpoints: {
[...]
}
}
}
}
I added middlewares to default.vue component:
export default {
components: {
TheHeader
},
middleware: ['auth'],
}
My auth.js:
export default function ({ app, store }) {
if (app.$cookies.get('AUTH_TOKEN')) {
var AUTH_TOKEN = app.$cookies.get('AUTH_TOKEN')
app.$axios.$post('https://example.com/api', {
email: Buffer.from(AUTH_TOKEN[0], 'base64').toString(),
password: Buffer.from(AUTH_TOKEN[1], 'base64').toString(),
}).then(response => {
store.dispatch('changeAuthStatus', {
authStatus: true,
userData: {
id: response.data.id,
login: response.data.login,
email: response.data.email,
firstName: response.data.first_name,
lastName: response.data.last_name,
}
})
})
}
}
So I can't understand why my middlewares don't load when the page is reloaded or with direct access to the page. Also mode: 'universal' and ssr: true are set in nuxt.config.js
Here is the documentation for the middlewares: https://nuxtjs.org/docs/2.x/directory-structure/middleware/
Few steps to have a working middleware:
use it only in a page (/pages/hello.vue) or layout (/layouts/MyFancyLayout.vue)
put the middleware in the proper directory (/middleware/test.js)
call it properly in the .vue file like middleware: 'test'
You can also try to debug and see if something like this works
export default {
middleware() {
console.log('working!')
}
}
It is working on client transitions and should be good on initial page load aswell.
As a more accurate way, you should do this in the Vuex Store using the 'context' attribute.
middleware/auth.js
export default function(context) {
if (process.client) {
context.store.dispatch('initAuth', null);
}
context.store.dispatch('initAuth', context.req);
}
store/index.js
import Cookie from 'js-cookie'
store/index.js
actions:{
initAuth(vuexContext,state){
let token;
let jwtCookie;
if (req) {
if (!req.headers.cookie) {
return;
}
jwtCookie = req.headers.cookie
.split(";")
.find(c => c.trim().startsWith("jwt="));
if (!jwtCookie) {
return;
}
token = jwtCookie.split('=')[1];
} else {
token = localStorage.getItem('token');
}
vuexContext.commit('setToken', token);
return $axios.post('https://example.com/api', {
email: Buffer.from(AUTH_TOKEN[0], 'base64').toString(),
password: Buffer.from(AUTH_TOKEN[1], 'base64').toString(),
}).then(response => {
vuexContext.commit('changeAuthStatus', {
authStatus: true,
userData: {
id: response.data.id,
login: response.data.login,
email: response.data.email,
firstName: response.data.first_name,
lastName: response.data.last_name,
}
})
})
}
}
this way it will work smoothly and understandably
I'm new to vue (started using vue 2) I'm using Store (vuex) and I'm trying to acheive something.
basically I managed to install the vue-auth plugin : I have this.$auth that I can call from within .vue files.
Now using the store I wanna call the userLogin function by dispatching the call like this from a vue file :
<script>
export default {
computed: {
comparePasswords() {
return this.password === this.passwordConfirm
? true
: "Passwords don't match";
}
},
methods: {
userSignUp() {
if (this.comparePasswords !== true) {
return;
}
this.$store.dispatch("userSignUp", {
email: this.email,
password: this.password
});
}
},
data() {
return {
email: "",
password: "",
passwordConfirm: ""
};
}
};
</script>
in the store/index I'm trying to access the 'this.$auth' I do understand is some kind of context switching but I don't know how to access the vue app instance. :
import Vue from 'vue'
import Vuex from 'vuex'
Vue.use(Vuex)
let app = this
export const store = new Vuex.Store({
state: {
appTitle: 'LiveScale Dashboard',
user: null,
error: null,
loading: false
},
mutations: {
setUser(state, payload) {
state.user = payload
},
setError(state, payload) {
state.error = payload
},
setLoading(state, payload) {
state.loading = payload
}
},
actions: {
userLogin({ commit }, payload) {
commit('setLoading', true)
var redirect = this.$auth.redirect(); // THIS IS WRONG.
this.$auth.login({ // THIS IS WRONG.
body: payload, // Vue-resource
data: payload, // Axios
rememberMe: this.data.rememberMe,
redirect: { name: redirect ? redirect.from.name : 'account' },
fetchUser: this.data.fetchUser
})
.then(() => {
commit('setUser', this.context)
commit('setLoading', false)
router.push('/home')
}, (res) => {
console.log('error ' + this.context);
commit('setError', res.data)
commit('setLoading', false)
});
},
userSignUp({ commit }, payload) {
// ...
}
},
getters: {}
})
Thanks for your help
try using Vue.$auth in index.js it should work
The idea (so far) is to pass the instance as an argument to the function as follows :
this.$store.dispatch("userSignUp", {
email: this.email,
password: this.password,
auth: this.$auth //added this line
});
and then in the store -> actions , payload.auth will contain my auth plugin :
userLogin({ commit }, payload) {
commit('setLoading', true)
var redirect = payload.auth.redirect();
payload.auth.login({
body: payload, // Vue-resource
data: payload, // Axios
rememberMe: this.data.rememberMe,
redirect: { name: redirect ? redirect.from.name : 'account' },
fetchUser: this.data.fetchUser
})
.then(() => {
commit('setUser', this.context)
commit('setLoading', false)
router.push('/home')
}, (res) => {
console.log('error ' + this.context);
commit('setError', res.data)
commit('setLoading', false)
});
},
I don't know if it's the best practice or not, but this is how I managed to do it. Please feel free to suggest anything.