Add custom component-level property to Vue typescript components

Viewed 169

I am using vue-class-component (and vue-property-decorator) in my vue2 project. I would like to incorporate component-level security checking to each component as it is loaded. I envision a signature like this:


@Component
@Security('USERS_LIST')
export default class UserList extends Vue {
...
}

Internally, the parameter passed (USERS_LIST) is checked against some Vuex store, and on failure the user is notified or redirected using Vue-Router. I can handle all the wiring, but I'm a bit lost on how I can create a component-level decorator, or expand the existing @Component decorator on my own.

I feel like I could use a mixin to override a lifecycle method and check state for the security aspect. But how do I define the @Security decorator, and provide it a value per-component?

1 Answers

I've got the idea working using mixins. I'm not super happy with this solution, but it works for now. This implements a check called from the created lifecycle hook to verify permissions. On failure, it redirects to a 'permission denied' page.

This, of course, is only a SPA solution, and actual security is enforced at the API level.

securityVue.ts:

import Vue from 'vue';
import Component from 'vue-class-component';

@Component
export class SecurityVue extends Vue {
  protected requiredPermission: string = null;

  public created() {
    // Check that we have permission
    if (this.requiredPermission && !this.hasPermission(this.requiredPermission)) {
      this.$router.push({ path: '/Error/NoPermissions', params: { permission: this.requiredPermission }});
    }
  }

  private hasPermission(permission: string): boolean {
    return true;
  }

}

Each component:

export default class UserList extends mixins(SecurityVue) {
  protected requiredPermission: string = 'USER_LIST';
Related