// BROWSER TESTING SHIM
// Keep it in-sync with what karma-test-shim does
/*global jasmine, __karma__, window*/
(function () {

Error.stackTraceLimit = 0; // "No stacktrace"" is usually best for app testing.

// Uncomment to get full stacktrace output. Sometimes helpful, usually not.
// Error.stackTraceLimit = Infinity; //

jasmine.DEFAULT_TIMEOUT_INTERVAL = 3000;

var baseURL = document.baseURI;
baseURL = baseURL + baseURL[baseURL.length-1] ? '' : '/';

System.config({
  baseURL: baseURL,
  // Extend usual application package list with test folder
  packages: { 'testing': { main: 'index.js', defaultExtension: 'js' } },

  // Assume npm: is set in `paths` in systemjs.config
  // Map the angular testing umd bundles
  map: {
    '@angular/core/testing': 'npm:@angular/core/bundles/core-testing.umd.js',
    '@angular/common/testing': 'npm:@angular/common/bundles/common-testing.umd.js',
    '@angular/compiler/testing': 'npm:@angular/compiler/bundles/compiler-testing.umd.js',
    '@angular/platform-browser/testing': 'npm:@angular/platform-browser/bundles/platform-browser-testing.umd.js',
    '@angular/platform-browser-dynamic/testing': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic-testing.umd.js',
    '@angular/http/testing': 'npm:@angular/http/bundles/http-testing.umd.js',
    '@angular/router/testing': 'npm:@angular/router/bundles/router-testing.umd.js',
    '@angular/forms/testing': 'npm:@angular/forms/bundles/forms-testing.umd.js',
  },
});

System.import('systemjs.config.js')
  .then(importSystemJsExtras)
  .then(initTestBed)
  .then(initTesting);

/** Optional SystemJS configuration extras. Keep going w/o it */
function importSystemJsExtras(){
  return System.import('systemjs.config.extras.js')
  .catch(function(reason) {
    console.log(
      'Note: System.import could not load "systemjs.config.extras.js" where you might have added more configuration. It is an optional file so we will continue without it.'
    );
    console.log(reason);
  });
}

function initTestBed(){
  return Promise.all([
    System.import('@angular/core/testing'),
    System.import('@angular/platform-browser-dynamic/testing')
  ])

  .then(function (providers) {
    var coreTesting    = providers[0];
    var browserTesting = providers[1];

    coreTesting.TestBed.initTestEnvironment(
      browserTesting.BrowserDynamicTestingModule,
      browserTesting.platformBrowserDynamicTesting());
  })
}

// Import all spec files defined in the html (__spec_files__)
// and start Jasmine testrunner
function initTesting () {
  console.log('loading spec files: '+__spec_files__.join(', '));
  return Promise.all(
    __spec_files__.map(function(spec) {
      return System.import(spec);
    })
  )
  //  After all imports load,  re-execute `window.onload` which
  //  triggers the Jasmine test-runner start or explain what went wrong
  .then(success, console.error.bind(console));

  function success () {
    console.log('Spec files loaded; starting Jasmine testrunner');
    window.onload();
  }
}

})();


/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
/**
 * Web (plunker) version of systemjs.config.extras.js
 * It should default to `.ts` extensions rather than `.js` extensions in almost all cases.
 */
// (function (global) {
//   System.config({
//     packages: {
//       // add packages here
//     }
//   });
// })(this);


/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
<!-- Run application specs in a browser -->
<!DOCTYPE html>
<html>
<head>
  <script>document.write('<base href="' + document.location + '" />');</script>
  <title>1st Specs</title>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.css">
</head>
<body>
  <script src="https://unpkg.com/systemjs@0.19.39/dist/system.src.js"></script>

  <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/jasmine-html.js"></script>
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jasmine/2.4.1/boot.js"></script>

  <script src="https://unpkg.com/reflect-metadata@0.1.8"></script>

  <script src="https://unpkg.com/zone.js@0.7.4?main=browser"></script>
  <script src="https://unpkg.com/zone.js/dist/long-stack-trace-zone.js?main=browser"></script>
  <script src="https://unpkg.com/zone.js/dist/proxy.js?main=browser"></script>
  <script src="https://unpkg.com/zone.js/dist/sync-test.js?main=browser"></script>
  <script src="https://unpkg.com/zone.js/dist/jasmine-patch.js?main=browser"></script>
  <script src="https://unpkg.com/zone.js/dist/async-test.js?main=browser"></script>
  <script src="https://unpkg.com/zone.js/dist/fake-async-test.js?main=browser"></script>

  <script>
    var __spec_files__ = [
      'app/feature-flipping.service.spec'
    ];
  </script>
  <script src="browser-test-shim.js"></script>
</body>

</html>


<!-- 
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
-->
/**
 * WEB ANGULAR VERSION
 * (based on systemjs.config.js in angular.io)
 * System configuration for Angular samples
 * Adjust as necessary for your application needs.
 */
(function (global) {
  System.config({
    // DEMO ONLY! REAL CODE SHOULD NOT TRANSPILE IN THE BROWSER
    transpiler: 'ts',
    typescriptOptions: {
      // Copy of compiler options in standard tsconfig.json
      "target": "es5",
      "module": "commonjs",
      "moduleResolution": "node",
      "sourceMap": true,
      "emitDecoratorMetadata": true,
      "experimentalDecorators": true,
      "lib": ["es2015", "dom"],
      "noImplicitAny": true,
      "suppressImplicitAnyIndexErrors": true
    },
    meta: {
      'typescript': {
        "exports": "ts"
      }
    },
    paths: {
      // paths serve as alias
      'npm:': 'https://unpkg.com/'
    },
    // map tells the System loader where to look for things
    map: {
      // our app is within the app folder
      app: 'app',

      // angular bundles
      '@angular/core': 'npm:@angular/core/bundles/core.umd.js',
      '@angular/common': 'npm:@angular/common/bundles/common.umd.js',
      '@angular/compiler': 'npm:@angular/compiler/bundles/compiler.umd.js',
      '@angular/platform-browser': 'npm:@angular/platform-browser/bundles/platform-browser.umd.js',
      '@angular/platform-browser-dynamic': 'npm:@angular/platform-browser-dynamic/bundles/platform-browser-dynamic.umd.js',
      '@angular/http': 'npm:@angular/http/bundles/http.umd.js',
      '@angular/router': 'npm:@angular/router/bundles/router.umd.js',
      '@angular/router/upgrade': 'npm:@angular/router/bundles/router-upgrade.umd.js',
      '@angular/forms': 'npm:@angular/forms/bundles/forms.umd.js',
      '@angular/upgrade': 'npm:@angular/upgrade/bundles/upgrade.umd.js',
      '@angular/upgrade/static': 'npm:@angular/upgrade/bundles/upgrade-static.umd.js',

      // other libraries
      'rxjs':                      'npm:rxjs',
      'angular-in-memory-web-api': 'npm:angular-in-memory-web-api/bundles/in-memory-web-api.umd.js',
      'ts':                        'npm:plugin-typescript@5.2.7/lib/plugin.js',
      'typescript':                'npm:typescript@2.0.10/lib/typescript.js',
      'angularfire2':              'npm:angularfire2',
      'firebase':                  'npm:firebase@3.4.0',
      'lodash':                    'npm:lodash/lodash.js'

    },
    // packages tells the System loader how to load when no filename and/or no extension
    packages: {
      app: {
        main: './main.ts',
        defaultExtension: 'ts'
      },
      rxjs: {
        defaultExtension: 'js'
      },
      angularfire2: {
        main: 'angularfire2.js'
      },
      firebase: {
        main: 'firebase.js'
      }
    }
  });

  if (global.autoBootstrap) { bootstrap(); }

  // Bootstrap with a default `AppModule`
  // ignore an `app/app.module.ts` and `app/main.ts`, even if present
  // This function exists primarily (exclusively?) for the QuickStart
  function bootstrap() {
    console.log('Auto-bootstrapping');

    // Stub out `app/main.ts` so System.import('app') doesn't fail if called in the index.html
    System.set(System.normalizeSync('app/main.ts'), System.newModule({ }));

    // bootstrap and launch the app (equivalent to standard main.ts)
    Promise.all([
      System.import('@angular/platform-browser-dynamic')
    /* , getAppModule()*/
    ])
    .then(function (imports) {
      var platform = imports[0];
      var app      = imports[1];
      platform.platformBrowserDynamic().bootstrapModule(app.AppModule);
    })
    .catch(function(err){ console.error(err); });
  }

  // Make the default AppModule
  // returns a promise for the AppModule
  function getAppModule() {
    console.log('Making a bare-bones, default AppModule');

    return Promise.all([
      System.import('@angular/core'),
      System.import('@angular/platform-browser'),
      System.import('app/app.component'),
      System.import('app/club-member-renderer')
    ])
    .then(function (imports) {

      var core    = imports[0];
      var browser = imports[1];
      var appComp = imports[2].AppComponent;
      var ClubMemberRenderer = imports[3].ClubMemberRenderer; 
   
      
      console.log('HAHHA')
      
      
      var AppModule = function() {}

      AppModule.annotations = [
        new core.NgModule({
          imports:      [ browser.BrowserModule ],
          declarations: [ appComp],
          bootstrap:    [ appComp ]
        })
      ]
      return {AppModule: AppModule};
    })
  }
})(this);

/*
Copyright 2016 Google Inc. All Rights Reserved.
Use of this source code is governed by an MIT-style license that
can be found in the LICENSE file at http://angular.io/license
*/
import { Injectable } from '@angular/core';
import { Observable } from 'rxjs/Rx';
import { AngularFire } from 'angularfire2';
import * as _ from 'lodash';

@Injectable()
export class FeatureFlippingService {
    private auth$: AngularFireAuth;

    constructor(
        public af: AngularFire
    ) {
        this.auth$ = this.af.auth;
    }

    /**
     * Return `true` if user have access to the feature
     * 
     * Database:
     * ```
     * {
     *   features: {
     *     a: {all: true},
     *     b: {team: true, robert: true},
     *     c: {bob: true},
     *     d: {all: true, team: false}
     *   },
     *   users: {
     *     bob: {
     *       groups: {
     *         team: true
     *       }
     *     },
     *     robert: {}
     *   }
     * }
     * ```
     * 
     * For bob:
     * haveFeature('a') => true
     * haveFeature('b') => true
     * haveFeature('c') => true
     * haveFeature('d') => false
     * 
     * For robert:
     * haveFeature('a') => true
     * haveFeature('b') => true
     * haveFeature('c') => false
     * 
     */
    haveFeature(featureName: string): Observable<boolean> {
        const feature$ = this.af.database.object(`/features/${featureName}`);
        const groups$ = this.auth$.flatMap(auth => {
            if (auth) return this.af.database.object(`/users/${auth.uid}/groups`);
            return Observable.of({});
        });

        return Observable.combineLatest(
            feature$,
            this.auth$,
            groups$
        ).map(([feature, auth, groups]) => {
            const uid = _.get(auth, 'uid');
            const isOpenToEveryBody = _.get(feature, 'all', false);
            const isOpenToMe = _.get(feature, uid, false);

            const activeGroups = _(groups).pickBy(a => a === true).keys().value();
            const allowedGroups = _(feature).pickBy(a => a === true).keys().value();
            const disallowedGroups = _(feature).pickBy(a => a === false).keys().value();
            const isOpenToMyGroup = _.intersection(activeGroups, allowedGroups).length > 0;
            const isDisallowed = _.intersection(disallowedGroups, [uid].concat(activeGroups)).length > 0;

            if (isDisallowed) return false;
            return isOpenToEveryBody || isOpenToMe || isOpenToMyGroup;
        });
    }
}
import { FeatureFlippingService } from './feature-flipping.service';
import { Observable } from 'rxjs/Rx';

describe('featureFlipping service', () => {
  
  describe('with auth user', () => {
    let service;
    
    beforeEach(()=>{
      const afStub = {
        auth: Observable.of({uid: 'bob'}),
        database: {
          object: (key) => {
            return {
              '/features/a': Observable.of({all: true}),
              '/features/b': Observable.of({all: false, bob: true}),
              '/features/c': Observable.of({all: false, team: true}),
              '/features/d': Observable.of({all: true, team: false}),
              '/features/e': Observable.of({all: true, bob: false}),
              '/features/f': Observable.of({}),
              '/features/g': Observable.of({betaTester: true}),
              '/users/bob/groups': Observable.of({team: true})
            }[key];
          }
        }
      };
      service = new FeatureFlippingService(afStub);
    });
    
    it('should be allowed if all is true', done => {
      service.haveFeature('a').subscribe(val => {
        expect(val).toBeTruthy();
        done();
      });
    });
    
    it('should be allowed if team is true', done => {
      service.haveFeature('c').subscribe(val => {
        expect(val).toBeTruthy();
        done();
      });
    });
    
    it('should be allowed if bob is true', done => {
      service.haveFeature('b').subscribe(val => {
        expect(val).toBeTruthy();
        done();
      });
    });
    
    it('should be disallowed if bob is false', done => {
      service.haveFeature('e').subscribe(val => {
        expect(val).toBeFalsy();
        done();
      });
    });
    
    it('should be disallowed if team is false', done => {
      service.haveFeature('d').subscribe(val => {
        expect(val).toBeFalsy();
        done();
      });
    });
    
    it('should be disallowed if no feature defined', done => {
      service.haveFeature('f').subscribe(val => {
        expect(val).toBeFalsy();
        done();
      });
    });
    
    it('should be disallowed if bob is not on allowed team', done => {
      service.haveFeature('g').subscribe(val => {
        expect(val).toBeFalsy();
        done();
      });
    });
  });
  
  describe('with unauth user', () => {
    let service;
    
    beforeEach(()=>{
      const afStub = {
        auth: Observable.of(null),
        database: {
          object: (key) => {
            return {
              '/features/a': Observable.of({all: true}),
              '/features/b': Observable.of({all: false, bob: true}),
              '/features/c': Observable.of({all: false, team: true}),
              '/features/d': Observable.of({all: true, team: false}),
              '/features/e': Observable.of({all: true, bob: false}),
              '/features/f': Observable.of({}),
              '/features/g': Observable.of({betaTester: true}),
              '/users/bob/groups': Observable.of({team: true})
            }[key];
          }
        }
      };
      service = new FeatureFlippingService(afStub);
    });
    
    it('should be allowed if all is true', done => {
      service.haveFeature('a').subscribe(val => {
        expect(val).toBeTruthy();
        done();
      });
    });
    
    it('should be disallowed if all is false', done => {
      service.haveFeature('b').subscribe(val => {
        expect(val).toBeFalsy();
        done();
      });
    });
    
  });
  
});