Skip to content

Commit 97c28f6

Browse files
committed
rework vue route
1 parent 8f0e893 commit 97c28f6

File tree

7 files changed

+160
-152
lines changed

7 files changed

+160
-152
lines changed

generators/vue/files-vue.mjs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ export const vueFiles = {
230230
...clientTestBlock,
231231
templates: [
232232
'jest.conf.js',
233+
'spec/app/reset-store.ts',
233234
'spec/app/account/account.service.spec.ts',
234235
'spec/app/core/home/home.component.spec.ts',
235236
'spec/app/core/error/error.component.spec.ts',
Lines changed: 51 additions & 63 deletions
Original file line numberDiff line numberDiff line change
@@ -1,12 +1,10 @@
11
import axios from 'axios';
22
import { Store } from 'vuex';
3-
import VueRouter from 'vue-router';
43
<%_ if (enableTranslation) { _%>
54
import TranslationService from '@/locale/translation.service';
65
<%_ } _%>
76

87
export default class AccountService {
9-
108
constructor(
119
private store: Store<any>,
1210
<%_ if (enableTranslation) { _%>
@@ -15,99 +13,89 @@ export default class AccountService {
1513
<%_ if (authenticationTypeSession || authenticationTypeOauth2) { _%>
1614
private cookie: any,
1715
<%_ } _%>
18-
private router: VueRouter
1916
) {
20-
this.init();
2117
}
2218

23-
public init(): void {
24-
this.retrieveProfiles();
19+
public async init(): Promise<void> {
20+
if (!this.store.getters.profilesLoaded) {
21+
await this.retrieveProfiles();
22+
this.store.commit('profilesLoaded');
23+
}
2524
}
2625

27-
public retrieveProfiles(): Promise<boolean> {
28-
return new Promise(resolve => {
29-
axios.get<any>('management/info').then(res => {
30-
if (res.data && res.data.activeProfiles) {
31-
this.store.commit('setRibbonOnProfiles', res.data['display-ribbon-on-profiles']);
32-
this.store.commit('setActiveProfiles', res.data['activeProfiles']);
33-
}
34-
resolve(true);
35-
}).catch(() => resolve(false));
36-
});
26+
public async retrieveProfiles(): Promise<boolean> {
27+
try {
28+
const res = await axios.get<any>('management/info');
29+
if (res.data && res.data.activeProfiles) {
30+
this.store.commit('setRibbonOnProfiles', res.data['display-ribbon-on-profiles']);
31+
this.store.commit('setActiveProfiles', res.data['activeProfiles']);
32+
}
33+
return true;
34+
} catch (error) {
35+
return false;
36+
}
3737
}
3838

39-
public retrieveAccount(): Promise<boolean> {
40-
return new Promise(resolve => {
41-
axios
42-
.get<any>('api/account').then((response) => {
43-
this.store.commit('authenticate');
39+
public async retrieveAccount(): Promise<boolean> {
40+
try {
41+
const response = await axios.get<any>('api/account');
42+
if (response.status === 200 && response.data) {
4443
const account = response.data;
45-
if (account) {
46-
this.store.commit('authenticated', account);
44+
this.store.commit('authenticated', account);
4745
<%_ if (enableTranslation) { _%>
48-
if (this.store.getters.currentLanguage !== account.langKey) {
49-
this.store.commit('currentLanguage', account.langKey);
50-
}
51-
<%_ } _%>
52-
if(sessionStorage.getItem('requested-url')) {
53-
this.router.replace(sessionStorage.getItem("requested-url"));
54-
sessionStorage.removeItem("requested-url");
55-
}
56-
} else {
57-
this.store.commit('logout');
58-
if (this.router.currentRoute.path !== '/') {
59-
this.router.push('/');
60-
}
61-
sessionStorage.removeItem("requested-url");
46+
if (this.store.getters.currentLanguage !== account.langKey) {
47+
this.store.commit('currentLanguage', account.langKey);
48+
this.translationService.refreshTranslation(this.store.getters.currentLanguage);
6249
}
63-
<%_ if (enableTranslation) { _%>
64-
this.translationService.refreshTranslation(this.store.getters.currentLanguage);
6550
<%_ } _%>
66-
resolve(true);
67-
}).catch(() => {
68-
this.store.commit('logout');
69-
resolve(false);
70-
});
71-
});
51+
return true;
52+
}
53+
} catch (error) {}
54+
55+
this.store.commit('logout');
56+
return false;
7257
}
7358

74-
public hasAnyAuthorityAndCheckAuth(authorities: any): Promise<boolean> {
75-
if (typeof authorities === 'string') {
76-
authorities = [authorities];
59+
public async loadAccount() {
60+
if (this.store.getters.logon) {
61+
return this.store.getters.logon;
7762
}
7863

79-
if (!this.authenticated || !this.userAuthorities) {
80-
const token = <%_ if (authenticationTypeJwt) { _%> localStorage.getItem('<%=jhiPrefixDashed %>-authenticationToken') || sessionStorage.getItem('<%=jhiPrefixDashed %>-authenticationToken'); <%_ } else { _%> this.cookie.get('JSESSIONID') || this.cookie.get('XSRF-TOKEN'); <%_ } _%>
81-
if (!this.store.getters.account && !this.store.getters.logon && token) {
82-
return this.retrieveAccount().then(resp => {
83-
if (resp) {
84-
return this.checkAuthorities(authorities);
85-
}
86-
return Promise.resolve(false);
87-
});
88-
}
89-
return Promise.resolve(false);
64+
const token = localStorage.getItem('jhi-authenticationToken') || sessionStorage.getItem('jhi-authenticationToken');
65+
if (this.authenticated && this.userAuthorities && token) {
66+
return;
67+
}
68+
69+
const promise = this.retrieveAccount();
70+
this.store.commit('authenticate', promise);
71+
return await promise;
72+
}
73+
74+
public async hasAnyAuthorityAndCheckAuth(authorities: any): Promise<boolean> {
75+
if (typeof authorities === 'string') {
76+
authorities = [authorities];
9077
}
9178

79+
await this.loadAccount();
9280
return this.checkAuthorities(authorities);
9381
}
9482

9583
public get authenticated(): boolean {
9684
return this.store.getters.authenticated;
9785
}
9886

99-
public get userAuthorities(): any {
87+
public get userAuthorities(): string[] {
10088
return this.store.getters.account?.authorities;
10189
}
10290

103-
private checkAuthorities(authorities: any): Promise<boolean> {
91+
private checkAuthorities(authorities: string[]): boolean {
10492
if (this.userAuthorities) {
10593
for (const authority of authorities) {
10694
if (this.userAuthorities.includes(authority)) {
107-
return Promise.resolve(true);
95+
return true;
10896
}
10997
}
11098
}
111-
return Promise.resolve(false);
99+
return false;
112100
}
113101
}

generators/vue/templates/src/main/webapp/app/main.ts.ejs

Lines changed: 50 additions & 32 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
// The Vue build version to load with the `import` command
22
// (runtime-only or standalone) has been set in webpack.common with an alias.
33
import Vue from 'vue';
4-
import {FontAwesomeIcon} from '@fortawesome/vue-fontawesome';
4+
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';
55
import { setupAxiosInterceptors } from '@/shared/config/axios-interceptor';
66

77
import App from './app.vue';
@@ -11,7 +11,7 @@ import router<% if (applicationTypeGateway && microfrontend) { %>, { lazyRoutes
1111
import * as config from './shared/config/config';
1212
import * as bootstrapVueConfig from './shared/config/config-bootstrap-vue';
1313
import JhiItemCountComponent from './shared/jhi-item-count.vue';
14-
import JhiSortIndicatorComponent from "./shared/sort/jhi-sort-indicator.vue";
14+
import JhiSortIndicatorComponent from './shared/sort/jhi-sort-indicator.vue';
1515
import InfiniteLoading from 'vue-infinite-loading';
1616
<%_ if (withAdminUi) { _%>
1717
import HealthService from './admin/health/health.service';
@@ -66,9 +66,11 @@ const trackerService = new TrackerService(router, store<%_ if (authenticationTyp
6666
const translationService = new TranslationService(store, i18n);
6767
<%_ } _%>
6868
const loginService = new LoginService();
69-
const accountService = new AccountService(store, <%_ if (enableTranslation) { _%>translationService, <%_ } _%><%_ if (authenticationTypeSession || authenticationTypeOauth2) { _%>(<any>Vue).cookie, <%_ } _%>router);
69+
const accountService = new AccountService(store<%_ if (enableTranslation) { _%>, translationService<%_ } _%><%_ if (authenticationTypeSession || authenticationTypeOauth2) { _%>, (<any>Vue).cookie<%_ } _%>);
7070

7171
router.beforeEach(async (to, from, next) => {
72+
await accountService.retrieveProfiles();
73+
await accountService.loadAccount();
7274
if (!to.matched.length) {
7375
<%_ if (applicationTypeGateway && microfrontend) { _%>
7476
await lazyRoutes;
@@ -78,22 +80,60 @@ router.beforeEach(async (to, from, next) => {
7880
}
7981
8082
<%_ } _%>
81-
next('/not-found');
83+
next({ path: '/not-found' });
8284
} else if (to.meta && to.meta.authorities && to.meta.authorities.length > 0) {
83-
accountService.hasAnyAuthorityAndCheckAuth(to.meta.authorities).then(value => {
84-
if (!value) {
85+
const value = await accountService.hasAnyAuthorityAndCheckAuth(to.meta.authorities);
86+
if (!value) {
87+
if (router.currentRoute.path !== '/forbidden') {
8588
sessionStorage.setItem('requested-url', to.fullPath);
86-
next('/forbidden');
89+
next({ path: '/forbidden' });
8790
} else {
8891
next();
8992
}
90-
});
93+
} else {
94+
const requestedUrl = sessionStorage.getItem('requested-url');
95+
if (requestedUrl) {
96+
router.replace(requestedUrl);
97+
sessionStorage.removeItem('requested-url');
98+
} else {
99+
next();
100+
}
101+
}
91102
} else {
92103
// no authorities, so just proceed
93104
next();
94105
}
95106
});
96107

108+
<%_ if (!authenticationTypeOauth2) { _%>
109+
let openLogin = () => {};
110+
<%_ } _%>
111+
setupAxiosInterceptors(
112+
error => {
113+
const url = error.response?.config?.url;
114+
const status = error.status || error.response.status;
115+
if (status === 401) {
116+
// Store logged out state.
117+
store.commit('logout');
118+
if (!url.endsWith('api/account') && !url.endsWith('api/authenticate')) {
119+
// Ask for a new authentication
120+
<%_ if (authenticationTypeOauth2) { _%>
121+
window.location.reload();
122+
<%_ } else { _%>
123+
openLogin();
124+
<%_ } _%>
125+
return;
126+
}
127+
}
128+
console.log('Unauthorized!');
129+
return Promise.reject(error);
130+
},
131+
error => {
132+
console.log('Server error!');
133+
return Promise.reject(error);
134+
}
135+
);
136+
97137
/* tslint:disable */
98138
<% if (!authenticationTypeOauth2) { %>const vue = <% } %>new Vue({
99139
el: '#app',
@@ -135,28 +175,6 @@ router.beforeEach(async (to, from, next) => {
135175
store,
136176
});
137177

138-
setupAxiosInterceptors(
139-
error => {
140-
const url = error.response?.config?.url;
141-
const status = error.status || error.response.status;
142-
if (status === 401) {
143-
// Store logged out state.
144-
store.commit('logout');
145-
if (!url.endsWith('api/account') && !url.endsWith('api/<% if (authenticationTypeSession) { %>authentication<% } else { %>authenticate<% } %>')) {
146-
// Ask for a new authentication
147-
<%_ if (authenticationTypeOauth2) { _%>
148-
window.location.reload();
149-
<%_ } else { _%>
150-
loginService.openLogin(vue);
178+
<%_ if (!authenticationTypeOauth2) { _%>
179+
openLogin = () => loginService.openLogin(vue);
151180
<%_ } _%>
152-
return;
153-
}
154-
}
155-
console.log('Unauthorized!');
156-
return Promise.reject(error);
157-
},
158-
error => {
159-
console.log('Server error!');
160-
return Promise.reject(error);
161-
}
162-
);

generators/vue/templates/src/main/webapp/app/shared/config/store/account-store.ts.ejs

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -4,14 +4,16 @@ export interface AccountStateStorable {
44
logon: boolean;
55
userIdentity: null | any;
66
authenticated: boolean;
7+
profilesLoaded: boolean;
78
ribbonOnProfiles: string;
89
activeProfiles: string;
9-
};
10+
}
1011

1112
export const defaultAccountState: AccountStateStorable = {
12-
logon: false,
13+
logon: null,
1314
userIdentity: null,
1415
authenticated: false,
16+
profilesLoaded: false,
1517
ribbonOnProfiles: '',
1618
activeProfiles: '',
1719
};
@@ -22,22 +24,26 @@ export const accountStore: Module<AccountStateStorable, any> = {
2224
logon: state => state.logon,
2325
account: state => state.userIdentity,
2426
authenticated: state => state.authenticated,
27+
profilesLoaded: state => state.profilesLoaded,
2528
activeProfiles: state => state.activeProfiles,
2629
ribbonOnProfiles: state => state.ribbonOnProfiles,
2730
},
2831
mutations: {
29-
authenticate(state) {
30-
state.logon = true;
32+
authenticate(state, promise) {
33+
state.logon = promise;
3134
},
3235
authenticated(state, identity) {
3336
state.userIdentity = identity;
3437
state.authenticated = true;
35-
state.logon = false;
38+
state.logon = null;
3639
},
3740
logout(state) {
3841
state.userIdentity = null;
3942
state.authenticated = false;
40-
state.logon = false;
43+
state.logon = null;
44+
},
45+
profilesLoaded(state) {
46+
state.profilesLoaded = true;
4147
},
4248
setActiveProfiles(state, profile) {
4349
state.activeProfiles = profile;

0 commit comments

Comments
 (0)