├── .angular-cli.json ├── .editorconfig ├── .gitignore ├── .plunk ├── README.md ├── e2e ├── app.e2e-spec.ts ├── app.po.ts └── tsconfig.e2e.json ├── karma.conf.js ├── package-lock.json ├── package.json ├── protractor.conf.js ├── src ├── app │ ├── app-routing.module.ts │ ├── app.component.css │ ├── app.component.html │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── app.reducers.ts │ ├── core │ │ ├── models │ │ │ └── user.ts │ │ ├── services │ │ │ └── user.service.ts │ │ └── util.ts │ ├── not-found │ │ ├── not-found.component.html │ │ ├── not-found.component.scss │ │ ├── not-found.component.spec.ts │ │ └── not-found.component.ts │ ├── shared │ │ └── authenticated.guard.ts │ └── users │ │ ├── my-account │ │ ├── my-account.component.html │ │ ├── my-account.component.scss │ │ ├── my-account.component.spec.ts │ │ └── my-account.component.ts │ │ ├── sign-in │ │ ├── sign-in.component.html │ │ ├── sign-in.component.scss │ │ ├── sign-in.component.spec.ts │ │ └── sign-in.component.ts │ │ ├── sign-out │ │ ├── sign-out.component.html │ │ ├── sign-out.component.scss │ │ ├── sign-out.component.spec.ts │ │ └── sign-out.component.ts │ │ ├── sign-up │ │ ├── sign-up.component.html │ │ ├── sign-up.component.scss │ │ ├── sign-up.component.spec.ts │ │ └── sign-up.component.ts │ │ ├── users-routing.module.ts │ │ ├── users.actions.ts │ │ ├── users.effects.ts │ │ ├── users.module.ts │ │ └── users.reducers.ts ├── assets │ └── .gitkeep ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── sass │ └── _mixins.scss ├── styles.css ├── test.ts ├── tsconfig.app.json ├── tsconfig.spec.json └── typings.d.ts ├── tsconfig.json └── tslint.json /.angular-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "project": { 4 | "name": "reactive-authentication-example" 5 | }, 6 | "apps": [ 7 | { 8 | "root": "src", 9 | "outDir": "dist", 10 | "assets": [ 11 | "assets", 12 | "favicon.ico" 13 | ], 14 | "index": "index.html", 15 | "main": "main.ts", 16 | "polyfills": "polyfills.ts", 17 | "test": "test.ts", 18 | "tsconfig": "tsconfig.app.json", 19 | "testTsconfig": "tsconfig.spec.json", 20 | "prefix": "app", 21 | "styles": [ 22 | "styles.css" 23 | ], 24 | "scripts": [], 25 | "environmentSource": "environments/environment.ts", 26 | "environments": { 27 | "dev": "environments/environment.ts", 28 | "prod": "environments/environment.prod.ts" 29 | } 30 | } 31 | ], 32 | "e2e": { 33 | "protractor": { 34 | "config": "./protractor.conf.js" 35 | } 36 | }, 37 | "lint": [ 38 | { 39 | "project": "src/tsconfig.app.json" 40 | }, 41 | { 42 | "project": "src/tsconfig.spec.json" 43 | }, 44 | { 45 | "project": "e2e/tsconfig.e2e.json" 46 | } 47 | ], 48 | "test": { 49 | "karma": { 50 | "config": "./karma.conf.js" 51 | } 52 | }, 53 | "defaults": { 54 | "styleExt": "scss", 55 | "component": { 56 | "inlineStyle": false, 57 | "inlineTemplate": false 58 | } 59 | } 60 | } 61 | -------------------------------------------------------------------------------- /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see http://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | 8 | # dependencies 9 | /node_modules 10 | 11 | # IDEs and editors 12 | /.idea 13 | .project 14 | .classpath 15 | .c9/ 16 | *.launch 17 | .settings/ 18 | *.sublime-workspace 19 | 20 | # IDE - VSCode 21 | .vscode/* 22 | !.vscode/settings.json 23 | !.vscode/tasks.json 24 | !.vscode/launch.json 25 | !.vscode/extensions.json 26 | 27 | # misc 28 | /.sass-cache 29 | /connect.lock 30 | /coverage 31 | /libpeerconnection.log 32 | npm-debug.log 33 | testem.log 34 | /typings 35 | 36 | # e2e 37 | /e2e/*.js 38 | /e2e/*.map 39 | 40 | # System Files 41 | .DS_Store 42 | Thumbs.db 43 | -------------------------------------------------------------------------------- /.plunk: -------------------------------------------------------------------------------- 1 | {"name":"reactive-authentication-example"} -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # ReactiveAuthenticationExample 2 | 3 | This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 1.0.0. 4 | 5 | ## Install 6 | 7 | Run `npm install` to install necessary dependencies. 8 | 9 | ## Authentication 10 | 11 | You can sign into the demo app using the username `foo@test.com` and the password `password`. It's a highly secure app. :thumbsup: 12 | 13 | ## Development server 14 | 15 | Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The app will automatically reload if you change any of the source files. 16 | 17 | ## Code scaffolding 18 | 19 | Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive/pipe/service/class/module`. 20 | 21 | ## Build 22 | 23 | Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory. Use the `-prod` flag for a production build. 24 | 25 | ## Running unit tests 26 | 27 | Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io). 28 | 29 | ## Running end-to-end tests 30 | 31 | Run `ng e2e` to execute the end-to-end tests via [Protractor](http://www.protractortest.org/). 32 | Before running the tests make sure you are serving the app via `ng serve`. 33 | 34 | ## Further help 35 | 36 | To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI README](https://github.com/angular/angular-cli/blob/master/README.md). 37 | -------------------------------------------------------------------------------- /e2e/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { ReactiveAuthenticationExamplePage } from './app.po'; 2 | 3 | describe('reactive-authentication-example App', () => { 4 | let page: ReactiveAuthenticationExamplePage; 5 | 6 | beforeEach(() => { 7 | page = new ReactiveAuthenticationExamplePage(); 8 | }); 9 | 10 | it('should display message saying app works', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('app works!'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /e2e/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, element, by } from 'protractor'; 2 | 3 | export class ReactiveAuthenticationExamplePage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types":[ 8 | "jasmine", 9 | "node" 10 | ] 11 | } 12 | } 13 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/0.13/config/configuration-file.html 3 | 4 | module.exports = function (config) { 5 | config.set({ 6 | basePath: '', 7 | frameworks: ['jasmine', '@angular/cli'], 8 | plugins: [ 9 | require('karma-jasmine'), 10 | require('karma-chrome-launcher'), 11 | require('karma-jasmine-html-reporter'), 12 | require('karma-coverage-istanbul-reporter'), 13 | require('@angular/cli/plugins/karma') 14 | ], 15 | client:{ 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | files: [ 19 | { pattern: './src/test.ts', watched: false } 20 | ], 21 | preprocessors: { 22 | './src/test.ts': ['@angular/cli'] 23 | }, 24 | mime: { 25 | 'text/x-typescript': ['ts','tsx'] 26 | }, 27 | coverageIstanbulReporter: { 28 | reports: [ 'html', 'lcovonly' ], 29 | fixWebpackSourcePaths: true 30 | }, 31 | angularCli: { 32 | environment: 'dev' 33 | }, 34 | reporters: config.angularCli && config.angularCli.codeCoverage 35 | ? ['progress', 'coverage-istanbul'] 36 | : ['progress', 'kjhtml'], 37 | port: 9876, 38 | colors: true, 39 | logLevel: config.LOG_INFO, 40 | autoWatch: true, 41 | browsers: ['Chrome'], 42 | singleRun: false 43 | }); 44 | }; 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "reactive-authentication-example", 3 | "version": "0.0.0", 4 | "license": "MIT", 5 | "scripts": { 6 | "ng": "ng", 7 | "start": "ng serve", 8 | "build": "ng build", 9 | "test": "ng test", 10 | "lint": "ng lint", 11 | "e2e": "ng e2e" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/animations": "^4.2.4", 16 | "@angular/cdk": "^2.0.0-beta.12", 17 | "@angular/common": "^4.2.4", 18 | "@angular/compiler": "^4.2.4", 19 | "@angular/core": "^4.2.4", 20 | "@angular/flex-layout": "^2.0.0-beta.9", 21 | "@angular/forms": "^4.2.4", 22 | "@angular/http": "^4.2.4", 23 | "@angular/material": "^2.0.0-beta.11", 24 | "@angular/platform-browser": "^4.2.4", 25 | "@angular/platform-browser-dynamic": "^4.2.4", 26 | "@angular/router": "^4.2.4", 27 | "@ngrx/core": "^1.2.0", 28 | "@ngrx/effects": "^2.0.2", 29 | "@ngrx/router-store": "^1.2.5", 30 | "@ngrx/store": "^2.2.1", 31 | "core-js": "^2.4.1", 32 | "reselect": "^3.0.0", 33 | "rxjs": "^5.1.0", 34 | "zone.js": "^0.8.5" 35 | }, 36 | "devDependencies": { 37 | "@angular/cli": "^1.5.4", 38 | "@angular/compiler-cli": "^4.2.4", 39 | "@angular/language-service": "^4.2.4", 40 | "@types/jasmine": "2.5.38", 41 | "@types/node": "^6.0.60", 42 | "codelyzer": "^2.1.1", 43 | "jasmine-core": "^2.8.0", 44 | "jasmine-spec-reporter": "^3.3.0", 45 | "karma": "^1.7.1", 46 | "karma-chrome-launcher": "^2.2.0", 47 | "karma-cli": "^1.0.1", 48 | "karma-coverage-istanbul-reporter": "^0.2.0", 49 | "karma-jasmine": "^1.1.0", 50 | "karma-jasmine-html-reporter": "^0.2.2", 51 | "ngrx-store-freeze": "^0.1.9", 52 | "protractor": "^5.2.0", 53 | "ts-node": "^2.1.2", 54 | "tslint": "^4.5.0", 55 | "typescript": "^2.4.2" 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /protractor.conf.js: -------------------------------------------------------------------------------- 1 | // Protractor configuration file, see link for more information 2 | // https://github.com/angular/protractor/blob/master/lib/config.ts 3 | 4 | const { SpecReporter } = require('jasmine-spec-reporter'); 5 | 6 | exports.config = { 7 | allScriptsTimeout: 11000, 8 | specs: [ 9 | './e2e/**/*.e2e-spec.ts' 10 | ], 11 | capabilities: { 12 | 'browserName': 'chrome' 13 | }, 14 | directConnect: true, 15 | baseUrl: 'http://localhost:4200/', 16 | framework: 'jasmine', 17 | jasmineNodeOpts: { 18 | showColors: true, 19 | defaultTimeoutInterval: 30000, 20 | print: function() {} 21 | }, 22 | beforeLaunch: function() { 23 | require('ts-node').register({ 24 | project: 'e2e/tsconfig.e2e.json' 25 | }); 26 | }, 27 | onPrepare() { 28 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 29 | } 30 | }; 31 | -------------------------------------------------------------------------------- /src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from "@angular/core"; 2 | import { Routes, RouterModule } from "@angular/router"; 3 | 4 | // guards 5 | import { AuthenticatedGuard } from "./shared/authenticated.guard"; 6 | 7 | // components 8 | import { NotFoundComponent } from "./not-found/not-found.component"; 9 | 10 | 11 | const routes: Routes = [ 12 | { 13 | path: "users", 14 | loadChildren: "./users/users.module#UsersModule" 15 | }, 16 | { 17 | path: "", 18 | pathMatch: "full", 19 | redirectTo: "/users/my-account" 20 | }, 21 | { 22 | path: "404", 23 | component: NotFoundComponent 24 | }, 25 | { 26 | path: "**", 27 | redirectTo: "/404" 28 | } 29 | ]; 30 | 31 | @NgModule({ 32 | exports: [ 33 | RouterModule 34 | ], 35 | imports: [ 36 | RouterModule.forRoot(routes) 37 | ] 38 | }) 39 | export class AppRoutingModule { } 40 | -------------------------------------------------------------------------------- /src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blove/angular-reactive-authentication/e00e6c1fb310022b2469a0816e3eda0b99028410/src/app/app.component.css -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed, async } from "@angular/core/testing"; 2 | 3 | import { AppComponent } from "./app.component"; 4 | 5 | describe("AppComponent", () => { 6 | beforeEach(async(() => { 7 | TestBed.configureTestingModule({ 8 | declarations: [ 9 | AppComponent 10 | ], 11 | }).compileComponents(); 12 | })); 13 | 14 | it("should create the app", async(() => { 15 | const fixture = TestBed.createComponent(AppComponent); 16 | const app = fixture.debugElement.componentInstance; 17 | expect(app).toBeTruthy(); 18 | })); 19 | 20 | it(`should have as title "app works!"`, async(() => { 21 | const fixture = TestBed.createComponent(AppComponent); 22 | const app = fixture.debugElement.componentInstance; 23 | expect(app.title).toEqual("app works!"); 24 | })); 25 | 26 | it("should render title in a h1 tag", async(() => { 27 | const fixture = TestBed.createComponent(AppComponent); 28 | fixture.detectChanges(); 29 | const compiled = fixture.debugElement.nativeElement; 30 | expect(compiled.querySelector("h1").textContent).toContain("app works!"); 31 | })); 32 | }); 33 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from "@angular/core"; 2 | 3 | @Component({ 4 | selector: "app-root", 5 | templateUrl: "./app.component.html", 6 | styleUrls: ["./app.component.css"] 7 | }) 8 | export class AppComponent {} 9 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from "@angular/platform-browser"; 2 | import { BrowserAnimationsModule } from "@angular/platform-browser/animations"; 3 | import { NgModule } from "@angular/core"; 4 | 5 | 6 | // @ngrx 7 | import { EffectsModule } from "@ngrx/effects"; 8 | import { RouterStoreModule } from "@ngrx/router-store"; 9 | import { StoreModule } from "@ngrx/store"; 10 | 11 | // routing 12 | import { AppRoutingModule } from "./app-routing.module"; 13 | 14 | // components 15 | import { AppComponent } from "./app.component"; 16 | import { NotFoundComponent } from "./not-found/not-found.component"; 17 | 18 | // effects 19 | import { UserEffects } from "./users/users.effects"; 20 | 21 | // guards 22 | import { AuthenticatedGuard} from "./shared/authenticated.guard"; 23 | 24 | // reducers 25 | import { reducer } from "./app.reducers"; 26 | 27 | // services 28 | import { UserService } from "./core/services/user.service"; 29 | 30 | @NgModule({ 31 | declarations: [ 32 | AppComponent, 33 | NotFoundComponent 34 | ], 35 | imports: [ 36 | AppRoutingModule, 37 | BrowserModule, 38 | BrowserAnimationsModule, 39 | EffectsModule.run(UserEffects), 40 | RouterStoreModule.connectRouter(), 41 | StoreModule.provideStore(reducer, { 42 | router: window.location.pathname + window.location.search 43 | }) 44 | ], 45 | providers: [ 46 | AuthenticatedGuard, 47 | UserService, 48 | ], 49 | bootstrap: [AppComponent] 50 | }) 51 | export class AppModule { } 52 | -------------------------------------------------------------------------------- /src/app/app.reducers.ts: -------------------------------------------------------------------------------- 1 | // reselect 2 | import { createSelector } from "reselect"; 3 | 4 | // @ngrx 5 | import { ActionReducer, combineReducers } from "@ngrx/store"; 6 | import { compose } from "@ngrx/core/compose"; 7 | import { routerReducer, RouterState } from "@ngrx/router-store"; 8 | import { storeFreeze } from "ngrx-store-freeze"; 9 | 10 | // environment 11 | import { environment } from "../environments/environment"; 12 | 13 | /** 14 | * Every reducer module"s default export is the reducer function itself. In 15 | * addition, each module should export a type or interface that describes 16 | * the state of the reducer plus any selector functions. The `* as` 17 | * notation packages up all of the exports into a single object. 18 | */ 19 | import * as users from "./users/users.reducers"; 20 | 21 | /** 22 | * We treat each reducer like a table in a database. 23 | * This means our top level state interface is just a map of keys to inner state types. 24 | */ 25 | export interface State { 26 | router: RouterState; 27 | users: users.State; 28 | } 29 | 30 | /** 31 | * Because metareducers take a reducer function and return a new reducer, 32 | * we can use our compose helper to chain them together. Here we are 33 | * using combineReducers to make our top level reducer, and then 34 | * wrapping that in storeLogger. Remember that compose applies 35 | * the result from right to left. 36 | */ 37 | const reducers = { 38 | router: routerReducer, 39 | users: users.reducer 40 | }; 41 | 42 | // development reducer includes storeFreeze to prevent state from being mutated 43 | const developmentReducer: ActionReducer = compose(storeFreeze, combineReducers)(reducers); 44 | 45 | // production reducer 46 | const productionReducer: ActionReducer = combineReducers(reducers); 47 | 48 | /** 49 | * The single reducer function. 50 | * @function reducer 51 | * @param {any} state 52 | * @param {any} action 53 | */ 54 | export function reducer(state: any, action: any) { 55 | if (environment.production) { 56 | return productionReducer(state, action); 57 | } else { 58 | return developmentReducer(state, action); 59 | } 60 | } 61 | 62 | /********************************************************** 63 | * Users Reducers 64 | *********************************************************/ 65 | 66 | /** 67 | * Returns the user state. 68 | * @function getUserState 69 | * @param {State} state Top level state. 70 | * @return {State} 71 | */ 72 | export const getUsersState = (state: State) => state.users; 73 | 74 | /** 75 | * Returns the authenticated user 76 | * @function getAuthenticatedUser 77 | * @param {State} state 78 | * @param {any} props 79 | * @return {User} 80 | */ 81 | export const getAuthenticatedUser = createSelector(getUsersState, users.getAuthenticatedUser); 82 | 83 | /** 84 | * Returns the authentication error. 85 | * @function getAuthenticationError 86 | * @param {State} state 87 | * @param {any} props 88 | * @return {Error} 89 | */ 90 | export const getAuthenticationError = createSelector(getUsersState, users.getAuthenticationError); 91 | 92 | /** 93 | * Returns true if the user is authenticated 94 | * @function isAuthenticated 95 | * @param {State} state 96 | * @param {any} props 97 | * @return {boolean} 98 | */ 99 | export const isAuthenticated = createSelector(getUsersState, users.isAuthenticated); 100 | 101 | /** 102 | * Returns true if the user is authenticated 103 | * @function isAuthenticated 104 | * @param {State} state 105 | * @param {any} props 106 | * @return {boolean} 107 | */ 108 | export const isAuthenticatedLoaded = createSelector(getUsersState, users.isAuthenticatedLoaded); 109 | 110 | /** 111 | * Returns true if the authentication request is loading. 112 | * @function isAuthenticationLoading 113 | * @param {State} state 114 | * @param {any} props 115 | * @return {boolean} 116 | */ 117 | export const isAuthenticationLoading = createSelector(getUsersState, users.isLoading); 118 | 119 | /** 120 | * Returns the sign out error. 121 | * @function getSignOutError 122 | * @param {State} state 123 | * @param {any} props 124 | * @return {Error} 125 | */ 126 | export const getSignOutError = createSelector(getUsersState, users.getSignOutError); 127 | 128 | /** 129 | * Returns the sign up error. 130 | * @function getSignUpError 131 | * @param {State} state 132 | * @param {any} props 133 | * @return {Error} 134 | */ 135 | export const getSignUpError = createSelector(getUsersState, users.getSignUpError); 136 | -------------------------------------------------------------------------------- /src/app/core/models/user.ts: -------------------------------------------------------------------------------- 1 | export class User { 2 | _id?: string; 3 | email?: string; 4 | firstName?: string; 5 | lastName?: string; 6 | password?: string; 7 | } 8 | -------------------------------------------------------------------------------- /src/app/core/services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from "@angular/core"; 2 | import { Observable } from "rxjs/Observable"; 3 | import "rxjs/add/observable/of"; 4 | import "rxjs/add/observable/throw"; 5 | import { User } from "../models/user"; 6 | 7 | export const MOCK_USER = new User(); 8 | MOCK_USER._id = "1"; 9 | MOCK_USER.email = "foo@test.com"; 10 | MOCK_USER.firstName = "Foo"; 11 | MOCK_USER.lastName = "Bar"; 12 | MOCK_USER.password = "password"; 13 | 14 | /** 15 | * The user service. 16 | */ 17 | @Injectable() 18 | export class UserService { 19 | 20 | /** 21 | * True if authenticated 22 | * @type 23 | */ 24 | private _authenticated = false; 25 | 26 | /** 27 | * Authenticate the user 28 | * 29 | * @param {string} email The user's email address 30 | * @param {string} password The user's password 31 | * @returns {Observable} The authenticated user observable. 32 | */ 33 | public authenticate(email: string, password: string): Observable { 34 | // Normally you would do an HTTP request to determine to 35 | // attempt authenticating the user using the supplied credentials. 36 | 37 | if (email === MOCK_USER.email && password === MOCK_USER.password) { 38 | this._authenticated = true; 39 | return Observable.of(MOCK_USER); 40 | } 41 | 42 | return Observable.throw(new Error("Invalid email or password")); 43 | } 44 | 45 | /** 46 | * Determines if the user is authenticated 47 | * @returns {Observable} 48 | */ 49 | public authenticated(): Observable { 50 | return Observable.of(this._authenticated); 51 | } 52 | 53 | /** 54 | * Returns the authenticated user 55 | * @returns {User} 56 | */ 57 | public authenticatedUser(): Observable { 58 | // Normally you would do an HTTP request to determine if 59 | // the user has an existing auth session on the server 60 | // but, let's just return the mock user for this example. 61 | return Observable.of(MOCK_USER); 62 | } 63 | 64 | /** 65 | * Create a new user 66 | * @returns {User} 67 | */ 68 | public create(user: User): Observable { 69 | // Normally you would do an HTTP request to POST the user 70 | // details and then return the new user object 71 | // but, let's just return the new user for this example. 72 | this._authenticated = true; 73 | return Observable.of(user); 74 | } 75 | 76 | /** 77 | * End session 78 | * @returns {Observable} 79 | */ 80 | public signout(): Observable { 81 | // Normally you would do an HTTP request sign end the session 82 | // but, let's just return an observable of true. 83 | this._authenticated = false; 84 | return Observable.of(true); 85 | } 86 | } 87 | -------------------------------------------------------------------------------- /src/app/core/util.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This function coerces a string into a string literal type. 3 | * Using tagged union types in TypeScript 2.0, this enables 4 | * powerful typechecking of our reducers. 5 | * 6 | * Since every action label passes through this function it 7 | * is a good place to ensure all of our action labels 8 | * are unique. 9 | */ 10 | 11 | const typeCache: { [label: string]: boolean } = {}; 12 | export function type(label: T | ""): T { 13 | if (typeCache[label]) { 14 | throw new Error(`Action type "${label}" is not unique"`); 15 | } 16 | 17 | typeCache[label] = true; 18 | 19 | return label; 20 | } 21 | -------------------------------------------------------------------------------- /src/app/not-found/not-found.component.html: -------------------------------------------------------------------------------- 1 | 404: Not Found -------------------------------------------------------------------------------- /src/app/not-found/not-found.component.scss: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blove/angular-reactive-authentication/e00e6c1fb310022b2469a0816e3eda0b99028410/src/app/not-found/not-found.component.scss -------------------------------------------------------------------------------- /src/app/not-found/not-found.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { async, ComponentFixture, TestBed } from "@angular/core/testing"; 2 | 3 | import { NotFoundComponent } from "./not-found.component"; 4 | 5 | describe("NotFoundComponent", () => { 6 | let component: NotFoundComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async(() => { 10 | TestBed.configureTestingModule({ 11 | declarations: [ NotFoundComponent ] 12 | }) 13 | .compileComponents(); 14 | })); 15 | 16 | beforeEach(() => { 17 | fixture = TestBed.createComponent(NotFoundComponent); 18 | component = fixture.componentInstance; 19 | fixture.detectChanges(); 20 | }); 21 | 22 | it("should create", () => { 23 | expect(component).toBeTruthy(); 24 | }); 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/not-found/not-found.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from "@angular/core"; 2 | 3 | @Component({ 4 | selector: "app-not-found", 5 | templateUrl: "./not-found.component.html", 6 | styleUrls: ["./not-found.component.scss"] 7 | }) 8 | export class NotFoundComponent { 9 | 10 | constructor() { } 11 | 12 | } 13 | -------------------------------------------------------------------------------- /src/app/shared/authenticated.guard.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from "@angular/core"; 2 | import { ActivatedRouteSnapshot, CanActivate, CanLoad, Route, RouterStateSnapshot } from "@angular/router"; 3 | 4 | // import rxjs 5 | import { Observable } from "rxjs/Observable"; 6 | 7 | // import @ngrx 8 | import { Store } from "@ngrx/store"; 9 | import { go } from "@ngrx/router-store"; 10 | 11 | // reducers 12 | import { 13 | isAuthenticated, 14 | State 15 | } from "../app.reducers"; 16 | 17 | /** 18 | * Prevent unauthorized activating and loading of routes 19 | * @class AuthenticatedGuard 20 | */ 21 | @Injectable() 22 | export class AuthenticatedGuard implements CanActivate, CanLoad { 23 | 24 | /** 25 | * @constructor 26 | */ 27 | constructor(private store: Store) {} 28 | 29 | /** 30 | * True when user is authenticated 31 | * @method canActivate 32 | */ 33 | canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable | boolean { 34 | // get observable 35 | const observable = this.store.select(isAuthenticated); 36 | 37 | // redirect to sign in page if user is not authenticated 38 | observable.subscribe(authenticated => { 39 | if (!authenticated) { 40 | this.store.dispatch(go("/users/sign-in")); 41 | } 42 | }); 43 | 44 | return observable; 45 | } 46 | 47 | /** 48 | * True when user is authenticated 49 | * @method canLoad 50 | */ 51 | canLoad(route: Route): Observable | Promise | boolean { 52 | // get observable 53 | const observable = this.store.select(isAuthenticated); 54 | 55 | // redirect to sign in page if user is not authenticated 56 | observable.subscribe(authenticated => { 57 | if (!authenticated) { 58 | this.store.dispatch(go("/users/sign-in")); 59 | } 60 | }); 61 | 62 | return observable; 63 | } 64 | } 65 | -------------------------------------------------------------------------------- /src/app/users/my-account/my-account.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | person 9 | 10 | 11 | 12 | more_vert 13 | 14 | 15 | Sign Out 16 | 17 | 18 | 19 | Hello, {{ (user | async).firstName }} 20 | 21 | 22 | 23 | 24 | -------------------------------------------------------------------------------- /src/app/users/my-account/my-account.component.scss: -------------------------------------------------------------------------------- 1 | @import "~@angular/material/theming"; 2 | @import "~@angular/material/theming"; 3 | @import "../../../sass/mixins"; 4 | 5 | :host { 6 | .flex-container { 7 | background-color: mat-color($mat-grey, 100); 8 | position: relative; 9 | top: 0; 10 | left: 0; 11 | right: 0; 12 | min-height: 100vh; 13 | 14 | &::after { 15 | position: absolute; 16 | top: 0; 17 | width: 100%; 18 | height: 200px; 19 | left: 0; 20 | right: 0; 21 | background-color: mat-color($mat-indigo, 500); 22 | content: ""; 23 | box-shadow: 0 2px 4px 1px rgba(0,0,0,.14); 24 | z-index: 0; 25 | } 26 | 27 | .card-container { 28 | z-index: 1; 29 | 30 | mat-card { 31 | margin-top: 88px; 32 | 33 | mat-card-title { 34 | margin-top: -70px; 35 | position: relative; 36 | 37 | .avatar-wrapper { 38 | background: #fff; 39 | border-radius: 50%; 40 | box-shadow: 0 2px 4px 1px rgba(0, 0, 0, 0.14); 41 | height: 140px; 42 | width: 140px; 43 | 44 | mat-icon { 45 | font-size: 100px; 46 | height: 100px; 47 | width: 100px; 48 | color: mat-color($mat-deep-purple, 100); 49 | } 50 | } 51 | 52 | .menu-button { 53 | position: absolute; 54 | top: 56px; 55 | right: -12px; 56 | } 57 | } 58 | 59 | mat-card-content { 60 | text-align: center; 61 | 62 | mat-slide-toggle { 63 | margin: 0 auto; 64 | } 65 | } 66 | } 67 | } 68 | } 69 | } 70 | -------------------------------------------------------------------------------- /src/app/users/my-account/my-account.component.spec.ts: -------------------------------------------------------------------------------- 1 | /* tslint:disable:no-unused-variable */ 2 | import { CUSTOM_ELEMENTS_SCHEMA } from "@angular/core"; 3 | import { async, ComponentFixture, TestBed } from "@angular/core/testing"; 4 | import { StoreModule } from "@ngrx/store"; 5 | 6 | // reducers 7 | import { reducer } from "../../app.reducers"; 8 | 9 | // services 10 | import { UserService } from "../../core/services/user.service"; 11 | 12 | // this component to test 13 | import { MyAccountComponent } from "./my-account.component"; 14 | 15 | describe("MyAccountComponent", () => { 16 | 17 | let component: MyAccountComponent; 18 | let fixture: ComponentFixture; 19 | 20 | beforeEach(async(() => { 21 | // refine the test module by declaring the test component 22 | TestBed.configureTestingModule({ 23 | imports: [ 24 | StoreModule.provideStore(reducer) 25 | ], 26 | declarations: [ 27 | MyAccountComponent 28 | ], 29 | schemas: [ 30 | CUSTOM_ELEMENTS_SCHEMA 31 | ] 32 | }) 33 | .compileComponents(); 34 | 35 | // create component and test fixture 36 | fixture = TestBed.createComponent(MyAccountComponent); 37 | 38 | // get test component from the fixture 39 | component = fixture.componentInstance; 40 | })); 41 | 42 | it("should create an instance", () => { 43 | expect(component).toBeTruthy(); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /src/app/users/my-account/my-account.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from "@angular/core"; 2 | 3 | // @ngrx 4 | import { Store } from "@ngrx/store"; 5 | import { go } from "@ngrx/router-store"; 6 | 7 | // rxjs 8 | import { Observable } from "rxjs/Observable"; 9 | 10 | // reducers 11 | import { 12 | getAuthenticatedUser, 13 | State 14 | } from "../../app.reducers"; 15 | 16 | // models 17 | import { User } from "../../core/models/user"; 18 | 19 | /** 20 | * The user"s account. 21 | * @class MyAccountComponent 22 | */ 23 | @Component({ 24 | selector: "app-my-account", 25 | templateUrl: "./my-account.component.html", 26 | styleUrls: ["./my-account.component.scss"] 27 | }) 28 | export class MyAccountComponent implements OnInit { 29 | 30 | // the authenticated user 31 | public user: Observable; 32 | 33 | /** 34 | * @constructor 35 | */ 36 | constructor(private store: Store) { } 37 | 38 | /** 39 | * Lifecycle hook that is called after data-bound properties of a directive are initialized. 40 | * @method ngOnInit 41 | */ 42 | public ngOnInit() { 43 | // get authenticated user 44 | this.user = this.store.select(getAuthenticatedUser); 45 | } 46 | 47 | /** 48 | * Go to the home page. 49 | * @method home 50 | */ 51 | public home() { 52 | this.store.dispatch(go("/")); 53 | } 54 | 55 | /** 56 | * Sign out. 57 | * @method home 58 | */ 59 | public signOut() { 60 | this.store.dispatch(go("/users/sign-out")); 61 | } 62 | 63 | } 64 | -------------------------------------------------------------------------------- /src/app/users/sign-in/sign-in.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Sign In 9 | 10 | {{ error | async }} 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | Sign In 20 | Sign Up with Email 21 | 22 | 23 | 24 | 25 | 26 | 27 | 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /src/app/users/sign-in/sign-in.component.scss: -------------------------------------------------------------------------------- 1 | @import "~@angular/material/theming"; 2 | @import "~@angular/material/theming"; 3 | @import "../../../sass/mixins"; 4 | 5 | :host { 6 | .flex-container { 7 | background-color: mat-color($mat-grey, 100); 8 | position: relative; 9 | top: 0; 10 | left: 0; 11 | right: 0; 12 | min-height: 100vh; 13 | 14 | &::after { 15 | position: absolute; 16 | top: 0; 17 | width: 100%; 18 | height: 200px; 19 | left: 0; 20 | right: 0; 21 | background-color: mat-color($mat-indigo, 500); 22 | content: ""; 23 | box-shadow: 0 2px 4px 1px rgba(0,0,0,.14); 24 | z-index: 0; 25 | } 26 | 27 | .logo-container, .card-container { 28 | z-index: 1; 29 | } 30 | 31 | button.logo-container { 32 | background: transparent; 33 | padding: 0 16px; 34 | box-sizing: border-box; 35 | cursor: pointer; 36 | user-select: none; 37 | outline: 0; 38 | border: none; 39 | display: inline-block; 40 | white-space: nowrap; 41 | text-decoration: none; 42 | vertical-align: baseline; 43 | 44 | .logo { 45 | height: 64px; 46 | width: 64px; 47 | margin: 48px auto; 48 | background: url("http://placehold.it/64x64") contain; 49 | @include retina { 50 | background: url("http://placehold.it/128x128") 64px/64px; 51 | } 52 | } 53 | } 54 | 55 | .card-container { 56 | mat-card { 57 | background-color: #fff; 58 | margin-bottom: 16px; 59 | 60 | mat-card-title { 61 | text-transform: uppercase; 62 | text-align: center; 63 | margin-bottom: 48px; 64 | } 65 | 66 | mat-card-content { 67 | margin-bottom: 16px; 68 | 69 | mat-form-field { 70 | margin-bottom: 16px; 71 | } 72 | 73 | button, a { 74 | margin-top: 16px; 75 | } 76 | } 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/app/users/sign-in/sign-in.component.spec.ts: -------------------------------------------------------------------------------- 1 | /* tslint:disable:no-unused-variable */ 2 | import { CUSTOM_ELEMENTS_SCHEMA, DebugElement } from "@angular/core"; 3 | import { ComponentFixture, TestBed, async } from "@angular/core/testing"; 4 | import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule } from "@angular/forms"; 5 | import { MaterialModule } from "@angular/material"; 6 | import { By } from "@angular/platform-browser"; 7 | import { Store, StoreModule } from "@ngrx/store"; 8 | import { go } from "@ngrx/router-store"; 9 | 10 | // reducers 11 | import { reducer } from "../../app.reducers"; 12 | 13 | // models 14 | import { User } from "../../core/models/user"; 15 | 16 | // services 17 | import { MOCK_USER } from "../../core/services/user.service"; 18 | 19 | // this component to test 20 | import { SignInComponent } from "./sign-in.component"; 21 | 22 | describe("SignInComponent", () => { 23 | 24 | let component: SignInComponent; 25 | let fixture: ComponentFixture; 26 | let page: Page; 27 | let user: User = new User(); 28 | 29 | beforeEach(() => { 30 | user = MOCK_USER; 31 | }); 32 | 33 | beforeEach(async(() => { 34 | // refine the test module by declaring the test component 35 | TestBed.configureTestingModule({ 36 | imports: [ 37 | FormsModule, 38 | MaterialModule, 39 | ReactiveFormsModule, 40 | StoreModule.provideStore(reducer) 41 | ], 42 | declarations: [ 43 | SignInComponent 44 | ], 45 | schemas: [ 46 | CUSTOM_ELEMENTS_SCHEMA 47 | ] 48 | }) 49 | .compileComponents(); 50 | 51 | // create component and test fixture 52 | fixture = TestBed.createComponent(SignInComponent); 53 | 54 | // get test component from the fixture 55 | component = fixture.componentInstance; 56 | })); 57 | 58 | beforeEach(() => { 59 | // create page 60 | page = new Page(component, fixture); 61 | 62 | // verify the fixture is stable (no pending tasks) 63 | fixture.whenStable().then(() => { 64 | page.addPageElements(); 65 | }); 66 | }); 67 | 68 | it("should create a FormGroup comprised of FormControls", () => { 69 | fixture.detectChanges(); 70 | expect(component.form instanceof FormGroup).toBe(true); 71 | }); 72 | 73 | it("should authenticate", () => { 74 | fixture.detectChanges(); 75 | 76 | // set FormControl values 77 | component.form.controls["email"].setValue(user.email); 78 | component.form.controls["password"].setValue(user.password); 79 | 80 | // submit form 81 | component.submit(); 82 | 83 | // verify Store.dispatch() is invoked 84 | expect(page.navigateSpy.calls.any()).toBe(true, "Store.dispatch not invoked"); 85 | }); 86 | }); 87 | 88 | /** 89 | * I represent the DOM elements and attach spies. 90 | * 91 | * @class Page 92 | */ 93 | class Page { 94 | 95 | public emailInput: HTMLInputElement; 96 | public navigateSpy: jasmine.Spy; 97 | public passwordInput: HTMLInputElement; 98 | 99 | constructor(private component: SignInComponent, private fixture: ComponentFixture) { 100 | // use injector to get services 101 | const injector = fixture.debugElement.injector; 102 | const store = injector.get(Store); 103 | 104 | // add spies 105 | this.navigateSpy = spyOn(store, "dispatch"); 106 | } 107 | 108 | public addPageElements() { 109 | const emailInputSelector = "input[formcontrolname=\"email\"]"; 110 | // console.log(this.fixture.debugElement.query(By.css(emailInputSelector))); 111 | this.emailInput = this.fixture.debugElement.query(By.css(emailInputSelector)).nativeElement; 112 | 113 | const passwordInputSelector = "input[formcontrolname=\"password\"]"; 114 | this.passwordInput = this.fixture.debugElement.query(By.css(passwordInputSelector)).nativeElement; 115 | } 116 | } 117 | -------------------------------------------------------------------------------- /src/app/users/sign-in/sign-in.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnDestroy, OnInit } from "@angular/core"; 2 | import { FormBuilder, FormGroup, Validators } from "@angular/forms"; 3 | 4 | // @ngrx 5 | import { Store } from "@ngrx/store"; 6 | import { go } from "@ngrx/router-store"; 7 | 8 | // rxjs 9 | import { Observable } from "rxjs/Observable"; 10 | import "rxjs/add/operator/filter"; 11 | import "rxjs/add/operator/takeWhile"; 12 | 13 | // actions 14 | import { AuthenticateAction } from "../users.actions"; 15 | 16 | // reducers 17 | import { 18 | getAuthenticationError, 19 | isAuthenticated, 20 | isAuthenticationLoading, 21 | State 22 | } from "../../app.reducers"; 23 | 24 | /** 25 | * /users/sign-in 26 | * @class SignInComponent 27 | */ 28 | @Component({ 29 | templateUrl: "./sign-in.component.html", 30 | styleUrls: ["./sign-in.component.scss"] 31 | }) 32 | export class SignInComponent implements OnDestroy, OnInit { 33 | 34 | /** 35 | * The error if authentication fails. 36 | * @type {Observable} 37 | */ 38 | public error: Observable; 39 | 40 | /** 41 | * True if the authentication is loading. 42 | * @type {boolean} 43 | */ 44 | public loading: Observable; 45 | 46 | /** 47 | * The authentication form. 48 | * @type {FormGroup} 49 | */ 50 | public form: FormGroup; 51 | 52 | /** 53 | * Component state. 54 | * @type {boolean} 55 | */ 56 | private alive = true; 57 | 58 | /** 59 | * @constructor 60 | * @param {FormBuilder} formBuilder 61 | * @param {Store} store 62 | */ 63 | constructor( 64 | private formBuilder: FormBuilder, 65 | private store: Store 66 | ) { } 67 | 68 | /** 69 | * Lifecycle hook that is called after data-bound properties of a directive are initialized. 70 | * @method ngOnInit 71 | */ 72 | public ngOnInit() { 73 | // set formGroup 74 | this.form = this.formBuilder.group({ 75 | email: ["", Validators.required], 76 | password: ["", Validators.required] 77 | }); 78 | 79 | // set error 80 | this.error = this.store.select(getAuthenticationError); 81 | 82 | // set loading 83 | this.loading = this.store.select(isAuthenticationLoading); 84 | 85 | // subscribe to success 86 | this.store.select(isAuthenticated) 87 | .takeWhile(() => this.alive) 88 | .filter(authenticated => authenticated) 89 | .subscribe(value => { 90 | this.store.dispatch(go("/users/my-account")); 91 | }); 92 | } 93 | 94 | /** 95 | * Lifecycle hook that is called when a directive, pipe or service is destroyed. 96 | * @method ngOnDestroy 97 | */ 98 | public ngOnDestroy() { 99 | this.alive = false; 100 | } 101 | 102 | /** 103 | * Go to the home page. 104 | * @method home 105 | */ 106 | public home() { 107 | this.store.dispatch(go("/")); 108 | } 109 | 110 | /** 111 | * To to the sign up page. 112 | * @method signUp 113 | */ 114 | public signUp() { 115 | this.store.dispatch(go("/users/sign-up")); 116 | } 117 | 118 | /** 119 | * Submit the authentication form. 120 | * @method submit 121 | */ 122 | public submit() { 123 | // get email and password values 124 | const email: string = this.form.get("email").value; 125 | const password: string = this.form.get("password").value; 126 | 127 | // trim values 128 | email.trim(); 129 | password.trim(); 130 | 131 | // set payload 132 | const payload = { 133 | email: email, 134 | password: password 135 | }; 136 | 137 | // dispatch AuthenticationAction and pass in payload 138 | this.store.dispatch(new AuthenticateAction(payload)); 139 | } 140 | } 141 | -------------------------------------------------------------------------------- /src/app/users/sign-out/sign-out.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Signed Out 9 | 10 | 11 | You have been successfully signed out. 12 | Sign In 13 | 14 | 15 | 16 | 17 | 18 | -------------------------------------------------------------------------------- /src/app/users/sign-out/sign-out.component.scss: -------------------------------------------------------------------------------- 1 | @import "~@angular/material/theming"; 2 | @import "~@angular/material/theming"; 3 | @import "../../../sass/mixins"; 4 | 5 | :host { 6 | .flex-container { 7 | background-color: mat-color($mat-grey, 100); 8 | position: relative; 9 | top: 0; 10 | left: 0; 11 | right: 0; 12 | min-height: 100vh; 13 | 14 | &::after { 15 | position: absolute; 16 | top: 0; 17 | width: 100%; 18 | height: 200px; 19 | left: 0; 20 | right: 0; 21 | background-color: mat-color($mat-indigo, 500); 22 | content: ""; 23 | box-shadow: 0 2px 4px 1px rgba(0,0,0,.14); 24 | z-index: 0; 25 | } 26 | 27 | .logo-container, .card-container { 28 | z-index: 1; 29 | } 30 | 31 | button.logo-container { 32 | background: transparent; 33 | padding: 0 16px; 34 | box-sizing: border-box; 35 | cursor: pointer; 36 | user-select: none; 37 | outline: 0; 38 | border: none; 39 | display: inline-block; 40 | white-space: nowrap; 41 | text-decoration: none; 42 | vertical-align: baseline; 43 | 44 | .logo { 45 | height: 64px; 46 | width: 64px; 47 | margin: 48px auto; 48 | background: url("http://placehold.it/64x64") contain; 49 | @include retina { 50 | background: url("http://placehold.it/128x128") 64px/64px; 51 | } 52 | } 53 | } 54 | 55 | .card-container { 56 | mat-card { 57 | background-color: #fff; 58 | margin-bottom: 16px; 59 | 60 | mat-card-title { 61 | text-transform: uppercase; 62 | text-align: center; 63 | margin-bottom: 48px; 64 | } 65 | 66 | mat-card-content { 67 | margin-bottom: 16px; 68 | 69 | mat-form-field { 70 | margin-bottom: 16px; 71 | } 72 | 73 | button, a { 74 | margin-top: 16px; 75 | } 76 | } 77 | } 78 | } 79 | } 80 | } 81 | -------------------------------------------------------------------------------- /src/app/users/sign-out/sign-out.component.spec.ts: -------------------------------------------------------------------------------- 1 | /* tslint:disable:no-unused-variable */ 2 | import { DebugElement, CUSTOM_ELEMENTS_SCHEMA } from "@angular/core"; 3 | import { async, ComponentFixture, TestBed } from "@angular/core/testing"; 4 | import { By } from "@angular/platform-browser"; 5 | import { Router } from "@angular/router"; 6 | 7 | // import ngrx 8 | import { Store, StoreModule } from "@ngrx/store"; 9 | 10 | // reducers 11 | import { reducer } from "../../app.reducers"; 12 | 13 | // test this component 14 | import { SignOutComponent } from "./sign-out.component"; 15 | 16 | describe("Component: Signout", () => { 17 | let component: SignOutComponent; 18 | let fixture: ComponentFixture; 19 | 20 | beforeEach(async(() => { 21 | // refine the test module by declaring the test component 22 | TestBed.configureTestingModule({ 23 | imports: [ 24 | StoreModule.provideStore(reducer) 25 | ], 26 | declarations: [ 27 | SignOutComponent 28 | ], 29 | schemas: [ 30 | CUSTOM_ELEMENTS_SCHEMA 31 | ] 32 | }) 33 | .compileComponents(); 34 | 35 | // create component and test fixture 36 | fixture = TestBed.createComponent(SignOutComponent); 37 | 38 | // get test component from the fixture 39 | component = fixture.componentInstance; 40 | })); 41 | 42 | it("should create an instance", () => { 43 | expect(component).toBeTruthy(); 44 | }); 45 | }); 46 | -------------------------------------------------------------------------------- /src/app/users/sign-out/sign-out.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnDestroy, OnInit } from "@angular/core"; 2 | 3 | // @ngrx 4 | import { Store } from "@ngrx/store"; 5 | import { go } from "@ngrx/router-store"; 6 | 7 | // rxjs 8 | import { Observable } from "rxjs/Observable"; 9 | 10 | // actions 11 | import { SignOutAction } from "../users.actions"; 12 | 13 | // reducers 14 | import { 15 | getSignOutError, 16 | isAuthenticated, 17 | isAuthenticationLoading, 18 | State 19 | } from "../../app.reducers"; 20 | 21 | @Component({ 22 | templateUrl: "./sign-out.component.html", 23 | styleUrls: ["./sign-out.component.scss"] 24 | }) 25 | export class SignOutComponent implements OnDestroy, OnInit { 26 | 27 | /** 28 | * Component state. 29 | * @type {boolean} 30 | */ 31 | private alive = true; 32 | 33 | /** 34 | * @constructor 35 | * @param {Store} store 36 | */ 37 | constructor(private store: Store) { } 38 | 39 | /** 40 | * Lifecycle hook that is called when a directive, pipe or service is destroyed. 41 | */ 42 | public ngOnDestroy() { 43 | this.alive = false; 44 | } 45 | 46 | /** 47 | * Lifecycle hook that is called after data-bound properties of a directive are initialized. 48 | */ 49 | ngOnInit() { 50 | this.store.dispatch(new SignOutAction()); 51 | } 52 | 53 | /** 54 | * Go to the home page. 55 | */ 56 | public home() { 57 | this.store.dispatch(go("/")); 58 | } 59 | 60 | /** 61 | * To to the sign up page. 62 | */ 63 | public signIn() { 64 | this.store.dispatch(go("/users/sign-in")); 65 | } 66 | 67 | } 68 | -------------------------------------------------------------------------------- /src/app/users/sign-up/sign-up.component.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | Sign Up 9 | 10 | {{ error | async }} 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | Sign Up 26 | 27 | 28 | 29 | 30 | 31 | 32 | 33 | 34 | 35 | 36 | -------------------------------------------------------------------------------- /src/app/users/sign-up/sign-up.component.scss: -------------------------------------------------------------------------------- 1 | @import "~@angular/material/theming"; 2 | @import "~@angular/material/theming"; 3 | @import "../../../sass/mixins"; 4 | 5 | :host { 6 | .flex-container { 7 | background-color: mat-color($mat-grey, 100); 8 | position: relative; 9 | top: 0; 10 | left: 0; 11 | right: 0; 12 | min-height: 100vh; 13 | 14 | &::after { 15 | position: absolute; 16 | top: 0; 17 | width: 100%; 18 | height: 200px; 19 | left: 0; 20 | right: 0; 21 | background-color: mat-color($mat-indigo, 500); 22 | content: ""; 23 | box-shadow: 0 2px 4px 1px rgba(0,0,0,.14); 24 | z-index: 0; 25 | } 26 | 27 | .logo-container, .card-container { 28 | z-index: 1; 29 | } 30 | 31 | button.logo-container { 32 | background: transparent; 33 | padding: 0 16px; 34 | box-sizing: border-box; 35 | cursor: pointer; 36 | user-select: none; 37 | outline: 0; 38 | border: none; 39 | display: inline-block; 40 | white-space: nowrap; 41 | text-decoration: none; 42 | vertical-align: baseline; 43 | 44 | .logo { 45 | height: 64px; 46 | width: 64px; 47 | margin: 48px auto; 48 | background: url("http://placehold.it/64x64"); 49 | background-size: contain; 50 | @include retina { 51 | background: url("http://placehold.it/128x128") 64px/64px; 52 | } 53 | } 54 | } 55 | 56 | .card-container { 57 | mat-card { 58 | background-color: #fff; 59 | margin-bottom: 16px; 60 | 61 | mat-card-title { 62 | text-transform: uppercase; 63 | text-align: center; 64 | margin-bottom: 48px; 65 | } 66 | 67 | mat-card-content { 68 | margin-bottom: 16px; 69 | 70 | mat-form-field { 71 | margin-bottom: 16px; 72 | } 73 | 74 | button, a { 75 | margin-top: 16px; 76 | } 77 | } 78 | } 79 | } 80 | } 81 | } 82 | -------------------------------------------------------------------------------- /src/app/users/sign-up/sign-up.component.spec.ts: -------------------------------------------------------------------------------- 1 | /* tslint:disable:no-unused-variable */ 2 | import { DebugElement, CUSTOM_ELEMENTS_SCHEMA } from "@angular/core"; 3 | import { ComponentFixture, TestBed, async } from "@angular/core/testing"; 4 | import { FormBuilder, FormGroup, FormsModule, ReactiveFormsModule } from "@angular/forms"; 5 | import { MaterialModule } from "@angular/material"; 6 | import { ActivatedRoute } from "@angular/router"; 7 | import { By } from "@angular/platform-browser"; 8 | 9 | // rxjs 10 | import { Observable } from "rxjs/Observable"; 11 | 12 | // ngrx 13 | import { Store, StoreModule } from "@ngrx/store"; 14 | import { go } from "@ngrx/router-store"; 15 | 16 | // reducers 17 | import { reducer } from "../../app.reducers"; 18 | 19 | // services 20 | import { GroupService } from "../../core/services/group.service"; 21 | import { MockGroupService } from "../../../testing/mock.group.service"; 22 | import { USER } from "../../../testing/mock.user.service"; 23 | 24 | // models 25 | import { User } from "../../models/user"; 26 | 27 | // component to test 28 | import { SignUpComponent } from "./sign-up.component"; 29 | 30 | describe("Component: Signup", () => { 31 | let component: SignUpComponent; 32 | let fixture: ComponentFixture; 33 | let page: Page; 34 | let user: User = new User(); 35 | 36 | beforeEach(() => { 37 | user = USER; 38 | }); 39 | 40 | beforeEach(async(() => { 41 | // refine the test module by declaring the test component 42 | TestBed.configureTestingModule({ 43 | imports: [ 44 | FormsModule, 45 | MaterialModule, 46 | ReactiveFormsModule, 47 | StoreModule.provideStore(reducer) 48 | ], 49 | declarations: [ 50 | SignUpComponent 51 | ], 52 | providers: [ 53 | { 54 | provide: ActivatedRoute, 55 | useValue: { 56 | queryParams: Observable.of({}) 57 | } 58 | }, 59 | { provide: GroupService, useClass: MockGroupService } 60 | ], 61 | schemas: [ 62 | CUSTOM_ELEMENTS_SCHEMA 63 | ] 64 | }) 65 | .compileComponents(); 66 | 67 | // create component and test fixture 68 | fixture = TestBed.createComponent(SignUpComponent); 69 | 70 | // get test component from the fixture 71 | component = fixture.componentInstance; 72 | })); 73 | 74 | beforeEach(() => { 75 | // create page 76 | page = new Page(component, fixture); 77 | fixture.whenStable().then(() => { 78 | page.addPageElements(); 79 | }); 80 | }); 81 | 82 | it("should create a FormGroup comprised of FormControls", () => { 83 | fixture.detectChanges(); 84 | expect(component.signupForm instanceof FormGroup).toBe(true); 85 | }); 86 | 87 | it("should authenticate", () => { 88 | fixture.detectChanges(); 89 | 90 | // set FormControl values 91 | component.signupForm.controls["firstName"].setValue(user.firstName); 92 | component.signupForm.controls["lastName"].setValue(user.lastName); 93 | component.signupForm.controls["email"].setValue(user.email); 94 | component.signupForm.controls["password"].setValue(user.password); 95 | 96 | // submit form 97 | component.submit(); 98 | 99 | // verify Store.dispatch is invoked 100 | expect(page.navigateSpy.calls.any()).toBe(true, "Store.dispatch not called"); 101 | }); 102 | }); 103 | 104 | /** 105 | * I represent the DOM elements and attach spies. 106 | * 107 | * @class Page 108 | */ 109 | class Page { 110 | 111 | public emailInput: HTMLInputElement; 112 | public firstNameInput: HTMLInputElement; 113 | public lastNameInput: HTMLInputElement; 114 | public navigateSpy: jasmine.Spy; 115 | public passwordInput: HTMLInputElement; 116 | 117 | constructor(private component: SignUpComponent, private fixture: ComponentFixture) { 118 | // ese component"s injector to get services 119 | const injector = fixture.debugElement.injector; 120 | const store = injector.get(Store); 121 | 122 | // add spies 123 | this.navigateSpy = spyOn(store, "dispatch"); 124 | } 125 | 126 | public addPageElements() { 127 | const firstNameInputSelector = "md-input-container input[formcontrolname=\"firstName\"]"; 128 | this.firstNameInput = this.fixture.debugElement.query(By.css(firstNameInputSelector)).nativeElement; 129 | 130 | const lastNameInputSelector = "md-input-container input[formcontrolname=\"lastName\"]"; 131 | this.lastNameInput = this.fixture.debugElement.query(By.css(lastNameInputSelector)).nativeElement; 132 | 133 | const emailInputSelector = "md-input-container input[formcontrolname=\"email\"]"; 134 | this.emailInput = this.fixture.debugElement.query(By.css(emailInputSelector)).nativeElement; 135 | 136 | const passwordInputSelector = "md-input-container input[formcontrolname=\"password\"]"; 137 | this.passwordInput = this.fixture.debugElement.query(By.css(passwordInputSelector)).nativeElement; 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/app/users/sign-up/sign-up.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnDestroy, OnInit } from "@angular/core"; 2 | import { FormBuilder, FormGroup, Validators } from "@angular/forms"; 3 | 4 | // @ngrx 5 | import { Store } from "@ngrx/store"; 6 | import { go } from "@ngrx/router-store"; 7 | 8 | // rxjs 9 | import { Observable } from "rxjs/Observable"; 10 | 11 | // actions 12 | import { SignUpAction } from "../users.actions"; 13 | 14 | // reducers 15 | import { 16 | getSignUpError, 17 | isAuthenticated, 18 | isAuthenticationLoading, 19 | State 20 | } from "../../app.reducers"; 21 | 22 | // models 23 | import { User } from "../../core/models/user"; 24 | 25 | /** 26 | * /users/sign-up 27 | * @class SignUpComponent 28 | */ 29 | @Component({ 30 | templateUrl: "./sign-up.component.html", 31 | styleUrls: ["./sign-up.component.scss"] 32 | }) 33 | export class SignUpComponent implements OnDestroy, OnInit { 34 | 35 | /** 36 | * The error if authentication fails. 37 | * @type {Observable} 38 | */ 39 | public error: Observable; 40 | 41 | /** 42 | * True if the authentication is loading. 43 | * @type {boolean} 44 | */ 45 | public loading: Observable; 46 | 47 | /** 48 | * The authentication form. 49 | * @type {FormGroup} 50 | */ 51 | public signupForm: FormGroup; 52 | 53 | /** 54 | * Component state. 55 | * @type {boolean} 56 | */ 57 | private alive = true; 58 | 59 | /** 60 | * @constructor 61 | * @param {FormBuilder} formBuilder 62 | * @param {Store} store 63 | */ 64 | constructor( 65 | private formBuilder: FormBuilder, 66 | private store: Store 67 | ) {} 68 | 69 | /** 70 | * Lifecycle hook that is called after data-bound properties of a directive are initialized. 71 | * @method ngOnInit 72 | */ 73 | public ngOnInit() { 74 | // set FormGroup 75 | this.signupForm = this.formBuilder.group({ 76 | firstName: ["", Validators.required], 77 | lastName: ["", Validators.required], 78 | email: ["", Validators.required], 79 | password: ["", Validators.required] 80 | }); 81 | 82 | // set error 83 | this.error = this.store.select(getSignUpError); 84 | 85 | // set loading 86 | this.loading = this.store.select(isAuthenticationLoading); 87 | 88 | // subscribe to success 89 | this.store.select(isAuthenticated) 90 | .takeWhile(() => this.alive) 91 | .filter(authenticated => authenticated) 92 | .subscribe(value => { 93 | this.store.dispatch(go("/users/my-account")); 94 | }); 95 | } 96 | 97 | /** 98 | * Lifecycle hook that is called when a directive, pipe or service is destroyed. 99 | * @method ngOnDestroy 100 | */ 101 | public ngOnDestroy() { 102 | this.alive = false; 103 | } 104 | 105 | /** 106 | * Go to the home page. 107 | * @method home 108 | */ 109 | public home() { 110 | this.store.dispatch(go("/")); 111 | } 112 | 113 | /** 114 | * Submit the sign up form. 115 | * @method submit 116 | */ 117 | public submit() { 118 | // create a new User object 119 | const user: User = new User(); 120 | user.email = this.signupForm.get("email").value; 121 | user.firstName = this.signupForm.get("firstName").value; 122 | user.lastName = this.signupForm.get("lastName").value; 123 | user.password = this.signupForm.get("password").value; 124 | 125 | // trim values 126 | user.email.trim(); 127 | user.firstName.trim(); 128 | user.lastName.trim(); 129 | user.password.trim(); 130 | 131 | // set payload 132 | const payload = { 133 | user: user 134 | }; 135 | 136 | // dispatch SignUpAction and pass in payload 137 | this.store.dispatch(new SignUpAction(payload)); 138 | } 139 | } 140 | -------------------------------------------------------------------------------- /src/app/users/users-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from "@angular/core"; 2 | import { Routes, RouterModule } from "@angular/router"; 3 | 4 | // guards 5 | import { AuthenticatedGuard } from "../shared/authenticated.guard"; 6 | 7 | // components 8 | import { MyAccountComponent } from "./my-account/my-account.component"; 9 | import { SignInComponent } from "./sign-in/sign-in.component"; 10 | import { SignOutComponent } from "./sign-out/sign-out.component"; 11 | import { SignUpComponent } from "./sign-up/sign-up.component"; 12 | 13 | // routes 14 | const routes: Routes = [ 15 | { 16 | canActivate: [AuthenticatedGuard], 17 | path: "my-account", 18 | component: MyAccountComponent 19 | }, 20 | { 21 | path: "sign-in", 22 | component: SignInComponent 23 | }, 24 | { 25 | path: "sign-out", 26 | component: SignOutComponent 27 | }, 28 | { 29 | path: "sign-up", 30 | component: SignUpComponent 31 | }, 32 | { 33 | path: "**", 34 | redirectTo: "/404" 35 | } 36 | ]; 37 | 38 | @NgModule({ 39 | exports: [ 40 | RouterModule 41 | ], 42 | imports: [ 43 | RouterModule.forChild(routes) 44 | ] 45 | }) 46 | export class UsersRoutingModule { } 47 | -------------------------------------------------------------------------------- /src/app/users/users.actions.ts: -------------------------------------------------------------------------------- 1 | // import @ngrx 2 | import { Action } from "@ngrx/store"; 3 | 4 | // import type function 5 | import { type } from "../core/util"; 6 | 7 | // import models 8 | import { User } from "../core/models/user"; 9 | 10 | export const ActionTypes = { 11 | AUTHENTICATE: type("[users] Authenticate"), 12 | AUTHENTICATE_ERROR: type("[users] Authentication error"), 13 | AUTHENTICATE_SUCCESS: type("[users] Authentication success"), 14 | AUTHENTICATED: type("[users] Authenticated"), 15 | AUTHENTICATED_ERROR: type("[users] Authenticated error"), 16 | AUTHENTICATED_SUCCESS: type("[users] Authenticated success"), 17 | SIGN_OUT: type("[users] Sign off"), 18 | SIGN_OUT_ERROR: type("[users] Sign off error"), 19 | SIGN_OUT_SUCCESS: type("[users] Sign off success"), 20 | SIGN_UP: type("[users] Sign up"), 21 | SIGN_UP_ERROR: type("[users] Sign up error"), 22 | SIGN_UP_SUCCESS: type("[users] Sign up success") 23 | }; 24 | 25 | /** 26 | * Authenticate. 27 | * @class AuthenticateAction 28 | * @implements {Action} 29 | */ 30 | export class AuthenticateAction implements Action { 31 | public type: string = ActionTypes.AUTHENTICATE; 32 | 33 | constructor(public payload: {email: string, password: string}) {} 34 | } 35 | 36 | /** 37 | * Checks if user is authenticated. 38 | * @class AuthenticatedAction 39 | * @implements {Action} 40 | */ 41 | export class AuthenticatedAction implements Action { 42 | public type: string = ActionTypes.AUTHENTICATED; 43 | 44 | constructor(public payload?: {token?: string}) {} 45 | } 46 | 47 | /** 48 | * Authenticated check success. 49 | * @class AuthenticatedSuccessAction 50 | * @implements {Action} 51 | */ 52 | export class AuthenticatedSuccessAction implements Action { 53 | public type: string = ActionTypes.AUTHENTICATED_SUCCESS; 54 | 55 | constructor(public payload: {authenticated: boolean, user: User}) {} 56 | } 57 | 58 | /** 59 | * Authenticated check error. 60 | * @class AuthenticatedErrorAction 61 | * @implements {Action} 62 | */ 63 | export class AuthenticatedErrorAction implements Action { 64 | public type: string = ActionTypes.AUTHENTICATED_ERROR; 65 | 66 | constructor(public payload?: any) {} 67 | } 68 | 69 | /** 70 | * Authentication error. 71 | * @class AuthenticationErrorAction 72 | * @implements {Action} 73 | */ 74 | export class AuthenticationErrorAction implements Action { 75 | public type: string = ActionTypes.AUTHENTICATE_ERROR; 76 | 77 | constructor(public payload?: any) {} 78 | } 79 | 80 | /** 81 | * Authentication success. 82 | * @class AuthenticationSuccessAction 83 | * @implements {Action} 84 | */ 85 | export class AuthenticationSuccessAction implements Action { 86 | public type: string = ActionTypes.AUTHENTICATE_SUCCESS; 87 | 88 | constructor(public payload: { user: User }) {} 89 | } 90 | 91 | /** 92 | * Sign out. 93 | * @class SignOutAction 94 | * @implements {Action} 95 | */ 96 | export class SignOutAction implements Action { 97 | public type: string = ActionTypes.SIGN_OUT; 98 | constructor(public payload?: any) {} 99 | } 100 | 101 | /** 102 | * Sign out error. 103 | * @class SignOutErrorAction 104 | * @implements {Action} 105 | */ 106 | export class SignOutErrorAction implements Action { 107 | public type: string = ActionTypes.SIGN_OUT_SUCCESS; 108 | constructor(public payload?: any) {} 109 | } 110 | 111 | /** 112 | * Sign out success. 113 | * @class SignOutSuccessAction 114 | * @implements {Action} 115 | */ 116 | export class SignOutSuccessAction implements Action { 117 | public type: string = ActionTypes.SIGN_OUT_SUCCESS; 118 | constructor(public payload?: any) {} 119 | } 120 | 121 | /** 122 | * Sign up. 123 | * @class SignUpAction 124 | * @implements {Action} 125 | */ 126 | export class SignUpAction implements Action { 127 | public type: string = ActionTypes.SIGN_UP; 128 | constructor(public payload: { user: User }) {} 129 | } 130 | 131 | /** 132 | * Sign up error. 133 | * @class SignUpErrorAction 134 | * @implements {Action} 135 | */ 136 | export class SignUpErrorAction implements Action { 137 | public type: string = ActionTypes.SIGN_UP_ERROR; 138 | constructor(public payload?: any) {} 139 | } 140 | 141 | /** 142 | * Sign up success. 143 | * @class SignUpSuccessAction 144 | * @implements {Action} 145 | */ 146 | export class SignUpSuccessAction implements Action { 147 | public type: string = ActionTypes.SIGN_UP_SUCCESS; 148 | constructor(public payload: { user: User }) {} 149 | } 150 | 151 | /** 152 | * Actions type. 153 | * @type {Actions} 154 | */ 155 | export type Actions 156 | = 157 | AuthenticateAction 158 | | AuthenticatedAction 159 | | AuthenticatedErrorAction 160 | | AuthenticatedSuccessAction 161 | | AuthenticationErrorAction 162 | | AuthenticationSuccessAction 163 | | SignUpAction 164 | | SignUpErrorAction 165 | | SignUpSuccessAction; 166 | -------------------------------------------------------------------------------- /src/app/users/users.effects.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from "@angular/core"; 2 | 3 | // import @ngrx 4 | import { Effect, Actions, toPayload } from "@ngrx/effects"; 5 | import { Action } from "@ngrx/store"; 6 | 7 | // import rxjs 8 | import { Observable } from "rxjs/Observable"; 9 | import "rxjs/add/observable/of"; 10 | import "rxjs/add/operator/catch"; 11 | import "rxjs/add/operator/debounceTime"; 12 | import "rxjs/add/operator/map"; 13 | import "rxjs/add/operator/switchMap"; 14 | 15 | // import services 16 | import { UserService } from "../core/services/user.service"; 17 | 18 | // import actions 19 | import { 20 | ActionTypes, 21 | AuthenticatedErrorAction, 22 | AuthenticatedSuccessAction, 23 | AuthenticationErrorAction, 24 | AuthenticationSuccessAction, 25 | SignOutErrorAction, 26 | SignOutSuccessAction, 27 | SignUpErrorAction, 28 | SignUpSuccessAction 29 | } from "./users.actions"; 30 | 31 | /** 32 | * Effects offer a way to isolate and easily test side-effects within your 33 | * application. 34 | * The `toPayload` helper function returns just 35 | * the payload of the currently dispatched action, useful in 36 | * instances where the current state is not necessary. 37 | * 38 | * Documentation on `toPayload` can be found here: 39 | * https://github.com/ngrx/effects/blob/master/docs/api.md#topayload 40 | * 41 | * If you are unfamiliar with the operators being used in these examples, please 42 | * check out the sources below: 43 | * 44 | * Official Docs: http://reactivex.io/rxjs/manual/overview.html#categories-of-operators 45 | * RxJS 5 Operators By Example: https://gist.github.com/btroncone/d6cf141d6f2c00dc6b35 46 | */ 47 | 48 | @Injectable() 49 | export class UserEffects { 50 | 51 | /** 52 | * Authenticate user. 53 | * @method authenticate 54 | */ 55 | @Effect() 56 | public authenticate: Observable = this.actions 57 | .ofType(ActionTypes.AUTHENTICATE) 58 | .debounceTime(500) 59 | .map(toPayload) 60 | .switchMap(payload => { 61 | return this.userService.authenticate(payload.email, payload.password) 62 | .map(user => new AuthenticationSuccessAction({user: user})) 63 | .catch(error => Observable.of(new AuthenticationErrorAction({error: error}))); 64 | }); 65 | 66 | @Effect() 67 | public authenticated: Observable = this.actions 68 | .ofType(ActionTypes.AUTHENTICATED) 69 | .map(toPayload) 70 | .switchMap(payload => { 71 | return this.userService.authenticatedUser() 72 | .map(user => new AuthenticatedSuccessAction({authenticated: (user !== null), user: user})) 73 | .catch(error => Observable.of(new AuthenticatedErrorAction({error: error}))); 74 | }); 75 | 76 | @Effect() 77 | public createUser: Observable = this.actions 78 | .ofType(ActionTypes.SIGN_UP) 79 | .debounceTime(500) 80 | .map(toPayload) 81 | .switchMap(payload => { 82 | return this.userService.create(payload.user) 83 | .map(user => new SignUpSuccessAction({user: user})) 84 | .catch(error => Observable.of(new SignUpErrorAction({error: error}))); 85 | }); 86 | 87 | @Effect() 88 | public signOut: Observable = this.actions 89 | .ofType(ActionTypes.SIGN_OUT) 90 | .map(toPayload) 91 | .switchMap(payload => { 92 | return this.userService.signout() 93 | .map(value => new SignOutSuccessAction()) 94 | .catch(error => Observable.of(new SignOutErrorAction({error: error}))); 95 | }); 96 | 97 | /** 98 | * @constructor 99 | * @param {Actions }actions 100 | * @param {UserService} userService 101 | */ 102 | constructor(private actions: Actions, 103 | private userService: UserService) { 104 | } 105 | } 106 | -------------------------------------------------------------------------------- /src/app/users/users.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from "@angular/core"; 2 | import { CommonModule } from "@angular/common"; 3 | import { FormsModule, ReactiveFormsModule } from "@angular/forms"; 4 | import { RouterModule } from "@angular/router"; 5 | 6 | // @angular/flex-layout 7 | import { FlexLayoutModule } from "@angular/flex-layout"; 8 | 9 | // @angular/material 10 | import { 11 | MatButtonModule, 12 | MatCardModule, 13 | MatIconModule, 14 | MatInputModule, 15 | MatProgressSpinnerModule, 16 | MatMenuModule 17 | } from "@angular/material"; 18 | 19 | // components 20 | import { MyAccountComponent } from "./my-account/my-account.component"; 21 | import { SignInComponent } from "./sign-in/sign-in.component"; 22 | import { SignOutComponent } from "./sign-out/sign-out.component"; 23 | import { SignUpComponent } from "./sign-up/sign-up.component"; 24 | 25 | // routing 26 | import { UsersRoutingModule } from "./users-routing.module"; 27 | 28 | // components constant 29 | const components = [ 30 | MyAccountComponent, 31 | SignInComponent, 32 | SignUpComponent, 33 | SignOutComponent 34 | ]; 35 | 36 | @NgModule({ 37 | imports: [ 38 | CommonModule, 39 | FlexLayoutModule, 40 | FormsModule, 41 | MatButtonModule, 42 | MatCardModule, 43 | MatIconModule, 44 | MatInputModule, 45 | MatProgressSpinnerModule, 46 | MatMenuModule, 47 | ReactiveFormsModule, 48 | RouterModule, 49 | UsersRoutingModule 50 | ], 51 | declarations: components, 52 | exports: components, 53 | }) 54 | export class UsersModule { } 55 | -------------------------------------------------------------------------------- /src/app/users/users.reducers.ts: -------------------------------------------------------------------------------- 1 | // import actions 2 | import { Actions, ActionTypes } from "./users.actions"; 3 | 4 | // import models 5 | import { User } from "../core/models/user"; 6 | 7 | /** 8 | * The state. 9 | * @interface State 10 | */ 11 | export interface State { 12 | 13 | // boolean if user is authenticated 14 | authenticated: boolean; 15 | 16 | // error message 17 | error?: string; 18 | 19 | // true if we have attempted existing auth session 20 | loaded: boolean; 21 | 22 | // true when loading 23 | loading: boolean; 24 | 25 | // the authenticated user 26 | user?: User; 27 | } 28 | 29 | /** 30 | * The initial state. 31 | */ 32 | const initialState: State = { 33 | authenticated: null, 34 | loaded: false, 35 | loading: false 36 | }; 37 | 38 | /** 39 | * The reducer function. 40 | * @function reducer 41 | * @param {State} state Current state 42 | * @param {Actions} action Incoming action 43 | */ 44 | export function reducer(state: any = initialState, action: Actions): State { 45 | 46 | switch (action.type) { 47 | case ActionTypes.AUTHENTICATE: 48 | return Object.assign({}, state, { 49 | error: undefined, 50 | loading: true 51 | }); 52 | 53 | case ActionTypes.AUTHENTICATED_ERROR: 54 | return Object.assign({}, state, { 55 | authenticated: false, 56 | error: action.payload.error.message, 57 | loaded: true 58 | }); 59 | 60 | case ActionTypes.AUTHENTICATED_SUCCESS: 61 | return Object.assign({}, state, { 62 | authenticated: action.payload.authenticated, 63 | loaded: true, 64 | user: action.payload.user 65 | }); 66 | 67 | case ActionTypes.AUTHENTICATE_ERROR: 68 | case ActionTypes.SIGN_UP_ERROR: 69 | return Object.assign({}, state, { 70 | authenticated: false, 71 | error: action.payload.error.message, 72 | loading: false 73 | }); 74 | 75 | case ActionTypes.AUTHENTICATE_SUCCESS: 76 | case ActionTypes.SIGN_UP_SUCCESS: 77 | const user: User = action.payload.user; 78 | 79 | // verify user is not null 80 | if (user === null) { 81 | return state; 82 | } 83 | 84 | return Object.assign({}, state, { 85 | authenticated: true, 86 | error: undefined, 87 | loading: false, 88 | user: user 89 | }); 90 | 91 | case ActionTypes.SIGN_OUT_ERROR: 92 | return Object.assign({}, state, { 93 | authenticated: true, 94 | error: action.payload.error.message, 95 | user: undefined 96 | }); 97 | 98 | case ActionTypes.SIGN_OUT_SUCCESS: 99 | return Object.assign({}, state, { 100 | authenticated: false, 101 | error: undefined, 102 | user: undefined 103 | }); 104 | 105 | case ActionTypes.SIGN_UP: 106 | return Object.assign({}, state, { 107 | authenticated: false, 108 | error: undefined, 109 | loading: true 110 | }); 111 | 112 | default: 113 | return state; 114 | } 115 | } 116 | 117 | /** 118 | * Returns true if the user is authenticated. 119 | * @function isAuthenticated 120 | * @param {State} state 121 | * @returns {boolean} 122 | */ 123 | export const isAuthenticated = (state: State) => state.authenticated; 124 | 125 | /** 126 | * Returns true if the authenticated has loaded. 127 | * @function isAuthenticatedLoaded 128 | * @param {State} state 129 | * @returns {boolean} 130 | */ 131 | export const isAuthenticatedLoaded = (state: State) => state.loaded; 132 | 133 | /** 134 | * Return the users state 135 | * @function getAuthenticatedUser 136 | * @param {State} state 137 | * @returns {User} 138 | */ 139 | export const getAuthenticatedUser = (state: State) => state.user; 140 | 141 | /** 142 | * Returns the authentication error. 143 | * @function getAuthenticationError 144 | * @param {State} state 145 | * @returns {Error} 146 | */ 147 | export const getAuthenticationError = (state: State) => state.error; 148 | 149 | /** 150 | * Returns true if request is in progress. 151 | * @function isLoading 152 | * @param {State} state 153 | * @returns {boolean} 154 | */ 155 | export const isLoading = (state: State) => state.loading; 156 | 157 | /** 158 | * Returns the sign out error. 159 | * @function getSignOutError 160 | * @param {State} state 161 | * @returns {Error} 162 | */ 163 | export const getSignOutError = (state: State) => state.error; 164 | 165 | /** 166 | * Returns the sign up error. 167 | * @function getSignUpError 168 | * @param {State} state 169 | * @returns {Error} 170 | */ 171 | export const getSignUpError = (state: State) => state.error; 172 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blove/angular-reactive-authentication/e00e6c1fb310022b2469a0816e3eda0b99028410/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // The file contents for the current environment will overwrite these during build. 2 | // The build system defaults to the dev environment which uses `environment.ts`, but if you do 3 | // `ng build --env=prod` then `environment.prod.ts` will be used instead. 4 | // The list of which env maps to which file can be found in `.angular-cli.json`. 5 | 6 | export const environment = { 7 | production: false 8 | }; 9 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/blove/angular-reactive-authentication/e00e6c1fb310022b2469a0816e3eda0b99028410/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | ReactiveAuthenticationExample 6 | 7 | 8 | 9 | 10 | 11 | 12 | Loading... 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import { enableProdMode } from '@angular/core'; 2 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 3 | 4 | import { AppModule } from './app/app.module'; 5 | import { environment } from './environments/environment'; 6 | 7 | if (environment.production) { 8 | enableProdMode(); 9 | } 10 | 11 | platformBrowserDynamic().bootstrapModule(AppModule); 12 | -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/array'; 32 | // import 'core-js/es6/regexp'; 33 | // import 'core-js/es6/map'; 34 | // import 'core-js/es6/set'; 35 | 36 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 37 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 38 | 39 | /** IE10 and IE11 requires the following to support `@angular/animation`. */ 40 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 41 | 42 | 43 | /** Evergreen browsers require these. **/ 44 | import 'core-js/es6/reflect'; 45 | import 'core-js/es7/reflect'; 46 | 47 | 48 | /** ALL Firefox browsers require the following to support `@angular/animation`. **/ 49 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 50 | 51 | 52 | 53 | /*************************************************************************************************** 54 | * Zone JS is required by Angular itself. 55 | */ 56 | import 'zone.js/dist/zone'; // Included with Angular CLI. 57 | 58 | 59 | 60 | /*************************************************************************************************** 61 | * APPLICATION IMPORTS 62 | */ 63 | 64 | /** 65 | * Date, currency, decimal and percent pipes. 66 | * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 67 | */ 68 | // import 'intl'; // Run `npm install --save intl`. 69 | -------------------------------------------------------------------------------- /src/sass/_mixins.scss: -------------------------------------------------------------------------------- 1 | /** 2 | * Mixin for retina media query. 3 | */ 4 | @mixin retina { 5 | @media 6 | only screen and (min-device-pixel-ratio: 2), 7 | only screen and (min-resolution: 192dpi), 8 | only screen and (min-resolution: 2dppx) { 9 | @content; 10 | } 11 | } -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | @import '~@angular/material/prebuilt-themes/indigo-pink.css'; 3 | 4 | body { 5 | padding: 0; 6 | margin: 0; 7 | } 8 | 9 | mat-form-field { 10 | width: 100% !important; 11 | } 12 | -------------------------------------------------------------------------------- /src/test.ts: -------------------------------------------------------------------------------- 1 | // This file is required by karma.conf.js and loads recursively all the .spec and framework files 2 | 3 | import 'zone.js/dist/long-stack-trace-zone'; 4 | import 'zone.js/dist/proxy.js'; 5 | import 'zone.js/dist/sync-test'; 6 | import 'zone.js/dist/jasmine-patch'; 7 | import 'zone.js/dist/async-test'; 8 | import 'zone.js/dist/fake-async-test'; 9 | import { getTestBed } from '@angular/core/testing'; 10 | import { 11 | BrowserDynamicTestingModule, 12 | platformBrowserDynamicTesting 13 | } from '@angular/platform-browser-dynamic/testing'; 14 | 15 | // Unfortunately there's no typing for the `__karma__` variable. Just declare it as any. 16 | declare var __karma__: any; 17 | declare var require: any; 18 | 19 | // Prevent Karma from running prematurely. 20 | __karma__.loaded = function () {}; 21 | 22 | // First, initialize the Angular testing environment. 23 | getTestBed().initTestEnvironment( 24 | BrowserDynamicTestingModule, 25 | platformBrowserDynamicTesting() 26 | ); 27 | // Then we find all the tests. 28 | const context = require.context('./', true, /\.spec\.ts$/); 29 | // And load the modules. 30 | context.keys().map(context); 31 | // Finally, start Karma to run the tests. 32 | __karma__.start(); 33 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "module": "es2015", 6 | "baseUrl": "", 7 | "types": [] 8 | }, 9 | "exclude": [ 10 | "test.ts", 11 | "**/*.spec.ts" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "baseUrl": "", 8 | "types": [ 9 | "jasmine", 10 | "node" 11 | ] 12 | }, 13 | "files": [ 14 | "test.ts" 15 | ], 16 | "include": [ 17 | "**/*.spec.ts", 18 | "**/*.d.ts" 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /src/typings.d.ts: -------------------------------------------------------------------------------- 1 | /* SystemJS module definition */ 2 | declare var module: NodeModule; 3 | interface NodeModule { 4 | id: string; 5 | } 6 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "outDir": "./dist/out-tsc", 5 | "baseUrl": "src", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "moduleResolution": "node", 9 | "emitDecoratorMetadata": true, 10 | "experimentalDecorators": true, 11 | "target": "es5", 12 | "typeRoots": [ 13 | "node_modules/@types" 14 | ], 15 | "lib": [ 16 | "es2017", 17 | "dom" 18 | ] 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "callable-types": true, 7 | "class-name": true, 8 | "comment-format": [ 9 | true, 10 | "check-space" 11 | ], 12 | "curly": true, 13 | "eofline": true, 14 | "forin": true, 15 | "import-blacklist": [true, "rxjs"], 16 | "import-spacing": true, 17 | "indent": [ 18 | true, 19 | "spaces" 20 | ], 21 | "interface-over-type-literal": true, 22 | "label-position": true, 23 | "max-line-length": [ 24 | true, 25 | 140 26 | ], 27 | "member-access": false, 28 | "member-ordering": [ 29 | true, 30 | "static-before-instance", 31 | "variables-before-functions" 32 | ], 33 | "no-arg": true, 34 | "no-bitwise": true, 35 | "no-console": [ 36 | true, 37 | "debug", 38 | "info", 39 | "time", 40 | "timeEnd", 41 | "trace" 42 | ], 43 | "no-construct": true, 44 | "no-debugger": true, 45 | "no-duplicate-variable": true, 46 | "no-empty": false, 47 | "no-empty-interface": true, 48 | "no-eval": true, 49 | "no-inferrable-types": [true, "ignore-params"], 50 | "no-shadowed-variable": true, 51 | "no-string-literal": false, 52 | "no-string-throw": true, 53 | "no-switch-case-fall-through": true, 54 | "no-trailing-whitespace": true, 55 | "no-unused-expression": true, 56 | "no-use-before-declare": true, 57 | "no-var-keyword": true, 58 | "object-literal-sort-keys": false, 59 | "one-line": [ 60 | true, 61 | "check-open-brace", 62 | "check-catch", 63 | "check-else", 64 | "check-whitespace" 65 | ], 66 | "prefer-const": true, 67 | "quotemark": [ 68 | true, 69 | "double" 70 | ], 71 | "radix": true, 72 | "semicolon": [ 73 | "always" 74 | ], 75 | "triple-equals": [ 76 | true, 77 | "allow-null-check" 78 | ], 79 | "typedef-whitespace": [ 80 | true, 81 | { 82 | "call-signature": "nospace", 83 | "index-signature": "nospace", 84 | "parameter": "nospace", 85 | "property-declaration": "nospace", 86 | "variable-declaration": "nospace" 87 | } 88 | ], 89 | "typeof-compare": true, 90 | "unified-signatures": true, 91 | "variable-name": false, 92 | "whitespace": [ 93 | true, 94 | "check-branch", 95 | "check-decl", 96 | "check-operator", 97 | "check-separator", 98 | "check-type" 99 | ], 100 | 101 | "directive-selector": [true, "attribute", "app", "camelCase"], 102 | "component-selector": [true, "element", "app", "kebab-case"], 103 | "use-input-property-decorator": true, 104 | "use-output-property-decorator": true, 105 | "use-host-property-decorator": true, 106 | "no-input-rename": true, 107 | "no-output-rename": true, 108 | "use-life-cycle-interface": true, 109 | "use-pipe-transform-interface": true, 110 | "component-class-suffix": true, 111 | "directive-class-suffix": true, 112 | "no-access-missing-member": true, 113 | "templates-use-public": true, 114 | "invoke-injectable": true 115 | } 116 | } 117 | --------------------------------------------------------------------------------
Hello, {{ (user | async).firstName }}
You have been successfully signed out.