├── src ├── assets │ └── .gitkeep ├── app │ ├── app.component.css │ ├── components │ │ ├── landing │ │ │ ├── landing.component.css │ │ │ ├── landing.component.ts │ │ │ └── landing.component.html │ │ ├── log-in │ │ │ ├── log-in.component.css │ │ │ ├── log-in.component.ts │ │ │ └── log-in.component.html │ │ ├── sign-up │ │ │ ├── sign-up.component.css │ │ │ ├── sign-up.component.ts │ │ │ └── sign-up.component.html │ │ └── status │ │ │ ├── status.component.css │ │ │ ├── status.component.html │ │ │ └── status.component.ts │ ├── app.component.html │ ├── models │ │ └── user.ts │ ├── app.component.ts │ ├── store │ │ ├── app.states.ts │ │ ├── reducers │ │ │ └── auth.reducers.ts │ │ ├── actions │ │ │ └── auth.actions.ts │ │ └── effects │ │ │ └── auth.effects.ts │ ├── services │ │ ├── auth-guard.service.ts │ │ ├── auth.service.ts │ │ └── token.interceptor.ts │ └── app.module.ts ├── favicon.ico ├── styles.css ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── typings.d.ts ├── tsconfig.app.json ├── tsconfig.spec.json ├── index.html ├── main.ts ├── test.ts └── polyfills.ts ├── cypress.json ├── cypress ├── fixtures │ └── example.json ├── integration │ ├── landing.component.spec.js │ ├── status.component.spec.js │ ├── signup.component.spec.js │ └── login.component.spec.js ├── support │ ├── commands.js │ └── index.js └── plugins │ └── index.js ├── e2e ├── app.po.ts ├── tsconfig.e2e.json └── app.e2e-spec.ts ├── .editorconfig ├── tsconfig.json ├── .gitignore ├── protractor.conf.js ├── karma.conf.js ├── LICENSE ├── README.md ├── .angular-cli.json ├── package.json └── tslint.json /src/assets/.gitkeep: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/app.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/components/landing/landing.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/components/log-in/log-in.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/components/sign-up/sign-up.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/components/status/status.component.css: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 | 2 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/mjhea0/angular-auth-ngrx/HEAD/src/favicon.ico -------------------------------------------------------------------------------- /cypress.json: -------------------------------------------------------------------------------- 1 | { 2 | "baseUrl": "http://127.0.0.1:4200", 3 | "videoRecording": false 4 | } 5 | -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/app/models/user.ts: -------------------------------------------------------------------------------- 1 | export class User { 2 | id?: string; 3 | email?: string; 4 | password?: string; 5 | token?: string; 6 | } 7 | -------------------------------------------------------------------------------- /src/typings.d.ts: -------------------------------------------------------------------------------- 1 | /* SystemJS module definition */ 2 | declare var module: NodeModule; 3 | interface NodeModule { 4 | id: string; 5 | } 6 | -------------------------------------------------------------------------------- /cypress/fixtures/example.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "Using fixtures to represent data", 3 | "email": "hello@cypress.io", 4 | "body": "Fixtures are a great way to mock data for responses to routes" 5 | } -------------------------------------------------------------------------------- /src/app/components/status/status.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

Status Works!

4 |

5 | Home 6 |
7 | -------------------------------------------------------------------------------- /e2e/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get('/'); 6 | } 7 | 8 | getParagraphText() { 9 | return element(by.css('app-root h1')).getText(); 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /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 | title = 'app'; 10 | } 11 | -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "baseUrl": "./", 6 | "module": "es2015", 7 | "types": [] 8 | }, 9 | "exclude": [ 10 | "test.ts", 11 | "**/*.spec.ts" 12 | ] 13 | } 14 | -------------------------------------------------------------------------------- /.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 | -------------------------------------------------------------------------------- /e2e/tsconfig.e2e.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 8 | "types": [ 9 | "jasmine", 10 | "jasminewd2", 11 | "node" 12 | ] 13 | } 14 | } 15 | -------------------------------------------------------------------------------- /src/app/store/app.states.ts: -------------------------------------------------------------------------------- 1 | import { createFeatureSelector } from '@ngrx/store'; 2 | 3 | import * as auth from './reducers/auth.reducers'; 4 | 5 | 6 | export interface AppState { 7 | authState: auth.State; 8 | } 9 | 10 | export const reducers = { 11 | auth: auth.reducer 12 | }; 13 | 14 | export const selectAuthState = createFeatureSelector('auth'); 15 | -------------------------------------------------------------------------------- /e2e/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | 3 | describe('angular-auth-ngrx App', () => { 4 | let page: AppPage; 5 | 6 | beforeEach(() => { 7 | page = new AppPage(); 8 | }); 9 | 10 | it('should display welcome message', () => { 11 | page.navigateTo(); 12 | expect(page.getParagraphText()).toEqual('Angular + NGRX'); 13 | }); 14 | }); 15 | -------------------------------------------------------------------------------- /cypress/integration/landing.component.spec.js: -------------------------------------------------------------------------------- 1 | describe('Landing Component', () => { 2 | 3 | it('should display the landing page', () => { 4 | cy 5 | .visit('/') 6 | .get('h1').contains('Angular + NGRX') 7 | .get('a.btn').contains('Log in') 8 | .get('a.btn').contains('Sign up') 9 | .get('a.btn').contains('Status'); 10 | }); 11 | 12 | }); 13 | -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "baseUrl": "./", 6 | "module": "commonjs", 7 | "target": "es5", 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/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | AngularAuthNgrx 6 | 7 | 8 | 9 | 10 | 11 | 12 |
13 | 14 |
15 | 16 | 17 | -------------------------------------------------------------------------------- /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 | .catch(err => console.log(err)); 13 | -------------------------------------------------------------------------------- /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 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "outDir": "./dist/out-tsc", 5 | "sourceMap": true, 6 | "declaration": false, 7 | "moduleResolution": "node", 8 | "emitDecoratorMetadata": true, 9 | "experimentalDecorators": true, 10 | "target": "es5", 11 | "typeRoots": [ 12 | "node_modules/@types" 13 | ], 14 | "lib": [ 15 | "es2017", 16 | "dom" 17 | ] 18 | } 19 | } 20 | -------------------------------------------------------------------------------- /src/app/services/auth-guard.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Router, CanActivate } from '@angular/router'; 3 | 4 | import { AuthService } from './auth.service'; 5 | 6 | 7 | @Injectable() 8 | export class AuthGuardService implements CanActivate { 9 | constructor( 10 | public auth: AuthService, 11 | public router: Router 12 | ) {} 13 | canActivate(): boolean { 14 | if (!this.auth.getToken()) { 15 | this.router.navigateByUrl('/log-in'); 16 | return false; 17 | } 18 | return true; 19 | } 20 | } 21 | -------------------------------------------------------------------------------- /src/app/components/status/status.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Store } from '@ngrx/store'; 3 | 4 | import { AppState } from '../../store/app.states'; 5 | import { GetStatus } from '../../store/actions/auth.actions'; 6 | 7 | @Component({ 8 | selector: 'app-status', 9 | templateUrl: './status.component.html', 10 | styleUrls: ['./status.component.css'] 11 | }) 12 | export class StatusComponent implements OnInit { 13 | 14 | constructor(private store: Store) { } 15 | 16 | ngOnInit() { 17 | this.store.dispatch(new GetStatus); 18 | } 19 | 20 | } 21 | -------------------------------------------------------------------------------- /cypress/support/commands.js: -------------------------------------------------------------------------------- 1 | Cypress.Commands.add('login', (email, password) => { 2 | cy 3 | .visit('/') 4 | .get('a.btn').contains('Log in').click() 5 | .get('form input[name="email"]').clear().type(email) 6 | .get('form input[name="password"]').clear().type(password) 7 | .get('button[type="submit"]').click(); 8 | }); 9 | 10 | Cypress.Commands.add('signup', (email, password) => { 11 | cy 12 | .visit('/') 13 | .get('a.btn').contains('Sign up').click() 14 | .get('form input[name="email"]').clear().type(email) 15 | .get('form input[name="password"]').clear().type(password) 16 | .get('button[type="submit"]').click(); 17 | }); 18 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /dist-server 6 | /tmp 7 | /out-tsc 8 | 9 | # dependencies 10 | /node_modules 11 | 12 | # IDEs and editors 13 | /.idea 14 | .project 15 | .classpath 16 | .c9/ 17 | *.launch 18 | .settings/ 19 | *.sublime-workspace 20 | 21 | # IDE - VSCode 22 | .vscode/* 23 | !.vscode/settings.json 24 | !.vscode/tasks.json 25 | !.vscode/launch.json 26 | !.vscode/extensions.json 27 | 28 | # misc 29 | /.sass-cache 30 | /connect.lock 31 | /coverage 32 | /libpeerconnection.log 33 | npm-debug.log 34 | testem.log 35 | /typings 36 | 37 | # e2e 38 | /e2e/*.js 39 | /e2e/*.map 40 | 41 | # System Files 42 | .DS_Store 43 | Thumbs.db 44 | -------------------------------------------------------------------------------- /cypress/plugins/index.js: -------------------------------------------------------------------------------- 1 | // *********************************************************** 2 | // This example plugins/index.js can be used to load plugins 3 | // 4 | // You can change the location of this file or turn off loading 5 | // the plugins file with the 'pluginsFile' configuration option. 6 | // 7 | // You can read more here: 8 | // https://on.cypress.io/plugins-guide 9 | // *********************************************************** 10 | 11 | // This function is called when a project is opened or re-opened (e.g. due to 12 | // the project's config changing) 13 | 14 | module.exports = (on, config) => { 15 | // `on` is used to hook into various events Cypress emits 16 | // `config` is the resolved Cypress config 17 | } 18 | -------------------------------------------------------------------------------- /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/zone-testing'; 4 | import { getTestBed } from '@angular/core/testing'; 5 | import { 6 | BrowserDynamicTestingModule, 7 | platformBrowserDynamicTesting 8 | } from '@angular/platform-browser-dynamic/testing'; 9 | 10 | declare const require: any; 11 | 12 | // First, initialize the Angular testing environment. 13 | getTestBed().initTestEnvironment( 14 | BrowserDynamicTestingModule, 15 | platformBrowserDynamicTesting() 16 | ); 17 | // Then we find all the tests. 18 | const context = require.context('./', true, /\.spec\.ts$/); 19 | // And load the modules. 20 | context.keys().map(context); 21 | -------------------------------------------------------------------------------- /cypress/support/index.js: -------------------------------------------------------------------------------- 1 | // *********************************************************** 2 | // This example support/index.js is processed and 3 | // loaded automatically before your test files. 4 | // 5 | // This is a great place to put global configuration and 6 | // behavior that modifies Cypress. 7 | // 8 | // You can change the location of this file or turn off 9 | // automatically serving support files with the 10 | // 'supportFile' configuration option. 11 | // 12 | // You can read more here: 13 | // https://on.cypress.io/configuration 14 | // *********************************************************** 15 | 16 | // Import commands.js using ES2015 syntax: 17 | import './commands' 18 | 19 | // Alternatively you can use CommonJS syntax: 20 | // require('./commands') 21 | -------------------------------------------------------------------------------- /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 | onPrepare() { 23 | require('ts-node').register({ 24 | project: 'e2e/tsconfig.e2e.json' 25 | }); 26 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 27 | } 28 | }; 29 | -------------------------------------------------------------------------------- /cypress/integration/status.component.spec.js: -------------------------------------------------------------------------------- 1 | describe('Status Component', () => { 2 | 3 | it('should display the component if a user is logged in', () => { 4 | cy 5 | .login('test@test.com', 'test'); 6 | cy 7 | .location('pathname').should('eq', '/') 8 | .get('p').contains('You logged in test@test.com!') 9 | .get('a.btn').contains('Status').click(); 10 | cy 11 | .location('pathname').should('eq', '/status') 12 | .get('h1').contains('Status Works!') 13 | .get('a.btn').contains('Home'); 14 | }); 15 | 16 | it('should not display the component if a user is not logged in', () => { 17 | cy 18 | .visit('/') 19 | .get('a.btn').contains('Status').click(); 20 | cy 21 | .location('pathname').should('eq', '/log-in') 22 | .get('h1').contains('Status Works!').should('not.be.visible'); 23 | }); 24 | 25 | }); 26 | -------------------------------------------------------------------------------- /src/app/services/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { HttpClient } from '@angular/common/http'; 2 | import { Injectable } from '@angular/core'; 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import { User } from '../models/user'; 6 | 7 | 8 | @Injectable() 9 | export class AuthService { 10 | private BASE_URL = 'http://localhost:1337'; 11 | 12 | constructor(private http: HttpClient) {} 13 | 14 | getToken(): string { 15 | return localStorage.getItem('token'); 16 | } 17 | 18 | logIn(email: string, password: string): Observable { 19 | const url = `${this.BASE_URL}/login`; 20 | return this.http.post(url, {email, password}); 21 | } 22 | 23 | signUp(email: string, password: string): Observable { 24 | const url = `${this.BASE_URL}/register`; 25 | return this.http.post(url, {email, password}); 26 | } 27 | 28 | getStatus(): Observable { 29 | const url = `${this.BASE_URL}/status`; 30 | return this.http.get(url); 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /karma.conf.js: -------------------------------------------------------------------------------- 1 | // Karma configuration file, see link for more information 2 | // https://karma-runner.github.io/1.0/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 | coverageIstanbulReporter: { 19 | reports: [ 'html', 'lcovonly' ], 20 | fixWebpackSourcePaths: true 21 | }, 22 | angularCli: { 23 | environment: 'dev' 24 | }, 25 | reporters: ['progress', 'kjhtml'], 26 | port: 9876, 27 | colors: true, 28 | logLevel: config.LOG_INFO, 29 | autoWatch: true, 30 | browsers: ['Chrome'], 31 | singleRun: false 32 | }); 33 | }; 34 | -------------------------------------------------------------------------------- /src/app/components/landing/landing.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Store } from '@ngrx/store'; 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import { AppState, selectAuthState } from '../../store/app.states'; 6 | import { LogOut } from '../../store/actions/auth.actions'; 7 | 8 | 9 | @Component({ 10 | selector: 'app-landing', 11 | templateUrl: './landing.component.html', 12 | styleUrls: ['./landing.component.css'] 13 | }) 14 | export class LandingComponent implements OnInit { 15 | 16 | getState: Observable; 17 | isAuthenticated: false; 18 | user = null; 19 | errorMessage = null; 20 | 21 | constructor( 22 | private store: Store 23 | ) { 24 | this.getState = this.store.select(selectAuthState); 25 | } 26 | 27 | ngOnInit() { 28 | this.getState.subscribe((state) => { 29 | this.isAuthenticated = state.isAuthenticated; 30 | this.user = state.user; 31 | this.errorMessage = state.errorMessage; 32 | }); 33 | } 34 | 35 | logOut(): void { 36 | this.store.dispatch(new LogOut); 37 | } 38 | 39 | } 40 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Michael Herman 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /src/app/components/log-in/log-in.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Store } from '@ngrx/store'; 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import { User } from '../../models/user'; 6 | import { AppState, selectAuthState } from '../../store/app.states'; 7 | import { LogIn } from '../../store/actions/auth.actions'; 8 | 9 | 10 | @Component({ 11 | selector: 'app-log-in', 12 | templateUrl: './log-in.component.html', 13 | styleUrls: ['./log-in.component.css'] 14 | }) 15 | export class LogInComponent implements OnInit { 16 | 17 | user: User = new User(); 18 | getState: Observable; 19 | errorMessage: string | null; 20 | 21 | constructor( 22 | private store: Store 23 | ) { 24 | this.getState = this.store.select(selectAuthState); 25 | } 26 | 27 | ngOnInit() { 28 | this.getState.subscribe((state) => { 29 | this.errorMessage = state.errorMessage; 30 | }); 31 | } 32 | 33 | onSubmit(): void { 34 | const payload = { 35 | email: this.user.email, 36 | password: this.user.password 37 | }; 38 | this.store.dispatch(new LogIn(payload)); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/app/components/sign-up/sign-up.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Store } from '@ngrx/store'; 3 | import { Observable } from 'rxjs/Observable'; 4 | 5 | import { User } from '../../models/user'; 6 | import { AppState, selectAuthState } from '../../store/app.states'; 7 | import { SignUp } from '../../store/actions/auth.actions'; 8 | 9 | 10 | @Component({ 11 | selector: 'app-sign-up', 12 | templateUrl: './sign-up.component.html', 13 | styleUrls: ['./sign-up.component.css'] 14 | }) 15 | export class SignUpComponent implements OnInit { 16 | 17 | user: User = new User(); 18 | getState: Observable; 19 | errorMessage: string | null; 20 | 21 | constructor( 22 | private store: Store 23 | ) { 24 | this.getState = this.store.select(selectAuthState); 25 | } 26 | 27 | ngOnInit() { 28 | this.getState.subscribe((state) => { 29 | this.errorMessage = state.errorMessage; 30 | }); 31 | } 32 | 33 | onSubmit(): void { 34 | const payload = { 35 | email: this.user.email, 36 | password: this.user.password 37 | }; 38 | this.store.dispatch(new SignUp(payload)); 39 | } 40 | 41 | } 42 | -------------------------------------------------------------------------------- /src/app/components/landing/landing.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 4 |

Angular + NGRX

5 |

6 | 7 |
8 | 9 |

You logged in {{user.email}}!

10 | 11 |
12 | 13 | Log in 14 | Sign up 15 | 16 | 17 | Status 18 | 19 |


20 | 21 |
22 |
23 |
Current State
24 |
    25 |
  • isAuthenticated - {{isAuthenticated}}
  • 26 |
  • user.email - {{ user?.email || 'null'}}
  • 27 |
  • user.token - {{ user?.token || 'null'}}
  • 28 |
  • errorMessage - {{ errorMessage || 'null'}}
  • 29 |
30 |
31 |
32 | 33 |
34 |
35 | -------------------------------------------------------------------------------- /src/app/components/log-in/log-in.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

Log in

4 |

5 |
6 | 9 |
10 |
11 |
12 | 13 | 21 |
22 |
23 | 24 | 32 |
33 | 34 | Cancel 35 |
36 |

37 | Don't have an account?  38 | Sign up! 39 |

40 |
41 |
42 | -------------------------------------------------------------------------------- /src/app/components/sign-up/sign-up.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

Sign up

4 |

5 |
6 | 9 |
10 |
11 |
12 | 13 | 21 |
22 |
23 | 24 | 32 |
33 | 34 | Cancel 35 |
36 |

37 | Already have an account?  38 | Log in! 39 |

40 |
41 |
42 | -------------------------------------------------------------------------------- /cypress/integration/signup.component.spec.js: -------------------------------------------------------------------------------- 1 | describe('SignUp Component', () => { 2 | 3 | it('should sign a user up', () => { 4 | cy 5 | .signup('test@test.com', 'test'); 6 | cy 7 | .location('pathname').should('eq', '/') 8 | .get('p').contains('You logged in test@test.com!') 9 | .get('a.btn').contains('Log in').should('not.be.visible') 10 | .get('a.btn').contains('Sign up').should('not.be.visible') 11 | .get('a.btn').contains('Status') 12 | .get('button.btn').contains('Log out'); 13 | }); 14 | 15 | it('should throw an error if the email is already is use', () => { 16 | cy 17 | .signup('in@use.com', 'test'); 18 | cy 19 | .get('p') 20 | .contains('You logged in test@test.com!') 21 | .should('not.be.visible'); 22 | cy 23 | .location('pathname').should('eq', '/sign-up') 24 | .get('div.alert.alert-danger') 25 | .contains('That email is already in use.'); 26 | }); 27 | 28 | it('should not display an error message when a user first hits the component', () => { 29 | cy 30 | .login('not@correct.com', 'incorrect') 31 | .get('div.alert.alert-danger') 32 | .contains('Incorrect email and/or password.') 33 | .get('a.btn').contains('Cancel').click() 34 | .get('a.btn').contains('Sign up').click(); 35 | // cy 36 | // .get('div.alert.alert-danger') 37 | // .should('not.be.visible'); 38 | }); 39 | 40 | }); 41 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Authentication in Angular with NGRX 2 | 3 | ## Want to learn how to build this project? 4 | 5 | Check out the [blog post](http://mherman.org/blog/2018/04/17/authentication-in-angular-with-ngrx/). 6 | 7 | ## Want to use this project? 8 | 9 | 1. Fork/Clone 10 | 1. Install dependencies - `npm install` 11 | 1. Run the development server - `ng serve` 12 | 13 | You will need to also spin up a back-end with the following routes: 14 | 15 | | URL | HTTP Verb | Action | 16 | |--------------------------------|-----------|---------------------| 17 | | http://localhost:1337/register | POST | Register a new user | 18 | | http://localhost:1337/login | POST | Log a user in | 19 | | http://localhost:1337/status | GET | Get user status | 20 | 21 | The blog post uses a fake back-end that generates a dummy token to test out the functionality on the front-end. If you'd like to use it, clone down the repo in a new terminal window, install the dependencies, and fire up the app: 22 | 23 | ```sh 24 | $ git clone https://github.com/testdrivenio/fake-token-api 25 | $ cd fake-token-api 26 | $ npm install 27 | $ npm start 28 | ``` 29 | 30 | > Just keep in mind that the back-end does **not** create a real JSON Web Token (JWT). Feel free to swap it out for a working back-end or use the final application from the [Token-Based Authentication with Node](http://mherman.org/blog/2016/10/28/token-based-authentication-with-node) blog post, if you'd like. 31 | -------------------------------------------------------------------------------- /.angular-cli.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "project": { 4 | "name": "angular-auth-ngrx" 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 | "../node_modules/bootstrap/dist/css/bootstrap.min.css", 23 | "styles.css" 24 | ], 25 | "scripts": [], 26 | "environmentSource": "environments/environment.ts", 27 | "environments": { 28 | "dev": "environments/environment.ts", 29 | "prod": "environments/environment.prod.ts" 30 | } 31 | } 32 | ], 33 | "e2e": { 34 | "protractor": { 35 | "config": "./protractor.conf.js" 36 | } 37 | }, 38 | "lint": [ 39 | { 40 | "project": "src/tsconfig.app.json", 41 | "exclude": "**/node_modules/**" 42 | }, 43 | { 44 | "project": "src/tsconfig.spec.json", 45 | "exclude": "**/node_modules/**" 46 | }, 47 | { 48 | "project": "e2e/tsconfig.e2e.json", 49 | "exclude": "**/node_modules/**" 50 | } 51 | ], 52 | "test": { 53 | "karma": { 54 | "config": "./karma.conf.js" 55 | } 56 | }, 57 | "defaults": { 58 | "styleExt": "css", 59 | "component": {} 60 | } 61 | } 62 | -------------------------------------------------------------------------------- /src/app/services/token.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable, Injector } from '@angular/core'; 2 | import { 3 | HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, 4 | HttpResponse, HttpErrorResponse 5 | } from '@angular/common/http'; 6 | import { Observable } from 'rxjs/Observable'; 7 | import 'rxjs/add/operator/do'; 8 | import { Router } from '@angular/router'; 9 | 10 | import { AuthService } from './auth.service'; 11 | 12 | 13 | @Injectable() 14 | export class TokenInterceptor implements HttpInterceptor { 15 | private authService: AuthService; 16 | constructor(private injector: Injector) {} 17 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 18 | this.authService = this.injector.get(AuthService); 19 | const token: string = this.authService.getToken(); 20 | request = request.clone({ 21 | setHeaders: { 22 | 'Authorization': `Bearer ${token}`, 23 | 'Content-Type': 'application/json' 24 | } 25 | }); 26 | return next.handle(request); 27 | } 28 | } 29 | 30 | @Injectable() 31 | export class ErrorInterceptor implements HttpInterceptor { 32 | constructor(private router: Router) {} 33 | intercept(request: HttpRequest, next: HttpHandler): Observable> { 34 | 35 | return next.handle(request) 36 | .catch((response: any) => { 37 | if (response instanceof HttpErrorResponse && response.status === 401) { 38 | localStorage.removeItem('token'); 39 | this.router.navigateByUrl('/log-in'); 40 | } 41 | return Observable.throw(response); 42 | }); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-auth-ngrx", 3 | "version": "0.0.0", 4 | "license": "MIT", 5 | "scripts": { 6 | "ng": "ng", 7 | "start": "ng serve", 8 | "build": "ng build --prod", 9 | "test": "ng test", 10 | "lint": "ng lint", 11 | "e2e": "ng e2e" 12 | }, 13 | "private": true, 14 | "dependencies": { 15 | "@angular/animations": "^5.2.0", 16 | "@angular/common": "^5.2.0", 17 | "@angular/compiler": "^5.2.0", 18 | "@angular/core": "^5.2.0", 19 | "@angular/forms": "^5.2.0", 20 | "@angular/http": "^5.2.0", 21 | "@angular/platform-browser": "^5.2.0", 22 | "@angular/platform-browser-dynamic": "^5.2.0", 23 | "@angular/router": "^5.2.0", 24 | "@ngrx/effects": "^5.2.0", 25 | "@ngrx/store": "^5.2.0", 26 | "bootstrap": "^4.1.0", 27 | "core-js": "^2.4.1", 28 | "rxjs": "^5.5.6", 29 | "zone.js": "^0.8.19" 30 | }, 31 | "devDependencies": { 32 | "@angular/cli": "~1.7.3", 33 | "@angular/compiler-cli": "^5.2.0", 34 | "@angular/language-service": "^5.2.0", 35 | "@types/jasmine": "~2.8.3", 36 | "@types/jasminewd2": "~2.0.2", 37 | "@types/node": "~6.0.60", 38 | "codelyzer": "^4.0.1", 39 | "cypress": "^2.1.0", 40 | "jasmine-core": "~2.8.0", 41 | "jasmine-spec-reporter": "~4.2.1", 42 | "karma": "~2.0.0", 43 | "karma-chrome-launcher": "~2.2.0", 44 | "karma-coverage-istanbul-reporter": "^1.2.1", 45 | "karma-jasmine": "~1.1.0", 46 | "karma-jasmine-html-reporter": "^0.2.2", 47 | "protractor": "~5.1.2", 48 | "ts-node": "~4.1.0", 49 | "tslint": "~5.9.1", 50 | "typescript": "~2.5.3" 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /src/app/store/reducers/auth.reducers.ts: -------------------------------------------------------------------------------- 1 | import { User } from '../../models/user'; 2 | import { AuthActionTypes, All } from '../actions/auth.actions'; 3 | 4 | 5 | export interface State { 6 | // is a user authenticated? 7 | isAuthenticated: boolean; 8 | // if authenticated, there should be a user object 9 | user: User | null; 10 | // error message 11 | errorMessage: string | null; 12 | } 13 | 14 | export const initialState: State = { 15 | isAuthenticated: false, 16 | user: null, 17 | errorMessage: null 18 | }; 19 | 20 | export function reducer(state = initialState, action: All): State { 21 | switch (action.type) { 22 | case AuthActionTypes.LOGIN_SUCCESS: { 23 | return { 24 | ...state, 25 | isAuthenticated: true, 26 | user: { 27 | token: action.payload.token, 28 | email: action.payload.email 29 | }, 30 | errorMessage: null 31 | }; 32 | } 33 | case AuthActionTypes.LOGIN_FAILURE: { 34 | return { 35 | ...state, 36 | errorMessage: 'Incorrect email and/or password.' 37 | }; 38 | } 39 | case AuthActionTypes.SIGNUP_SUCCESS: { 40 | return { 41 | ...state, 42 | isAuthenticated: true, 43 | user: { 44 | token: action.payload.token, 45 | email: action.payload.email 46 | }, 47 | errorMessage: null 48 | }; 49 | } 50 | case AuthActionTypes.SIGNUP_FAILURE: { 51 | return { 52 | ...state, 53 | errorMessage: 'That email is already in use.' 54 | }; 55 | } 56 | case AuthActionTypes.LOGOUT: { 57 | return initialState; 58 | } 59 | default: { 60 | return state; 61 | } 62 | } 63 | } 64 | -------------------------------------------------------------------------------- /src/app/store/actions/auth.actions.ts: -------------------------------------------------------------------------------- 1 | import { Action } from '@ngrx/store'; 2 | 3 | 4 | export enum AuthActionTypes { 5 | LOGIN = '[Auth] Login', 6 | LOGIN_SUCCESS = '[Auth] Login Success', 7 | LOGIN_FAILURE = '[Auth] Login Failure', 8 | SIGNUP = '[Auth] Signup', 9 | SIGNUP_SUCCESS = '[Auth] Signup Success', 10 | SIGNUP_FAILURE = '[Auth] Signup Failure', 11 | LOGOUT = '[Auth] Logout', 12 | GET_STATUS = '[Auth] GetStatus' 13 | } 14 | 15 | export class LogIn implements Action { 16 | readonly type = AuthActionTypes.LOGIN; 17 | constructor(public payload: any) {} 18 | } 19 | 20 | export class LogInSuccess implements Action { 21 | readonly type = AuthActionTypes.LOGIN_SUCCESS; 22 | constructor(public payload: any) {} 23 | } 24 | 25 | export class LogInFailure implements Action { 26 | readonly type = AuthActionTypes.LOGIN_FAILURE; 27 | constructor(public payload: any) {} 28 | } 29 | 30 | export class SignUp implements Action { 31 | readonly type = AuthActionTypes.SIGNUP; 32 | constructor(public payload: any) {} 33 | } 34 | 35 | export class SignUpSuccess implements Action { 36 | readonly type = AuthActionTypes.SIGNUP_SUCCESS; 37 | constructor(public payload: any) {} 38 | } 39 | 40 | export class SignUpFailure implements Action { 41 | readonly type = AuthActionTypes.SIGNUP_FAILURE; 42 | constructor(public payload: any) {} 43 | } 44 | 45 | export class LogOut implements Action { 46 | readonly type = AuthActionTypes.LOGOUT; 47 | } 48 | 49 | export class GetStatus implements Action { 50 | readonly type = AuthActionTypes.GET_STATUS; 51 | } 52 | 53 | export type All = 54 | | LogIn 55 | | LogInSuccess 56 | | LogInFailure 57 | | SignUp 58 | | SignUpSuccess 59 | | SignUpFailure 60 | | LogOut 61 | | GetStatus; 62 | -------------------------------------------------------------------------------- /cypress/integration/login.component.spec.js: -------------------------------------------------------------------------------- 1 | describe('LogIn Component', () => { 2 | 3 | it('should log a user in if the credentials are valid', () => { 4 | cy 5 | .login('test@test.com', 'test'); 6 | cy 7 | .location('pathname').should('eq', '/') 8 | .get('p').contains('You logged in test@test.com!') 9 | .get('a.btn').contains('Log in').should('not.be.visible') 10 | .get('a.btn').contains('Sign up').should('not.be.visible') 11 | .get('a.btn').contains('Status') 12 | .get('button.btn').contains('Log out'); 13 | }); 14 | 15 | it('should not log a user in if the credentials are invalid', () => { 16 | cy 17 | .login('not@correct.com', 'incorrect'); 18 | cy 19 | .get('p') 20 | .contains('You logged in test@test.com!') 21 | .should('not.be.visible'); 22 | cy 23 | .location('pathname').should('eq', '/log-in') 24 | .get('div.alert.alert-danger') 25 | .contains('Incorrect email and/or password.'); 26 | }); 27 | 28 | it('should log an authenticated user out', () => { 29 | cy 30 | .login('test@test.com', 'test'); 31 | cy 32 | .get('p').contains('You logged in test@test.com!') 33 | .get('button.btn').contains('Log out').click() 34 | cy 35 | .location('pathname').should('eq', '/') 36 | .get('h1').contains('Angular + NGRX') 37 | .get('a.btn').contains('Log in') 38 | .get('a.btn').contains('Sign up') 39 | .get('a.btn').contains('Status'); 40 | }); 41 | 42 | it('should not display an error message when a user first hits the component', () => { 43 | cy 44 | .signup('in@use.com', 'test') 45 | .get('div.alert.alert-danger') 46 | .contains('That email is already in use.') 47 | .get('a.btn').contains('Cancel').click() 48 | .get('a.btn').contains('Log in').click(); 49 | // cy 50 | // .get('div.alert.alert-danger') 51 | // .should('not.be.visible'); 52 | }); 53 | 54 | }); 55 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | import { RouterModule, CanActivate } from '@angular/router'; 4 | import { FormsModule } from '@angular/forms'; 5 | import { HttpClientModule } from '@angular/common/http'; 6 | import { EffectsModule } from '@ngrx/effects'; 7 | import { StoreModule } from '@ngrx/store'; 8 | import { HTTP_INTERCEPTORS } from '@angular/common/http'; 9 | 10 | import { AppComponent } from './app.component'; 11 | import { LandingComponent } from './components/landing/landing.component'; 12 | import { SignUpComponent } from './components/sign-up/sign-up.component'; 13 | import { LogInComponent } from './components/log-in/log-in.component'; 14 | import { AuthService } from './services/auth.service'; 15 | import { AuthEffects } from './store/effects/auth.effects'; 16 | import { reducers } from './store/app.states'; 17 | import { 18 | TokenInterceptor, ErrorInterceptor 19 | } from './services/token.interceptor'; 20 | import { StatusComponent } from './components/status/status.component'; 21 | import { AuthGuardService as AuthGuard } from './services/auth-guard.service'; 22 | 23 | 24 | @NgModule({ 25 | declarations: [ 26 | AppComponent, 27 | LandingComponent, 28 | SignUpComponent, 29 | LogInComponent, 30 | StatusComponent 31 | ], 32 | imports: [ 33 | BrowserModule, 34 | FormsModule, 35 | HttpClientModule, 36 | StoreModule.forRoot(reducers, {}), 37 | EffectsModule.forRoot([AuthEffects]), 38 | RouterModule.forRoot([ 39 | { path: 'log-in', component: LogInComponent }, 40 | { path: 'sign-up', component: SignUpComponent }, 41 | { path: 'status', component: StatusComponent, canActivate: [AuthGuard] }, 42 | { path: '', component: LandingComponent }, 43 | { path: '**', redirectTo: '/' } 44 | ]) 45 | ], 46 | providers: [ 47 | AuthService, 48 | AuthGuard, 49 | { 50 | provide: HTTP_INTERCEPTORS, 51 | useClass: TokenInterceptor, 52 | multi: true 53 | }, 54 | { 55 | provide: HTTP_INTERCEPTORS, 56 | useClass: ErrorInterceptor, 57 | multi: true 58 | } 59 | ], 60 | bootstrap: [AppComponent] 61 | }) 62 | export class AppModule { } 63 | -------------------------------------------------------------------------------- /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/weak-map'; 35 | // import 'core-js/es6/set'; 36 | 37 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 38 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 39 | 40 | /** IE10 and IE11 requires the following for the Reflect API. */ 41 | // import 'core-js/es6/reflect'; 42 | 43 | 44 | /** Evergreen browsers require these. **/ 45 | // Used for reflect-metadata in JIT. If you use AOT (and only Angular decorators), you can remove. 46 | import 'core-js/es7/reflect'; 47 | 48 | 49 | /** 50 | * Required to support Web Animations `@angular/platform-browser/animations`. 51 | * Needed for: All but Chrome, Firefox and Opera. http://caniuse.com/#feat=web-animation 52 | **/ 53 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 54 | 55 | 56 | 57 | /*************************************************************************************************** 58 | * Zone JS is required by default for Angular itself. 59 | */ 60 | import 'zone.js/dist/zone'; // Included with Angular CLI. 61 | 62 | 63 | 64 | /*************************************************************************************************** 65 | * APPLICATION IMPORTS 66 | */ 67 | -------------------------------------------------------------------------------- /src/app/store/effects/auth.effects.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Action } from '@ngrx/store'; 3 | import { Router } from '@angular/router'; 4 | import { Actions, Effect, ofType } from '@ngrx/effects'; 5 | import { Observable } from 'rxjs/Observable'; 6 | import 'rxjs/add/observable/of'; 7 | import 'rxjs/add/operator/map'; 8 | import 'rxjs/add/operator/switchMap'; 9 | import 'rxjs/add/operator/catch'; 10 | import { tap } from 'rxjs/operators'; 11 | 12 | import { AuthService } from '../../services/auth.service'; 13 | import { 14 | AuthActionTypes, 15 | LogIn, LogInSuccess, LogInFailure, 16 | SignUp, SignUpSuccess, SignUpFailure, 17 | LogOut, 18 | } from '../actions/auth.actions'; 19 | 20 | 21 | @Injectable() 22 | export class AuthEffects { 23 | 24 | constructor( 25 | private actions: Actions, 26 | private authService: AuthService, 27 | private router: Router, 28 | ) {} 29 | 30 | @Effect() 31 | LogIn: Observable = this.actions 32 | .ofType(AuthActionTypes.LOGIN) 33 | .map((action: LogIn) => action.payload) 34 | .switchMap(payload => { 35 | return this.authService.logIn(payload.email, payload.password) 36 | .map((user) => { 37 | return new LogInSuccess({token: user.token, email: payload.email}); 38 | }) 39 | .catch((error) => { 40 | return Observable.of(new LogInFailure({ error: error })); 41 | }); 42 | }); 43 | 44 | 45 | @Effect({ dispatch: false }) 46 | LogInSuccess: Observable = this.actions.pipe( 47 | ofType(AuthActionTypes.LOGIN_SUCCESS), 48 | tap((user) => { 49 | localStorage.setItem('token', user.payload.token); 50 | this.router.navigateByUrl('/'); 51 | }) 52 | ); 53 | 54 | @Effect({ dispatch: false }) 55 | LogInFailure: Observable = this.actions.pipe( 56 | ofType(AuthActionTypes.LOGIN_FAILURE) 57 | ); 58 | 59 | @Effect() 60 | SignUp: Observable = this.actions 61 | .ofType(AuthActionTypes.SIGNUP) 62 | .map((action: SignUp) => action.payload) 63 | .switchMap(payload => { 64 | return this.authService.signUp(payload.email, payload.password) 65 | .map((user) => { 66 | return new SignUpSuccess({token: user.token, email: payload.email}); 67 | }) 68 | .catch((error) => { 69 | return Observable.of(new SignUpFailure({ error: error })); 70 | }); 71 | }); 72 | 73 | @Effect({ dispatch: false }) 74 | SignUpSuccess: Observable = this.actions.pipe( 75 | ofType(AuthActionTypes.SIGNUP_SUCCESS), 76 | tap((user) => { 77 | localStorage.setItem('token', user.payload.token); 78 | this.router.navigateByUrl('/'); 79 | }) 80 | ); 81 | 82 | @Effect({ dispatch: false }) 83 | SignUpFailure: Observable = this.actions.pipe( 84 | ofType(AuthActionTypes.SIGNUP_FAILURE) 85 | ); 86 | 87 | @Effect({ dispatch: false }) 88 | public LogOut: Observable = this.actions.pipe( 89 | ofType(AuthActionTypes.LOGOUT), 90 | tap((user) => { 91 | localStorage.removeItem('token'); 92 | }) 93 | ); 94 | 95 | @Effect({ dispatch: false }) 96 | GetStatus: Observable = this.actions 97 | .ofType(AuthActionTypes.GET_STATUS) 98 | .switchMap(payload => { 99 | return this.authService.getStatus(); 100 | }); 101 | 102 | } 103 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "rulesDirectory": [ 3 | "node_modules/codelyzer" 4 | ], 5 | "rules": { 6 | "arrow-return-shorthand": true, 7 | "callable-types": true, 8 | "class-name": true, 9 | "comment-format": [ 10 | true, 11 | "check-space" 12 | ], 13 | "curly": true, 14 | "deprecation": { 15 | "severity": "warn" 16 | }, 17 | "eofline": true, 18 | "forin": true, 19 | "import-blacklist": [ 20 | true, 21 | "rxjs", 22 | "rxjs/Rx" 23 | ], 24 | "import-spacing": true, 25 | "indent": [ 26 | true, 27 | "spaces" 28 | ], 29 | "interface-over-type-literal": true, 30 | "label-position": true, 31 | "max-line-length": [ 32 | true, 33 | 140 34 | ], 35 | "member-access": false, 36 | "member-ordering": [ 37 | true, 38 | { 39 | "order": [ 40 | "static-field", 41 | "instance-field", 42 | "static-method", 43 | "instance-method" 44 | ] 45 | } 46 | ], 47 | "no-arg": true, 48 | "no-bitwise": true, 49 | "no-console": [ 50 | true, 51 | "debug", 52 | "info", 53 | "time", 54 | "timeEnd", 55 | "trace" 56 | ], 57 | "no-construct": true, 58 | "no-debugger": true, 59 | "no-duplicate-super": true, 60 | "no-empty": false, 61 | "no-empty-interface": true, 62 | "no-eval": true, 63 | "no-inferrable-types": [ 64 | true, 65 | "ignore-params" 66 | ], 67 | "no-misused-new": true, 68 | "no-non-null-assertion": true, 69 | "no-shadowed-variable": true, 70 | "no-string-literal": false, 71 | "no-string-throw": true, 72 | "no-switch-case-fall-through": true, 73 | "no-trailing-whitespace": true, 74 | "no-unnecessary-initializer": true, 75 | "no-unused-expression": true, 76 | "no-use-before-declare": true, 77 | "no-var-keyword": true, 78 | "object-literal-sort-keys": false, 79 | "one-line": [ 80 | true, 81 | "check-open-brace", 82 | "check-catch", 83 | "check-else", 84 | "check-whitespace" 85 | ], 86 | "prefer-const": true, 87 | "quotemark": [ 88 | true, 89 | "single" 90 | ], 91 | "radix": true, 92 | "semicolon": [ 93 | true, 94 | "always" 95 | ], 96 | "triple-equals": [ 97 | true, 98 | "allow-null-check" 99 | ], 100 | "typedef-whitespace": [ 101 | true, 102 | { 103 | "call-signature": "nospace", 104 | "index-signature": "nospace", 105 | "parameter": "nospace", 106 | "property-declaration": "nospace", 107 | "variable-declaration": "nospace" 108 | } 109 | ], 110 | "typeof-compare": true, 111 | "unified-signatures": true, 112 | "variable-name": false, 113 | "whitespace": [ 114 | true, 115 | "check-branch", 116 | "check-decl", 117 | "check-operator", 118 | "check-separator", 119 | "check-type" 120 | ], 121 | "directive-selector": [ 122 | true, 123 | "attribute", 124 | "app", 125 | "camelCase" 126 | ], 127 | "component-selector": [ 128 | true, 129 | "element", 130 | "app", 131 | "kebab-case" 132 | ], 133 | "no-output-on-prefix": true, 134 | "use-input-property-decorator": true, 135 | "use-output-property-decorator": true, 136 | "use-host-property-decorator": true, 137 | "no-input-rename": true, 138 | "no-output-rename": true, 139 | "use-life-cycle-interface": true, 140 | "use-pipe-transform-interface": true, 141 | "component-class-suffix": true, 142 | "directive-class-suffix": true 143 | } 144 | } 145 | --------------------------------------------------------------------------------