Angular: E2E Test via login page - javascript

I have an Angular application using an Express.js backend. It features a default address pathway to a login page /avior/login. I need to write an E2E Test for the whole application and I just started writing the first test part which is supposed to recognize the login page and login itself and then check whether the redirect was successful. I have wrote this error-prone code so far:
import { AppPage } from './app.po';
import { browser, logging, element } from 'protractor';
import { async, ComponentFixture, fakeAsync, TestBed, tick,
} from '#angular/core/testing';
import {AppComponent} from '../../src/app/app.component'
let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let page: AppPage;
let router: Router;
let location: SpyLocation;
let username: 'Test';
let password: 'testtest';
let usernameInput: element(by.css('#inputUser'));
let passwordInput: element(by.css('#inputPassword'));
let loginButton: element(by.css('#loginSubmit'));
describe('Avior App', () => {
let page: AppPage;
beforeEach(() => {
page = new AppPage();
});
it('should navigate to "/avior/login" immediately', fakeAsync(() => {
createComponent();
tick(); // wait for async data to arrive
expect(location.path()).toEqual('/avior/login', 'after initialNavigation()');
expectElementOf(DashboardComponent);
}));
it('should display Login message in the header', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Anmeldung');
});
it('there should be username and password login fields', () => {
// how to check?
});
it('login using false credentials should make you stay put and throw an error', () => {
// how to?
});
it('login using Test:testtset (=successful credentials => successful login) should redirect to /avior/dashboard', () => {
// how to?
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
function createComponent() {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
const injector = fixture.debugElement.injector;
location = injector.get(Location) as SpyLocation;
router = injector.get(Router);
router.initialNavigation();
spyOn(injector.get(TwainService), 'getQuote')
// fake fast async observable
.and.returnValue(asyncData('Test Quote'));
advance();
page = new Page();
}
function loginFn() {
usernameInput.sendKeys(username);
passwordInput.sendKeys(password);
loginButton.click();
};
How to fix this code?
UPDATE
I tried simplifying my code to only include routing tests so far and I get new errors thrown out.
My new code is the following:
import { AppPage } from './app.po';
import { browser, logging, element } from 'protractor';
import { async, ComponentFixture, fakeAsync, TestBed, tick,
} from '#angular/core/testing';
import {AppComponent} from '../../src/app/app.component'
import {Component} from "#angular/core";
import {RouterTestingModule} from "#angular/router/testing";
import {Routes} from "#angular/router";
import {Router} from "#angular/router";
import { AviorComponent } from '../../src/app/avior/avior.component';
import { DashboardComponent } from '../../src/app/avior/dashboard/dashboard.component';
import { ProfileComponent } from '../../src/app/avior/profile/profile.component';
import { SettingsComponent } from '../../src/app/avior/settings/settings.component';
import { LoginComponent } from '../../src/app/avior/login/login.component';
import { PageNotFoundComponent } from '../../src/app/avior/page-not-found/page-not-found.component';
import { InfoComponent } from '../../src/app/avior/info/info.component';
import { UsersComponent } from '../../src/app/avior/users/users.component';
import { MandatorsComponent } from '../../src/app/avior/mandators/mandators.component';
import { SystemComponent } from '../../src/app/avior/system/system.component';
import { WorkflowsComponent } from '../../src/app/avior/workflows/workflows.component';
import { MessagesComponent } from '../../src/app/avior/messages/messages.component';
import { BrowserDynamicTestingModule,
platformBrowserDynamicTesting } from '#angular/platform-browser-dynamic/testing';
/* let comp: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let page: AppPage;
let router: Router;
let location: SpyLocation;
let username: 'Chad';
let password: 'chadchad';
let usernameInput: element(by.css('#inputUser'));
let passwordInput: element(by.css('#inputPassword'));
let loginButton: element(by.css('#loginSubmit')); */
const aviorRoutes: Routes = [{
path: '', component: AviorComponent,
children: [
{
path: '', component: ProfileComponent
},
{
path: 'dashboard', component: DashboardComponent,
data: {title: 'Dashboard'},
},
{
path: 'login', component: LoginComponent,
data: {title: 'Login'},
},
{
path: 'logout', component: LoginComponent,
data: {title: 'Login'},
},
{
path: 'profile', component: ProfileComponent,
data: {title: 'Profil'},
},
{
path: 'settings', component: SettingsComponent,
data: {title: 'Einstellungen'},
},
{
path: 'info', component: InfoComponent,
data: {title: 'Info'},
},
{
path: 'users', component: UsersComponent,
data: {title: 'Benutzer'},
},
{
path: 'workflows', component: WorkflowsComponent,
data: {title: 'Workflows'},
},
{
path: 'system', component: SystemComponent,
data: {title: 'System'},
},
{
path: 'mandators', component: MandatorsComponent,
data: {title: 'Mandanten'}
},
{
path: 'messages', component: MessagesComponent,
data: {title: 'Nachrichten'}
},
{
path: '404', component: PageNotFoundComponent,
data: {title: 'Page not found'},
}
]
}];
describe('Avior App', () => {
let page: AppPage;
beforeEach(() => {
TestBed.resetTestEnvironment();
TestBed.initTestEnvironment(BrowserDynamicTestingModule,
platformBrowserDynamicTesting())
TestBed.configureTestingModule({
imports: [RouterTestingModule.withRoutes(aviorRoutes)],
declarations: [
DashboardComponent,
ProfileComponent,
SettingsComponent,
LoginComponent,
PageNotFoundComponent,
InfoComponent,
UsersComponent,
MandatorsComponent,
SystemComponent,
WorkflowsComponent,
MessagesComponent
]
});
page = new AppPage();
this.router = TestBed.get(Router);
location = TestBed.get(Location);
this.fixture = TestBed.createComponent(AppComponent);
this.router.initialNavigation();
});
/* it('should navigate to "/avior/login" immediately', fakeAsync(() => {
createComponent();
tick(); // wait for async data to arrive
expect(location.path()).toEqual('/avior/login', 'after initialNavigation()');
expectElementOf(DashboardComponent);
})); */
it('navigate to "" redirects you to /avior/login', fakeAsync(() => {
  this.router.navigate(['']);
tick();
expect(location.path()).toBe('/avior/login');
}));
it('navigate to "dashboard" takes you to /dashboard', fakeAsync(() => {
  this.router.navigate(['dashboard']);
 tick();
expect(location.path()).toBe('avior/dashboard');
}));
it('should display Anmeldung message in the header', () => {
page.navigateTo();
expect(page.getTitleText()).toEqual('Anmeldung');
});
it('there should be username and password login fields', () => {
});
it('login using false credentials should make you stay put and throw an error', () => {
});
it('login using Chad:chadchad should redirect to /avior/dashboard', () => {
});
afterEach(async () => {
// Assert that there are no errors emitted from the browser
const logs = await browser.manage().logs().get(logging.Type.BROWSER);
expect(logs).not.toContain(jasmine.objectContaining({
level: logging.Level.SEVERE,
} as logging.Entry));
});
});
/* function createComponent() {
fixture = TestBed.createComponent(AppComponent);
comp = fixture.componentInstance;
const injector = fixture.debugElement.injector;
location = injector.get(Location) as SpyLocation;
router = injector.get(Router);
router.initialNavigation();
spyOn(injector.get(TwainService), 'getQuote')
// fake fast async observable
.and.returnValue(asyncData('Test Quote'));
advance();
page = new Page();
}
function loginFn(username, password) {
usernameInput.sendKeys(username);
passwordInput.sendKeys(password);
loginButton.click();
};
*/
The errors get thrown out during ng e2e runtime:
- Failed: Can't resolve all parameters for ApplicationModule: (?). - Failed: Cannot read property 'assertPresent' of null

Related

Why style.backgroundImage returns empty?

So here is the HTML
<button class="w drum">w</button>
<script src="index.js" charset="utf-8"></script>
And This is the CSS
.w {
background-image: url("images/tom1.png");
}
.a {
background-image: url("images/tom2.png");
}
.s {
background-image: url("images/tom3.png");
}
.d {
background-image: url("images/tom4.png");
}
.j {
background-image: url("images/snare.png");
}
.k {
background-image: url("images/crash.png");
}
.l {
background-image: url("images/kick.png");
}
Lastly this is the javascript
for (let i in document.querySelectorAll(".drum")) {
document.querySelectorAll(".drum")[i].addEventListener("click", handleClick);
}
function handleClick() {
var url = this.style.backgroundImage;
console.log(url);
}
So when I click on w / a / s / d / etc. button, Console should return the image url right?
But this is what happened...
Console log shows empty string
Why is it empty??? Plz help
Use NodeList.prototype.forEach() and Window.getComputedStyle
const handleClick = (evt) => {
const url = getComputedStyle(evt.currentTarget).backgroundImage;
console.log(url);
}
document.querySelectorAll(".drum").forEach((elDrum) => {
elDrum.addEventListener("click", handleClick);
});
import { createApp, markRaw } from 'vue'
import { createPinia } from 'pinia'
import App from './App.vue'
import router from './router'
import vue3GoogleLogin from 'vue3-google-login'
import './assets/style.css'
const app = createApp(App)
app.use(vue3GoogleLogin, {
clientId: '433430770978-3pff7bk6ff4qmcc8qnvpckqil6q17bg2.apps.googleusercontent.com'
})
const pinia = createPinia()
pinia.use(({ store }) => {
store.router = markRaw(router)
})
app.use(router)
app.use(pinia)
app.mount('#app')
di dalam router:
import { createRouter, createWebHistory } from 'vue-router'
const routes = [
{path: '/', name: 'home', component: Home},
{path: '/menu', name: 'menu', component: Menu},
{path: '/login', name: 'login', component: Login, beforeEnter:(to, from, next) => {
if(!localStorage.getItem("access_token")) {
next()
} else{
next('/')
}
}},
{path: '/register', name: 'register', component: Register, beforeEnter:(to, from, next ) => {
if(!localStorage.getItem("access_token")) {
next()
} else{
next('/')
}
}},
{path: '/menu/:id', name: 'detail', component: Detail},
{path: '/favorite', name: 'favorite', component: Favorite, beforeEnter:(to, from, next) => {
if(localStorage.getItem("access_token")){
next()
} else{
next('/')
}
}},
]
const router = createRouter({
history: createWebHistory(),
routes
})
export default router
di dalam store nya
import { ref, computed } from 'vue'
import { defineStore } from 'pinia'
import axios from 'axios';
export const useAppStore = defineStore("app", {
state: () => ({
isAuth: false,
foods: [],
food: {},
favorite: [],
}),
getters:{},
actions:{
checkAuth(){
this.isAuth = !!localStorage.getItem('access_token')
},
// tempat methode terjadi
}
})
di dalam component:
import {mapActions, mapState, mapWritableState } from "pinia"
import { useAppStore } from './stores/app'
export default{
name: "Register",
components:{},
data(){
return{
data:{
email: "",
password: "",
phoneNumber: "",
address: "",
}
}
},
computed:{
...mapState(useAppStore,["var"])
},
methods:{
...mapActions(useAppStore, ["var"])
},
created(){
}
}

"TypeError: next is not a function" in the router.js file of my vue 3 project when trying to apply navigation guards?

I don't understand why i doesn't recognise the next function whereas i followed a similar video implementing this and it worked with no errors
I don't understand why i doesn't recognise the next function whereas i followed a similar video implementing this and it worked with no errors
I don't understand why i doesn't recognise the next function whereas i followed a similar video implementing this and it worked with no errors
import Dashboard from "./Pages/Dashboard.vue";
import Customers from "./Pages/Customers.vue";
import EditProfile from "./Pages/EditProfile.vue";
import Insurance from "./Pages/Insurance.vue";
import Activations from "./Pages/Activations.vue";
import Login from "./Pages/Login.vue"
import ForgotPassword from "./Pages/ForgotPassword.vue"
import MyDashboard from "./Pages_cus/MyDashboard.vue";
import MyActivations from "./Pages_cus/MyActivations.vue";
import MyEditProfile from './Pages_cus/MyEditProfile.vue';
import NotFound from './Pages/NotFound.vue';
import NetworkError from './Pages/NetworkError.vue'
import { createRouter, createWebHistory } from "vue-router";
const routes = [
{
name: "MyDashboard",
component: MyDashboard,
path: "/my-dashboard",
meta: {
requiresAuth: true,
}
},
{
name: "MyActivations",
component: MyActivations,
path: "/my-activations",
},
{
name: "MyEditProfile",
component: MyEditProfile,
path: "/my-edit-profile",
},
{
name: "Dashboard",
component: Dashboard,
path: "/dashboard",
meta: {
requiresAuth: true,
}
},
{
name: "Customers",
component: Customers,
path: "/customers",
},
{
name: "EditProfile",
component: EditProfile,
path: "/edit-profile",
},
{
name: "Insurance",
component: Insurance,
path: "/insurance",
},
{
name: "Activations",
component: Activations,
path: "/activations",
},
{
name: "Login",
component: Login,
path: "/",
meta: {
requiresAuth: true,
}
},
{
name: "ForgotPassword",
component: ForgotPassword,
path: "/forgot-password",
},
{
name: "404Resource",
component: NotFound,
path: '/404/:resource',
props:true
},
{
name: "NetworkError",
component: NetworkError,
path: '/network-error'
},
{
name: "NotFound",
component: NotFound,
path: '/:catchAll(.*)'
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
router.beforeEach((to, next)=>{
if (to.matched.some(record => record.meta.requiresAuth)) {
if (localStorage.getItem('token') == null) {
console.log('Hello JS')
next({
path: '/',
params: { nextUrl: to.fullPath }
}) // I get the error at this level it doesn't recognise next as a function
}
else{
next();
}
}
else {
next()
}
})
export default router;
[Screenshot of code in VS code][1]
[Screenshot of code in browser
<!-- begin snippet: js hide: false console: true babel: false -->
import Dashboard from "./Pages/Dashboard.vue";
import Customers from "./Pages/Customers.vue";
import EditProfile from "./Pages/EditProfile.vue";
import Insurance from "./Pages/Insurance.vue";
import Activations from "./Pages/Activations.vue";
import Login from "./Pages/Login.vue"
import ForgotPassword from "./Pages/ForgotPassword.vue"
import MyDashboard from "./Pages_cus/MyDashboard.vue";
import MyActivations from "./Pages_cus/MyActivations.vue";
import MyEditProfile from './Pages_cus/MyEditProfile.vue';
import NotFound from './Pages/NotFound.vue';
import NetworkError from './Pages/NetworkError.vue'
import { createRouter, createWebHistory } from "vue-router";
const routes = [
{
name: "MyDashboard",
component: MyDashboard,
path: "/my-dashboard",
meta: {
requiresAuth: true,
}
},
{
name: "MyActivations",
component: MyActivations,
path: "/my-activations",
},
{
name: "MyEditProfile",
component: MyEditProfile,
path: "/my-edit-profile",
},
{
name: "Dashboard",
component: Dashboard,
path: "/dashboard",
meta: {
requiresAuth: true,
}
},
{
name: "Customers",
component: Customers,
path: "/customers",
},
{
name: "EditProfile",
component: EditProfile,
path: "/edit-profile",
},
{
name: "Insurance",
component: Insurance,
path: "/insurance",
},
{
name: "Activations",
component: Activations,
path: "/activations",
},
{
name: "Login",
component: Login,
path: "/",
meta: {
requiresAuth: true,
}
},
{
name: "ForgotPassword",
component: ForgotPassword,
path: "/forgot-password",
},
{
name: "404Resource",
component: NotFound,
path: '/404/:resource',
props:true
},
{
name: "NetworkError",
component: NetworkError,
path: '/network-error'
},
{
name: "NotFound",
component: NotFound,
path: '/:catchAll(.*)'
},
];
const router = createRouter({
history: createWebHistory(),
routes,
});
router.beforeEach((to, next)=>{
if (to.matched.some(record => record.meta.requiresAuth)) {
if (localStorage.getItem('token') == null) {
console.log('Hello JS')
next({
path: '/',
params: { nextUrl: to.fullPath }
}) // I get the error at this level it doesn't recognise next as a function
}
else{
next();
}
}
else {
next()
}
})
export default router;
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.5.17/vue.js"></script>
[1]: https://i.stack.imgur.com/Y9D08.png
[2]: https://i.stack.imgur.com/n9ERj.png
next is the third argument for the beforeEach function, so it should be:
beforeEach((to, from, next)) => {...
While you're using the next function correctly here (ensuring that it's called exactly once), it is currently deprecated: https://github.com/vuejs/rfcs/blob/master/active-rfcs/0037-router-return-guards.md#motivation
It's now suggested to use 1 or 2 arguments and return a boolean value to indicate whether or not to proceed, or a route to redirect to:
router.beforeEach((to)=>{
if (to.matched.some(record => record.meta.requiresAuth)
&& localStorage.getItem('token') == null) {
//redirect
return {
name: '/',
query: { nextUrl: to.fullPath }
}
}
return true; //proceed (equivalent of next())
});

Why is router.push not working? [Vue3] [Vuex4]

I have some issues with Vue 3 and Vuex.
I'm trying to redirect users when logged in in my Vuex file, but it's not working as expected.
It's not returning any errors, it's changing a link, but not redirected to another page.
My action looks like this;
actions: {
async login(commit: any, payload: any ) {
const cookie_token = useCookies();
API.post('/login', {
email: payload.email.value,
password: payload.password.value
})
.then((response: any) => {
notif.success('Welcome back, ' + response.data.player.name)
cookie.set('user', response.data)
commit.commit('loginSuccess', response.data)
router.push({
name: 'index',
})
}).catch((e) => (
console.log(e.message)
)
)
}
},
And the router is getting files where routes are defined.
And here is my full router file:
import {
createRouter as createClientRouter,
createWebHistory,
} from 'vue-router'
import * as NProgress from 'nprogress'
// import routes from 'pages-generated'
import type { RouteRecordRaw } from "vue-router";
// Then we can define our routes
const routes: RouteRecordRaw[] = [
// This is a simple route
{
component: () => import("/#src/pages/index.vue"),
name: "index",
path: "/",
props: true,
},
{
component: () => import("/#src/pages/auth.vue"),
path: "/auth",
props: true,
children: [
{
component: () => import("/#src/pages/auth/login.vue"),
name: "auth-login",
path: "login-1",
props: true,
},
{
component: () => import("/#src/pages/auth/login.vue"),
name: "auth-signup",
path: "singup",
props: true,
},
],
},
{
component: () => import("/#src/pages/[...all].vue"),
name: "404",
path: "/:all(.*)",
props: true,
},
];
export function createRouter() {
const router = createClientRouter({
history: createWebHistory(),
routes,
})
/**
* Handle NProgress display on-page changes
*/
router.beforeEach(() => {
NProgress.start()
})
router.afterEach(() => {
NProgress.done()
})
return router
}
export default createRouter()
Have in mind that it's working on other files, and I can see that router is triggered here, but not chaning a page, only on vuex is not working. If it's not working, why there is no error?
You're creating more than one instance of Vue Router. You should export the same router instance, not a function creating a new instance each time it gets called.
The following code will likely yield the desired outcome:
import {
createRouter,
createWebHistory,
} from 'vue-router'
import * as NProgress from 'nprogress'
import type { RouteRecordRaw } from "vue-router";
const routes: RouteRecordRaw[] = [
// your routes here...
];
let router;
export function useRouter() {
if (!router) {
router = createRouter({
history: createWebHistory(),
routes,
})
router.beforeEach(() => {
NProgress.start()
})
router.afterEach(() => {
NProgress.done()
})
}
return router
}
I'm placing the router instance in the outer scope, so you always get the same instance when calling useRouter().
Consume it using:
import { useRouter } from '../path/to/router'
const router = useRouter();

Vue router and Firebase middleware. I cannot move to the next page after logging in

I am using vue and firebase.
I want to add the redirect method using vue-router.
In my vue-router code, I have meta: { requiresAuth: true } in the multiple pages for the middleware.
My vue-router redirect method is, if jwt token is not stored in the local storage, the url redirects to /login.
I am using firebase, so I think the user account token is stored in the local storage when the user logs in.
So if my vuex code is correct, my vue-router code supposed to work properly.
Now, if I login as a user, the url doesn't change. But if I enter the
specific user's dashboard page, the redirect is working.
Why doesn't the url change when I log in?
import Vue from 'vue'
import VueRouter from 'vue-router'
//import Home from '../views/Home.vue'
import Dashboard from '../views/Dashboard.vue'
import OrdersMobile from '../views/OrdersMobile.vue'
Vue.use(VueRouter)
const routes = [
{
path: '/',
name: 'Home',
component: () => import(/* webpackChunkName: "about" */ '../selfonboarding/Home.vue')
},
{
path: '/login',
name: 'Login',
component: () => import(/* webpackChunkName: "about" */ '../components/Login.vue')
},
{
path: '/dashboard/',
name: 'Dashboard',
component: Dashboard,
meta: { requiresAuth: true },
children: [
{
path: 'products/:id',
name: 'Products',
component: () => import(/* webpackChunkName: "about" */ '../views/Products.vue')
},
{
path: 'working-hours/:id',
name: 'WorkingHours',
component: () => import(/* webpackChunkName: "about" */ '../views/WorkingHours.vue')
},
// {
// path: 'pictures/:id',
// name: 'Pictures',
// component: Pictures,
// },
{
path: 'orders/:id',
name: 'Orders',
component: () => import(/* webpackChunkName: "about" */ '../views/Orders.vue')
},
{
path: 'orders.s/:id',
name: 'OrdersMobile',
component: OrdersMobile,
children: [
{
path: 'processed',
name: 'Processed',
component: () => import(/* webpackChunkName: "about" */ '../views/Processed.vue')
}
]
},
{
path: 'information/:id',
name: 'Information',
component: () => import(/* webpackChunkName: "about" */ '../views/Information.vue')
},
{
path: 'information.s/:id',
name: 'InformationMobile',
component: () => import(/* webpackChunkName: "about" */ '../views/InformationMobile.vue')
},
]
}
]
const router = new VueRouter({
mode: 'history',
base: process.env.BASE_URL,
routes,
})
router.beforeEach((to, from, next) => {
if(to.matched.some(record => record.meta.requiresAuth)) {
if (localStorage.getItem('jwt') == null) {
next({
path: '/login',
params: { nextUrl: to.fullPath }
})
}
} else {
next()
}
})
export default router
vuex code
../store/user.js
import 'firebase/firebase-auth'
import fireApp from '#/plugins/firebase'
import router from '../../router'
const firebase = require("firebase");
require("firebase/firestore");
const db = firebase.firestore();
const state = {
currentUser: null
}
const getters = {
currentUser: state => state.currentUser
}
const mutations = {
userStatus: (state, user) => {
user === null ? state.currentUser = null : state.currentUser = user.email
}
}
const actions = {
signIn: async ({ commit }, user) => {
try {
const userData = await fireApp.auth().signInWithEmailAndPassword(
user.email,
user.password
);
// Get the user id (from the user object I guess)
const userId = fireApp.auth().currentUser.uid;
// or maybe through const userId = fireApp.auth().currentUser.uid;
const proUserDocRef = db.collection('ProUser').doc(userId);
proUserDocRef.get().then((doc) => {
if(doc.exists && doc.data().status === true) {
router.push({name:'Products',params:{id: userId}}).catch(err => {})
} else if(doc.exists && doc.data().status === false){
router.push({name:'Welcome',params:{id: userId}}).catch(err => {})
} else {
alert('You are not registered as a pro user.')
}
})
}
catch(error) {
const errorCode = error.code
const errorMesage = error.message
if(errorCode === 'auth/wrong-password') {
alert('wrong password')
} else {
alert(errorMesage)
}
}
},
signOut: async({ commit }) => {
try {
await fireApp.auth().signOut()
}
catch(error) {
alert(`error sign out, ${error}`)
}
commit('userStatus', null)
}
}
export default {
state,
mutations,
getters,
actions
}
The beforeEach navigation guard is missing a next() call when the route requires authentication and you are logged in:
router.beforeEach((to, from, next) => {
if(to.matched.some(record => record.meta.requiresAuth)) {
if (localStorage.getItem('jwt') == null) {
next({
path: '/login',
params: { nextUrl: to.fullPath }
})
} else {
next(); // Add this ✅
}
} else {
next()
}
})
I added
const token = await firebase.auth().currentUser.getIdToken(true)
localStorage.setItem('jwt', token)
in user.js actions section.
Then, I could make it.
I couldn't set the jwt token in the local storage.
So I did when I log in to the website.
Also I was missing to add next().

Vuex sore lost when manually navigate vue-router route

ONLY ON SAFARI BROWSER.
When I manually write the url on navigation bar after logged in, ex: "http://x.x.x.x:8080/gestione", the browser loses the vuex store state (so does the gest_user module with the currentUser) and redirect to login component, I'M USING VUEX-PERSISTEDSTATE:
routes:
const routes = [
{
id: "login",
path: "/login",
name: "login",
component: Login,
meta: {
...meta.default
}
},
{
id: "home",
path: "/",
name: "homeriluser",
component: HomeUtente,
meta: {
...meta.public, authorize: [Role.user, Role.admin]
},
},
{
id: "gestione",
path: "/gestione",
name: "gestrilevazioni",
component: GestRils,
meta: {
...meta.admin, authorize: [Role.admin]
}
},
{
path: "/modifica",
name: "modificaril",
component: EditRil,
meta: {
...meta.public, authorize: [Role.user, Role.admin]
}
},
{
path: "*",
name: "page404",
component: Pagenotfound,
meta: {
...meta.public
}
}
];
my router:
import Vue from 'vue';
import VueRouter from 'vue-router';
import routes from "./router";
import store from "#/store/index"
Vue.use(VueRouter);
const router = new VueRouter({
routes,
mode: "history"
});
router.beforeEach(async (to, from, next) => {
// redirect to login page if not logged in and trying to access a restricted page
const { auth } = to.meta;
const { authorize } = to.meta;
const currentUser = store.state.gest_user;
if (auth) {
if (!currentUser.username) {
// not logged in so redirect to login page with the return url
return next({ path: '/login', query: { returnUrl: to.path } });
}
// check if route is restricted by role
if (authorize && authorize.length && !authorize.includes(currentUser.roles)) {
// role not authorised so redirect to home page
return next({ path: '/' });
}
}
next();
});
export default router;
my store:
import createPersistedState from "vuex-persistedstate";
Vue.use(Vuex);
Vue.prototype.$http = axios;
Vue.prototype.axios = axios;
const debug = process.env.NODE_ENV !== "production";
const customPersist = createPersistedState({
paths: ["gest_user", "gest_rilevazione.rilevazione"],
storage: {
getItem: key => sessionStorage.getItem(key),
setItem: (key, value) => {
sessionStorage.setItem(key, value)
},
removeItem: key => sessionStorage.removeItem(key)
}
});
const store = new Vuex.Store({
modules: {
pubblico: pubblico,
amministrazione: amministrazione,
loading_console: loading_console,
login_console: login_console,
gest_itemconc: gest_itemconc,
gest_rilslave: gest_rilslave,
gest_rilmaster: gest_rilmaster,
sidebar_console: sidebar_console,
gest_user: gest_user,
gest_newril: gest_newril,
gest_rilevazione: gest_rilevazione
},
plugins: [customPersist],
strict: debug
});
export default store;
Can anyone tell me why this happens?
You are probably using browser's local storage to persist data. Could you check if local storage is enabled in your Safari browser?

Categories