I have a problem with my Vue application with the router on the authentication but only on the first page load...
All my routes are under a middleware to check if they are logged, so my router looke like this :
import Vue from 'vue'
import Router from 'vue-router'
import store from './store'
Vue.use(Router);
let router = new Router({
mode: 'history',
routes: [
{
path: '/',
name: 'root',
component: resolve => require(['./views/Root.vue'], resolve),
meta: {
pageTitle: `Index`,
}
},
{
path: '/authentication/',
name: 'authentication',
component: resolve => require(['./views/Login.vue'], resolve),
meta: {
pageTitle: `Connexion`,
authNotRequired: true,
}
},
],
});
router.beforeEach((to, from, next) => {
//Si l'Utilisateur est authentifié :
if (!store.getters.isLoggedIn && !to.matched.some(r => r.meta.authNotRequired)) {
next({ name: 'authentication' });
}
else {
next();
}
});
export default router;
My session store is quite simple :
import Vue from 'vue'
import Vuex from 'vuex'
import VuexPersist from 'vuex-persist'
Vue.use(Vuex);
const vuexLocalStorage = new VuexPersist({
key: 'my.personal.key',
storage: window.localStorage,
})
export default new Vuex.Store({
plugins: [vuexLocalStorage.plugin],
state: {
session: {
sessionId: null,
},
},
getters: {
isLoggedIn: (state) => {
return (state.session.sessionId !== null);
},
},
mutations: {
save(state, session) {
state.session = session;
},
destroy(state) {
state.session = {};
},
},
actions: {
save(context, payload) {
return new Promise((resolve, reject) => {
context.commit('save', payload);
resolve();
});
},
destroy(context) {
return new Promise((resolve, reject) => {
context.commit('destroy');
resolve();
});
}
}
});
And so my Login function is quite simple too :
/* THE FORM WAS SUCCESSFULLY SENT TO THE API WHICH ANSWERED {obj.id: 456} */
onLogIn(obj) {
this.$store.dispatch('save', { sessionId: obj.id }).then(() => {
this.$router.push({ name: 'root' });
});
},
So, this code works fine when the application is already launched, if I disconnect and reconnect, the redirection works fine... Litterally everything is working great ...
BUT when the user first load the page and logIn, the router is not pushing the new route so the User stay on the authentication page, but the session is changed (if I put a console.log I have the sessionId in the store)
I don't really understan why the redirection not working on the first load, I found that when I do a localStorage.clear() then reload the page and try to connect it's also not working.
Do you have any idea why it's doing this?
Related
For now I have this piece of code
import addToast from '#/utils/toast-queue';
import routes from './routes';
import App from './app';
import './assets/styles/global.scss';
import { jsonRequest } from './utils/requests';
Vue.use(VueRouter);
const router = new VueRouter({ routes });
router.beforeEach(async (to, from, next) => {
const userInfo = await jsonRequest('GET', '/user/info');
const notAuthenticated = userInfo.status !== 200;
if (to.name !== 'login' && notAuthenticated) {
if (to.name === 'survey') {
next({ name: 'survey' });
} else {
addToast('Please login', { type: 'error' });
next({ name: 'login' });
}
} else {
next();
}
});
/* eslint-disable-next-line no-new */
new Vue({
el: '#app',
router,
render: h => h(App)
});
When a GET request comes from /user/info to the path /public/form I would like an user not authenticated to be redirected to the page displaying the form. How can I achieve this in vue.js?
I have declared the route in route.js file like this
{
path: '/public/form',
name: 'form',
component: () => import('./views/form'),
}
I updated the beforeEach() like this
router.beforeEach(async (to, from, next) => {
const userInfo = await jsonRequest('GET', '/user/info');
const notAuthenticated = userInfo.status !== 200;
if (to.name !== 'login' && notAuthenticated) {
if (to.name === 'form') {
next({ name: 'form' });
} else {
addToast('Please login', { type: 'error' });
next({ name: 'login' });
}
} else {
next();
}
});
but it seems not working
According to the documentation, you should use
return { name: 'Login' };
or
return '/login';
instead of
next({ name: 'login' });
The same for form.
I have a route. If the user is not logged in it redirects them to the login page. I am trying to grab the route the user came from so I can redirect them back after they have logged in.
Here is my route:
{
path: '/builder/:pin?',
name: 'Builder',
component: Builder,
props: true,
meta: {
requiresAuth: true, roles: ['XXXX', 'XXXX', 'XXXX']
}
}
router.beforeEach((to, from, next) => {
// check to see if router requires auth
if (to.meta.requiresAuth) {
let user = store.getters.getUser
firebase.auth().onAuthStateChanged((user) => {
if (user) {
if(!user.emailVerified) {
next({ name: 'Login' })
store.dispatch('setLoginFeedback', {code: 'resubmit-verification', message: 'Your email is not verified'})
return
}
// get current user
let ref = db.collection('users').where('email', '==', user.email)
ref.get().then(snapshot => {
if (!snapshot.empty) {
snapshot.forEach(doc => {
this.user = doc.data()
// if no roles are set
if(!to.meta.roles) {
next()
} else if(to.meta.roles) {
const hasRole = this.user.roles.find(val => to.meta.roles.includes(val))
if (hasRole) {
next()
} else {
alert('you do not have permission to enter')
}
} else {
// next({ name: 'Dashboard' })
}
})
} else {
// no user
// if (!this.user) {
next({ name: 'Login' })
// }
}
})
} else {
next({ name: 'Login' })
}
})
} else {
// console.log('does not require auth')
next()
}
})
In my Login component I have this code:
beforeRouteEnter(to, from, next) {
next((vm) => {
vm.prevRoute = from;
});
console.log(to, from, next)
},
I am currently on a local server. When I go to localhost:8080/builder it redirects me to the Login properly but in the console. I get this for the From
{name: null, meta: {}, path: "/", hash: "", query: {}, …}
Why am I not getting /builder in the path?
You could just do this..
this.$router.back();
This will take you back to the previous route
Programmatic Navigation | Vue Router https://router.vuejs.org/guide/essentials/navigation.html
It seems that the next({ name: 'Login' }) call you use to redirect to the login page doesn't modify the from attributes. That is because you are "internally" routing, it is different from making a router.push call.
Probably the easiest way to do this kind of redirect is by using a query param:
next({
name: "bar",
query: { redirect: to.fullPath }
});
Then access it either in your component $route.query.redirect or in a router navigation guard from.query.redirect.
To go back the previous route you can use
this.$router.go(-1)
vue maintains history of previous visited routes.
-1 mean go back one record.
see https://router.vuejs.org/guide/essentials/navigation.html#router-go-n
VueJs has its own router so we cannot implement middleware. Instead we go for navigation guard for restricting user from certain pages. My project has two users one is client and the other one is worker. I don't want worker to access the client's page and client to worker's page. The problem i am facing right now is how can i write code there. Reading the documentation doesn't help me.
here is my code from routes.js
const routes =[
{
path:'/login',
name: 'login',
component: Login
},
{
path:'/signup',
name:'signup',
component: Signup
},
{
path:'/user/dashboard',
name:'userdashboard',
component: Dashboard,
meta:{
requiredAuth: true,
client: true,
worker: false
}
},
{
path:'/verifyemail',
name:'verifyemail',
component: Verifyemail
},
{
path: '/logout',
name: 'logout',
component: Logout
},
{
path: '/worker/Dashboard',
name:'workerDashboard',
component: WorkerDashboard,
meta:{
requiredAuth: true,
client: false,
worker: true
}
}
];
const router = new Router({
routes,
mode: 'history'
});
router.beforeEach((to,from,next)=>
{
if(to.matched.some(record => record.meta.requiredAuth) && !Store.state.isLoggedIn )
{
next({name: 'login'});
return
}
if(to.path === '/login' && Store.state.isLoggedIn)
{
next({name:'userdashboard'});
return
}
if(to.path === '/signup' && Store.state.isLoggedIn)
{
next({name:'userdashboard'});
return
}
next()
});
In my login component
axios.post('http://127.0.0.1:8000/api/signin', { email: this.email, password: this.password}, { headers: { 'X-Requested-with': 'XMLHttpRequest' } })
.then((response) => {
const token = response.data.token;
localStorage.setItem('token', token);
this.loadinglogin = false;
store.commit('loginUser');
const UserType = response.data.userType;
if(UserType === '1'){
app.$router.push({name: 'userdashboard'});
}else if(UserType === '2'){
app.$router.push({name: 'workerDashboard'})
}else{
return 'not ok';
}
})
.catch((error) => {
console.log(error.response.data.error);
this.errored = true;
this.error= error.response.data.error;
this.loadinglogin = false
})
Not sure what the question is but you would get the group from your API and put it in your store. Then add some getters, inspect the value in beforeEach() and redirect accordingly. For example:
const router = new VueRouter({
routes: [
{
path: '/foo',
component: Foo,
beforeEnter: (to, from, next) => {
if (!store.getters.isAdmin) {
next(false)
}
}
}
]
})
As #Tarasovych mentioned, this does not replace server side authentication/authorization. It simply adds to user friendliness. You would still need to authenticate/authorize every request before returning any data.
Im trying to create a plugin for manage the Oauth2 token data in my vuejs app.
I created the plugin following some few tutorials that are available on the internet.
var plugin = {}
plugin.install = function (Vue, options) {
var authStorage = {
getToken () {
let token = localStorage.getItem('access_token')
let expiration = localStorage.getItem('expiration')
if (!token || !expiration) {
return null
}
if (Date.now() > parseInt(expiration)) {
this.destroyToken()
return null
}
return token
},
setToken (accessToken, expiration, refreshToken) {
localStorage.setItem('access_token', accessToken)
localStorage.setItem('expiration', expiration + Date.now())
localStorage.setItem('refresh_token', refreshToken)
},
destroyToken () {
localStorage.removeItem('access_token')
localStorage.removeItem('expiration')
localStorage.removeItem('refresh_token')
},
isAuthenticated () {
if (this.getToken()) {
return true
} else {
return false
}
}
}
Vue.prototype.$authStorage = authStorage
}
export default plugin
but when a try to access the methods on the main.js file, i get error saying that the object is undefined.
import Vue from 'vue'
import App from './App'
import router from './router'
import AuthStorage from './AuthStorage.js'
Vue.config.productionTip = false
Vue.use(AuthStorage)
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuth)) {
if (!Vue.$authStorage.getToken()) {
next({
path: '/',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next()
}
})
axios.defaults.headers.common = {
'Authorization': `Bearer ${Vue.$authStorage.getToken()}`
}
/* eslint-disable no-new */
new Vue({
el: '#app',
router,
template: '<App/>',
components: { App }
})
Inside the components the plugin works as expected. The problem is when o try to use in the main.js file.
I already tried with:
this.$authStorage
this.authStorage
Vue.authStorage
no success
You are adding $authStorage to the prototype of Vue.
Vue.prototype.$authStorage = authStorage
That means will only be available on instances of the Vue object (ie. the result of new Vue(...).
If you want $authStorage to be available as a property of Vue without creating an instance, you need to add it as a static property.
Vue.$authStorage = authStorage
But, if it were me, I would probably take a different approach. I would likely build the AuthStorage plugin like this:
const authStorage = {
getToken() {
let token = localStorage.getItem('access_token')
let expiration = localStorage.getItem('expiration')
if (!token || !expiration) {
return null
}
if (Date.now() > parseInt(expiration)) {
this.destroyToken()
return null
}
return token
},
setToken(accessToken, expiration, refreshToken) {
localStorage.setItem('access_token', accessToken)
localStorage.setItem('expiration', expiration + Date.now())
localStorage.setItem('refresh_token', refreshToken)
},
destroyToken() {
localStorage.removeItem('access_token')
localStorage.removeItem('expiration')
localStorage.removeItem('refresh_token')
},
isAuthenticated() {
if (this.getToken()) {
return true
} else {
return false
}
},
install(Vue) {
Vue.prototype.$authStorage = this
}
}
export default authStorage
Which would allow me to use it like this outside of Vue,
import Vue from 'vue'
import App from './App'
import router from './router'
import AuthStorage from './AuthStorage.js'
Vue.config.productionTip = false
Vue.use(AuthStorage)
router.beforeEach((to, from, next) => {
if (to.matched.some(record => record.meta.requireAuth)) {
if (!AuthStorage.getToken()) {
next({
path: '/',
query: { redirect: to.fullPath }
})
} else {
next()
}
} else {
next()
}
})
And reference it like this inside of Vue:
created(){
let token = this.$authStorage.getToken()
}
Here is an example.
I'm trying to create an App with Vue, and Vue-ressource
Actually i need to use ressource to made auth system by an API call.
But in my Auth.js (that i import into my login.vue) console said he can't read $http of undefined. So apparantly i can't reach 'this' (so vue).
Did i missed something ? Or its just a bad use ?
Thank you all
actually my main.js :
import Vue from 'vue'
import VueRouter from 'vue-router'
import VueResource from 'vue-resource'
Vue.use(VueRouter)
Vue.use(VueResource)
import App from './components/App.vue'
import Login from './components/Login.vue'
import Home from './components/Containers.vue'
function requireAuth (to, from, next) {
if (!auth.loggedIn()) {
next({
path: '/',
query: { redirect: to.fullPath }
})
} else {
next()
}
}
const router = new VueRouter({
mode: 'history',
routes: [
{ path: '/home', name: 'home', component: Home, beforeEnter: requireAuth },
{ path: '/', component: Login },
{ path: '/logout',
beforeEnter (to, from, next) {
auth.logout()
next('/')
}}
]
})
new Vue({
el: '#app',
router,
render: h => h(App)
})
the login.vue
import auth from '../utils/auth'
export default {
data () {
return {
email: '',
pass: '',
error: false
}
},
methods: {
login () {
auth.login(this.email, this.pass, loggedIn => {
if (!loggedIn) {
this.error = true
} else {
console.log('good')
this.$router.replace('/home')
}
})
}
}
}
and my auth.js where the vue-ressource post is made :
export default {
login (email, pass, cb) {
cb = arguments[arguments.length - 1]
if (localStorage.token) {
if (cb) cb(true)
this.onChange(true)
return
}
pretendRequest(email, pass, (res) => {
if (res.authenticated) {
localStorage.token = res.token
if (cb) cb(true)
this.onChange(true)
} else {
if (cb) cb(false)
this.onChange(false)
}
})
},
getToken () {
return localStorage.token
},
logout (cb) {
delete localStorage.token
if (cb) cb()
this.onChange(false)
},
loggedIn () {
return !!localStorage.token
},
onChange () {}
}
function pretendRequest (email, pass, cb) {
setTimeout(() => {
this.$http.post('localhost:9000/api/login', {email: email, password: pass}).then(response => {
if (response.status === 200) {
cb({
authenticated: true,
token: Math.random().toString(36).substring(7)
})
} else {
cb({ authenticated: false })
}
}, response => {
console.log('error ' + response.status)
})
}, 0)
}
Replace vue-resource with axios. Easy to do. Vue-resource is not longer maintained by Vue team, so it's bad choice to use it.( https://medium.com/the-vue-point/retiring-vue-resource-871a82880af4#.dwmy5ymjx )
Axios is widely supported. https://github.com/mzabriskie/axios .
Nice laracasts about using axios with vue. You will quickly get it. https://laracasts.com/series/learn-vue-2-step-by-step/episodes/18
It is normal that you can't access Vue instance in your auth module. Try to learn more about using this and you will quickly get it 'why?'
To make ajax requests in your auth module, just import axios and use axios.post / axios.get
Any questions? Comment and I will explain more.