UNPKG

1.75 kBPlain TextView Raw
1import {TypeDecorator} from '@angular/core';
2import {makeDecorator} from '@angular/core/src/util/decorators';
3import {ComponentInstruction} from '@angular/router-deprecated';
4import {CanActivate} from '@angular/router-deprecated/src/lifecycle/lifecycle_annotations_impl';
5import {Meteor} from 'meteor/meteor';
6
7class InjectUserAnnotation {
8 constructor(public propName: string = 'user') {}
9}
10
11export function InjectUser(propName?: string): (cls: any) => any {
12 const annInstance = new InjectUserAnnotation(propName);
13 const TypeDecorator: TypeDecorator = <TypeDecorator>function TypeDecorator(cls) {
14 const propName = annInstance.propName;
15 const fieldName = `_${propName}`;
16 const injected = `${fieldName}Injected`;
17 Object.defineProperty(cls.prototype, propName, {
18 get: function() {
19 if (!this[injected]) {
20 this[fieldName] = Meteor.user();
21 if (this.autorun) {
22 this.autorun(() => {
23 this[fieldName] = Meteor.user();
24 }, true);
25 }
26 this[injected] = true;
27 }
28 return this[fieldName];
29 },
30 enumerable: true,
31 configurable: false
32 });
33 return cls;
34 };
35 return TypeDecorator;
36};
37
38/**
39 * Here CanActivate is an internal class (not present in the typings)
40 * defined at angular/modules/angular2/src/router/lifecycle_annotations_impl.ts.
41 * Each annotation designed to implement activation logic should extend it.
42 */
43class RequireUserAnnotation extends CanActivate {
44 constructor() {
45 super(this.canProceed.bind(this));
46 }
47
48 canProceed(prev: ComponentInstruction,
49 next: ComponentInstruction) {
50 return !!Meteor.user();
51 }
52}
53
54export const RequireUser = makeDecorator(RequireUserAnnotation);