Can't access Vue from js - javascript

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.

Related

Infinite redirection using middleware

I'm trying to implement simple middleware logic and got
Detected an infinite redirection in a navigation guard when going from
"/" to "/login". Aborting to avoid a Stack Overflow. This will break
in production if not fixed.
I know that somewhere in my code it redirects more than once, but cannot find where.
Here is the router:
import { createWebHistory, createRouter } from 'vue-router'
import store from '#/store'
/* Guest Component */
const Login = () => import('#/components/Login.vue')
const Register = () => import('#/components/Register.vue')
/* Guest Component */
/* Layouts */
const DahboardLayout = () => import('#/components/layouts/Default.vue')
/* Layouts */
/* Authenticated Component */
const Dashboard = () => import('#/components/Dashboard.vue')
/* Authenticated Component */
const routes = [
{
name: "login",
path: "/login",
component: Login,
meta: {
middleware: "guest",
title: `Login`
}
},
{
name: "register",
path: "/register",
component: Register,
meta: {
middleware: "guest",
title: `Register`
}
},
{
path: "/",
component: DahboardLayout,
meta: {
middleware: ["all"]
},
children: [
{
name: "dashboard",
path: '/',
component: Dashboard,
meta: {
title: `Dashboard`
}
}
]
}
]
const router = createRouter({
history: createWebHistory(),
routes, // short for `routes: routes`
})
router.beforeEach((to, from, next) => {
document.title = to.meta.title
if (to.meta.middleware == "all") {
return next();
} else if (to.meta.middleware == "guest") {
if (store.state.auth.authenticated) {
return next({ name: "login" })
} else {
return next()
}
} else if (to.meta.middleware == "auth") {
if (store.state.auth.authenticated) {
return next()
} else {
return next({ name: "login" })
}
}
})
export default router
And in Default.vue component:
<router-link :to="{name:'login'}">Login</router-link>
Based on #DaveNewton questions I changed it like that and it works fine:
router.beforeEach((to, from, next) => {
document.title = to.meta.title
if (to.meta.middleware == "all") {
return next();
} else if (to.meta.middleware == "guest") {
if (!store.state.auth.authenticated) {
return next()
}
} else if (to.meta.middleware == "auth") {
if (store.state.auth.authenticated) {
return next()
} else {
return next({ name: "login" })
}
}
})
Every time you redirect in the beforeEach navigation guard the new route will also have to go through the navigation guard. The infinite loop is from trying to redirect to the login route, and always hitting this code:
else if (to.meta.middleware == "guest") {
if (store.state.auth.authenticated) {
return next({ name: "login" })
So you redirect to login, which redirects to login, which redirects... etc. You need to add some other condition to just return next() when going to the login route in this situation, maybe like this:
router.beforeEach((to, from, next) => {
document.title = to.meta.title;
if (to.meta.middleware == 'all' || to.name === 'login') {
return next();
}
...

Vue.js - redirecting user not authenticated to specific page, different from login

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.

Vue Router : function push is not working with Store modification

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?

How can i implement Role based authentication in vuejs?

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.

Using vuejs plugin on the main.js file

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.

Categories

Resources