检查角色时的无限循环.VueJS



有一个导航栏,根据用户的角色显示元素:

<b-navbar-toggle
right
class="jh-navbar-toggler d-lg-none"
href="javascript:void(0);"
data-toggle="collapse"
target="header-tabs"
aria-expanded="false"
aria-label="Toggle navigation">
<font-awesome-icon icon="bars"/>
</b-navbar-toggle>
<b-collapse is-nav id="header-tabs">
<b-navbar-nav class="ml-auto">
<b-nav-item-dropdown
right
id="pass-menu"
v-if="hasAnyAuthority('ROLE_USER') && authenticated"
:class="{'router-link-active': subIsActive('/pass')}"
active-class="active"
class="pointer">
<span slot="button-content" class="navbar-dropdown-menu">
<font-awesome-icon icon="ticket-alt"/>
<span>First element</span>
</span>
</b-nav-item-dropdown>
<b-nav-item-dropdown
right
id="dictionaries-menu"
v-if="hasAnyAuthority('ROLE_ADMIN') && authenticated"
:class="{'router-link-active': subIsActive('/dictionary')}"
active-class="active"
class="pointer">
<span slot="button-content" class="navbar-dropdown-menu">
<font-awesome-icon icon="book"/>
<span>Second element</span>
</span>
</b-nav-item-dropdown>
</b-navbar-nav>

如果我为两个元素设置相同的角色,例如ROLE_USER,那么一切都可以正常工作。但当两个元素的角色不同时,就会开始一个无限循环,一切都会冻结。

用于检查角色的组件:

@Component
export default class JhiNavbar extends Vue {
@Inject('loginService')
private loginService: () => LoginService;
@Inject('accountService') private accountService: () => AccountService;
public version = VERSION ? 'v' + VERSION : '';
private currentLanguage = this.$store.getters.currentLanguage;
private languages: any = this.$store.getters.languages;
private hasAnyAuthorityValue = false;
created() {}
public get authenticated(): boolean {
return this.$store.getters.authenticated;
}
public hasAnyAuthority(authorities: any): boolean {
this.accountService()
.hasAnyAuthorityAndCheckAuth(authorities)
.then(value => {
this.hasAnyAuthorityValue = value;
});
return this.hasAnyAuthorityValue;
}
}

使用用户帐户的服务:

export default class AccountService {
constructor(private store: Store<any>, private router: VueRouter) {
this.init();
}
public init(): void {
this.retrieveProfiles();
}
public retrieveProfiles(): void {
axios.get('management/info').then(res => {
if (res.data && res.data.activeProfiles) {
this.store.commit('setRibbonOnProfiles', res.data['display-ribbon-on-profiles']);
this.store.commit('setActiveProfiles', res.data['activeProfiles']);
}
});
}
public retrieveAccount(): Promise<boolean> {
return new Promise(resolve => {
axios
.get('api/account')
.then(response => {
this.store.commit('authenticate');
const account = response.data;
if (account) {
this.store.commit('authenticated', account);
if (sessionStorage.getItem('requested-url')) {
this.router.replace(sessionStorage.getItem('requested-url'));
sessionStorage.removeItem('requested-url');
}
} else {
this.store.commit('logout');
this.router.push('/');
sessionStorage.removeItem('requested-url');
}
resolve(true);
})
.catch(() => {
this.store.commit('logout');
resolve(false);
});
});
}
public hasAnyAuthorityAndCheckAuth(authorities: any): Promise<boolean> {
if (typeof authorities === 'string') {
authorities = [authorities];
}
if (!this.authenticated || !this.userAuthorities) {
const token = localStorage.getItem('jhi-authenticationToken') || sessionStorage.getItem('jhi-authenticationToken');
if (!this.store.getters.account && !this.store.getters.logon && token) {
return this.retrieveAccount();
} else {
return new Promise(resolve => {
resolve(false);
});
}
}
for (let i = 0; i < authorities.length; i++) {
if (this.userAuthorities.includes(authorities[i])) {
return new Promise(resolve => {
resolve(true);
});
}
}
return new Promise(resolve => {
resolve(false);
});
}
public get authenticated(): boolean {
return this.store.getters.authenticated;
}
public get userAuthorities(): any {
return this.store.getters.account.authorities;
}
}

有@bigliss:的解决方案

...
private hasAdminAuthorityValue = false;
private hasUserAuthorityValue = false;
...
public hasAdminAuthority(): boolean {
this.accountService()
.hasAnyAuthorityAndCheckAuth('ROLE_ADMIN')
.then(value => {
this.hasAdminAuthorityValue = value;
});
return this.hasAdminAuthorityValue;
}
public hasUserAuthority(): boolean {
this.accountService()
.hasAnyAuthorityAndCheckAuth('ROLE_USER')
.then(value => {
this.hasUserAuthorityValue = value;
});
return this.hasUserAuthorityValue;
}

这是由Vue的反应性引起的。您在v-if语句中使用异步方法,这通常是个坏主意。Vue监视该方法的所有反应依赖项,如果任何依赖项发生变化,它将再次评估该语句(这意味着再次调用该函数(。这是故事的一部分。

为什么只有当角色不同时才会发生这种情况。因为您使用了共享属性hasAnyAuthorityValue,它是上述方法的反应依赖项。

例如:它获得ROLE_USER的权限,立即返回hasAnyAuthorityValue(sync(,但稍后会获取并更新该值(async(。如果异步结果不改变(一个角色(,它可以工作,但当hasAnyAuthorityValue的值在role_USER和role_ADMIN异步结果之间切换时,它会被困在无休止的循环中。

有很多解决方案。f.e.在创建阶段将两个hasAnyAuthority(any)的结果保存为数据的属性值,或者为每个角色使用不同的属性名称,而不是共享一个。

最新更新