[
  {
    "path": ".editorconfig",
    "content": "# Editor configuration, see https://editorconfig.org\nroot = true\n\n[*]\ncharset = utf-8\nindent_style = space\nindent_size = 2\ninsert_final_newline = true\ntrim_trailing_whitespace = true\n\n[*.md]\nmax_line_length = off\ntrim_trailing_whitespace = false\n"
  },
  {
    "path": ".gitignore",
    "content": "# See http://help.github.com/ignore-files/ for more about ignoring files.\n\n# compiled output\n/dist\n/tmp\n/out-tsc\n# Only exists if Bazel was run\n/bazel-out\n\n# dependencies\n/node_modules\n\n# profiling files\nchrome-profiler-events.json\nspeed-measure-plugin.json\n\n# IDEs and editors\n/.idea\n.project\n.classpath\n.c9/\n*.launch\n.settings/\n*.sublime-workspace\n\n# IDE - VSCode\n.vscode/*\n!.vscode/settings.json\n!.vscode/tasks.json\n!.vscode/launch.json\n!.vscode/extensions.json\n.history/*\n\n# misc\n/.sass-cache\n/connect.lock\n/coverage\n/libpeerconnection.log\nnpm-debug.log\nyarn-error.log\ntestem.log\n/typings\n\n# System Files\n.DS_Store\nThumbs.db\n"
  },
  {
    "path": "LICENSE",
    "content": "The MIT License (MIT)\n\nCopyright (c) 2019 Jason Watmore\n\nPermission is hereby granted, free of charge, to any person obtaining a copy\nof this software and associated documentation files (the \"Software\"), to deal\nin the Software without restriction, including without limitation the rights\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\ncopies of the Software, and to permit persons to whom the Software is\nfurnished to do so, subject to the following conditions:\n\nThe above copyright notice and this permission notice shall be included in all\ncopies or substantial portions of the Software.\n\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\nSOFTWARE.\n"
  },
  {
    "path": "README.md",
    "content": "# angular-8-jwt-authentication-example\n\nAngular 8 - JWT Authentication Example with the Angular CLI\n\nTo see a demo and further details go to https://jasonwatmore.com/post/2019/06/22/angular-8-jwt-authentication-example-tutorial"
  },
  {
    "path": "angular.json",
    "content": "{\n  \"$schema\": \"./node_modules/@angular/cli/lib/config/schema.json\",\n  \"version\": 1,\n  \"newProjectRoot\": \"projects\",\n  \"projects\": {\n    \"angular-8-jwt-authentication-example\": {\n      \"projectType\": \"application\",\n      \"schematics\": {\n        \"@schematics/angular:component\": {\n          \"style\": \"less\"\n        }\n      },\n      \"root\": \"\",\n      \"sourceRoot\": \"src\",\n      \"prefix\": \"app\",\n      \"architect\": {\n        \"build\": {\n          \"builder\": \"@angular-devkit/build-angular:browser\",\n          \"options\": {\n            \"outputPath\": \"dist\",\n            \"index\": \"src/index.html\",\n            \"main\": \"src/main.ts\",\n            \"polyfills\": \"src/polyfills.ts\",\n            \"tsConfig\": \"tsconfig.app.json\",\n            \"aot\": false,\n            \"assets\": [\n              \"src/favicon.ico\",\n              \"src/assets\"\n            ],\n            \"styles\": [\n              \"src/styles.less\"\n            ],\n            \"scripts\": []\n          },\n          \"configurations\": {\n            \"production\": {\n              \"fileReplacements\": [\n                {\n                  \"replace\": \"src/environments/environment.ts\",\n                  \"with\": \"src/environments/environment.prod.ts\"\n                }\n              ],\n              \"optimization\": true,\n              \"outputHashing\": \"all\",\n              \"sourceMap\": false,\n              \"extractCss\": true,\n              \"namedChunks\": false,\n              \"aot\": true,\n              \"extractLicenses\": true,\n              \"vendorChunk\": false,\n              \"buildOptimizer\": true,\n              \"budgets\": [\n                {\n                  \"type\": \"initial\",\n                  \"maximumWarning\": \"2mb\",\n                  \"maximumError\": \"5mb\"\n                }\n              ]\n            }\n          }\n        },\n        \"serve\": {\n          \"builder\": \"@angular-devkit/build-angular:dev-server\",\n          \"options\": {\n            \"browserTarget\": \"angular-8-jwt-authentication-example:build\"\n          },\n          \"configurations\": {\n            \"production\": {\n              \"browserTarget\": \"angular-8-jwt-authentication-example:build:production\"\n            }\n          }\n        },\n        \"extract-i18n\": {\n          \"builder\": \"@angular-devkit/build-angular:extract-i18n\",\n          \"options\": {\n            \"browserTarget\": \"angular-8-jwt-authentication-example:build\"\n          }\n        },\n        \"test\": {\n          \"builder\": \"@angular-devkit/build-angular:karma\",\n          \"options\": {\n            \"main\": \"src/test.ts\",\n            \"polyfills\": \"src/polyfills.ts\",\n            \"tsConfig\": \"tsconfig.spec.json\",\n            \"karmaConfig\": \"karma.conf.js\",\n            \"assets\": [\n              \"src/favicon.ico\",\n              \"src/assets\"\n            ],\n            \"styles\": [\n              \"src/styles.less\"\n            ],\n            \"scripts\": []\n          }\n        },\n        \"lint\": {\n          \"builder\": \"@angular-devkit/build-angular:tslint\",\n          \"options\": {\n            \"tsConfig\": [\n              \"tsconfig.app.json\",\n              \"tsconfig.spec.json\",\n              \"e2e/tsconfig.json\"\n            ],\n            \"exclude\": [\n              \"**/node_modules/**\"\n            ]\n          }\n        },\n        \"e2e\": {\n          \"builder\": \"@angular-devkit/build-angular:protractor\",\n          \"options\": {\n            \"protractorConfig\": \"e2e/protractor.conf.js\",\n            \"devServerTarget\": \"angular-8-jwt-authentication-example:serve\"\n          },\n          \"configurations\": {\n            \"production\": {\n              \"devServerTarget\": \"angular-8-jwt-authentication-example:serve:production\"\n            }\n          }\n        }\n      }\n    }},\n  \"defaultProject\": \"angular-8-jwt-authentication-example\"\n}"
  },
  {
    "path": "browserslist",
    "content": "# This file is used by the build system to adjust CSS and JS output to support the specified browsers below.\n# For additional information regarding the format and rule options, please see:\n# https://github.com/browserslist/browserslist#queries\n\n# You can see what browsers were selected by your queries by running:\n#   npx browserslist\n\n> 0.5%\nlast 2 versions\nFirefox ESR\nnot dead\nnot IE 9-11 # For IE 9-11 support, remove 'not'."
  },
  {
    "path": "e2e/protractor.conf.js",
    "content": "// @ts-check\n// Protractor configuration file, see link for more information\n// https://github.com/angular/protractor/blob/master/lib/config.ts\n\nconst { SpecReporter } = require('jasmine-spec-reporter');\n\n/**\n * @type { import(\"protractor\").Config }\n */\nexports.config = {\n  allScriptsTimeout: 11000,\n  specs: [\n    './src/**/*.e2e-spec.ts'\n  ],\n  capabilities: {\n    'browserName': 'chrome'\n  },\n  directConnect: true,\n  baseUrl: 'http://localhost:4200/',\n  framework: 'jasmine',\n  jasmineNodeOpts: {\n    showColors: true,\n    defaultTimeoutInterval: 30000,\n    print: function() {}\n  },\n  onPrepare() {\n    require('ts-node').register({\n      project: require('path').join(__dirname, './tsconfig.json')\n    });\n    jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } }));\n  }\n};"
  },
  {
    "path": "e2e/src/app.e2e-spec.ts",
    "content": "import { AppPage } from './app.po';\nimport { browser, logging } from 'protractor';\n\ndescribe('workspace-project App', () => {\n  let page: AppPage;\n\n  beforeEach(() => {\n    page = new AppPage();\n  });\n\n  it('should display welcome message', () => {\n    page.navigateTo();\n    expect(page.getTitleText()).toEqual('Welcome to angular-8-jwt-authentication-example!');\n  });\n\n  afterEach(async () => {\n    // Assert that there are no errors emitted from the browser\n    const logs = await browser.manage().logs().get(logging.Type.BROWSER);\n    expect(logs).not.toContain(jasmine.objectContaining({\n      level: logging.Level.SEVERE,\n    } as logging.Entry));\n  });\n});\n"
  },
  {
    "path": "e2e/src/app.po.ts",
    "content": "import { browser, by, element } from 'protractor';\n\nexport class AppPage {\n  navigateTo() {\n    return browser.get(browser.baseUrl) as Promise<any>;\n  }\n\n  getTitleText() {\n    return element(by.css('app-root h1')).getText() as Promise<string>;\n  }\n}\n"
  },
  {
    "path": "e2e/tsconfig.json",
    "content": "{\n  \"extends\": \"../tsconfig.json\",\n  \"compilerOptions\": {\n    \"outDir\": \"../out-tsc/e2e\",\n    \"module\": \"commonjs\",\n    \"target\": \"es5\",\n    \"types\": [\n      \"jasmine\",\n      \"jasminewd2\",\n      \"node\"\n    ]\n  }\n}\n"
  },
  {
    "path": "karma.conf.js",
    "content": "// Karma configuration file, see link for more information\n// https://karma-runner.github.io/1.0/config/configuration-file.html\n\nmodule.exports = function (config) {\n  config.set({\n    basePath: '',\n    frameworks: ['jasmine', '@angular-devkit/build-angular'],\n    plugins: [\n      require('karma-jasmine'),\n      require('karma-chrome-launcher'),\n      require('karma-jasmine-html-reporter'),\n      require('karma-coverage-istanbul-reporter'),\n      require('@angular-devkit/build-angular/plugins/karma')\n    ],\n    client: {\n      clearContext: false // leave Jasmine Spec Runner output visible in browser\n    },\n    coverageIstanbulReporter: {\n      dir: require('path').join(__dirname, './coverage/angular-8-jwt-authentication-example'),\n      reports: ['html', 'lcovonly', 'text-summary'],\n      fixWebpackSourcePaths: true\n    },\n    reporters: ['progress', 'kjhtml'],\n    port: 9876,\n    colors: true,\n    logLevel: config.LOG_INFO,\n    autoWatch: true,\n    browsers: ['Chrome'],\n    singleRun: false,\n    restartOnFileChange: true\n  });\n};\n"
  },
  {
    "path": "package.json",
    "content": "{\n    \"name\": \"angular-8-jwt-authentication-example\",\n    \"version\": \"1.0.0\",\n    \"scripts\": {\n        \"ng\": \"ng\",\n        \"start\": \"ng serve --open\",\n        \"build\": \"ng build\",\n        \"test\": \"ng test\",\n        \"lint\": \"ng lint\",\n        \"e2e\": \"ng e2e\"\n    },\n    \"private\": true,\n    \"license\": \"MIT\",\n    \"dependencies\": {\n        \"@angular/animations\": \"~8.0.1\",\n        \"@angular/common\": \"~8.0.1\",\n        \"@angular/compiler\": \"~8.0.1\",\n        \"@angular/core\": \"~8.0.1\",\n        \"@angular/forms\": \"~8.0.1\",\n        \"@angular/platform-browser\": \"~8.0.1\",\n        \"@angular/platform-browser-dynamic\": \"~8.0.1\",\n        \"@angular/router\": \"~8.0.1\",\n        \"rxjs\": \"~6.4.0\",\n        \"tslib\": \"^1.9.0\",\n        \"zone.js\": \"~0.9.1\"\n    },\n    \"devDependencies\": {\n        \"@angular-devkit/build-angular\": \"~0.800.0\",\n        \"@angular/cli\": \"~8.0.3\",\n        \"@angular/compiler-cli\": \"~8.0.1\",\n        \"@angular/language-service\": \"~8.0.1\",\n        \"@types/node\": \"~8.9.4\",\n        \"@types/jasmine\": \"~3.3.8\",\n        \"@types/jasminewd2\": \"~2.0.3\",\n        \"codelyzer\": \"^5.0.0\",\n        \"jasmine-core\": \"~3.4.0\",\n        \"jasmine-spec-reporter\": \"~4.2.1\",\n        \"karma\": \"~4.1.0\",\n        \"karma-chrome-launcher\": \"~2.2.0\",\n        \"karma-coverage-istanbul-reporter\": \"~2.0.1\",\n        \"karma-jasmine\": \"~2.0.1\",\n        \"karma-jasmine-html-reporter\": \"^1.4.0\",\n        \"protractor\": \"~5.4.0\",\n        \"ts-node\": \"~7.0.0\",\n        \"tslint\": \"~5.15.0\",\n        \"typescript\": \"~3.4.3\"\n    }\n}"
  },
  {
    "path": "src/app/_helpers/auth.guard.ts",
    "content": "﻿import { Injectable } from '@angular/core';\nimport { Router, CanActivate, ActivatedRouteSnapshot, RouterStateSnapshot } from '@angular/router';\n\nimport { AuthenticationService } from '@app/_services';\n\n@Injectable({ providedIn: 'root' })\nexport class AuthGuard implements CanActivate {\n    constructor(\n        private router: Router,\n        private authenticationService: AuthenticationService\n    ) { }\n\n    canActivate(route: ActivatedRouteSnapshot, state: RouterStateSnapshot) {\n        const currentUser = this.authenticationService.currentUserValue;\n        if (currentUser) {\n            // logged in so return true\n            return true;\n        }\n\n        // not logged in so redirect to login page with the return url\n        this.router.navigate(['/login'], { queryParams: { returnUrl: state.url } });\n        return false;\n    }\n}"
  },
  {
    "path": "src/app/_helpers/error.interceptor.ts",
    "content": "import { Injectable } from '@angular/core';\nimport { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';\nimport { Observable, throwError } from 'rxjs';\nimport { catchError } from 'rxjs/operators';\n\nimport { AuthenticationService } from '@app/_services';\n\n@Injectable()\nexport class ErrorInterceptor implements HttpInterceptor {\n    constructor(private authenticationService: AuthenticationService) { }\n\n    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n        return next.handle(request).pipe(catchError(err => {\n            if (err.status === 401) {\n                // auto logout if 401 response returned from api\n                this.authenticationService.logout();\n                location.reload(true);\n            }\n\n            const error = err.error.message || err.statusText;\n            return throwError(error);\n        }))\n    }\n}"
  },
  {
    "path": "src/app/_helpers/fake-backend.ts",
    "content": "﻿import { Injectable } from '@angular/core';\nimport { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http';\nimport { Observable, of, throwError } from 'rxjs';\nimport { delay, mergeMap, materialize, dematerialize } from 'rxjs/operators';\n\nimport { User } from '@app/_models';\n\nconst users: User[] = [{ id: 1, username: 'test', password: 'test', firstName: 'Test', lastName: 'User' }];\n\n@Injectable()\nexport class FakeBackendInterceptor implements HttpInterceptor {\n    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n        const { url, method, headers, body } = request;\n\n        // wrap in delayed observable to simulate server api call\n        return of(null)\n            .pipe(mergeMap(handleRoute))\n            .pipe(materialize()) // call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648)\n            .pipe(delay(500))\n            .pipe(dematerialize());\n\n        function handleRoute() {\n            switch (true) {\n                case url.endsWith('/users/authenticate') && method === 'POST':\n                    return authenticate();\n                case url.endsWith('/users') && method === 'GET':\n                    return getUsers();\n                default:\n                    // pass through any requests not handled above\n                    return next.handle(request);\n            }    \n        }\n\n        // route functions\n\n        function authenticate() {\n            const { username, password } = body;\n            const user = users.find(x => x.username === username && x.password === password);\n            if (!user) return error('Username or password is incorrect');\n            return ok({\n                id: user.id,\n                username: user.username,\n                firstName: user.firstName,\n                lastName: user.lastName,\n                token: 'fake-jwt-token'\n            })\n        }\n\n        function getUsers() {\n            if (!isLoggedIn()) return unauthorized();\n            return ok(users);\n        }\n\n        // helper functions\n\n        function ok(body?) {\n            return of(new HttpResponse({ status: 200, body }))\n        }\n\n        function error(message) {\n            return throwError({ error: { message } });\n        }\n\n        function unauthorized() {\n            return throwError({ status: 401, error: { message: 'Unauthorised' } });\n        }\n\n        function isLoggedIn() {\n            return headers.get('Authorization') === 'Bearer fake-jwt-token';\n        }\n    }\n}\n\nexport let fakeBackendProvider = {\n    // use fake backend in place of Http service for backend-less development\n    provide: HTTP_INTERCEPTORS,\n    useClass: FakeBackendInterceptor,\n    multi: true\n};"
  },
  {
    "path": "src/app/_helpers/index.ts",
    "content": "﻿export * from './auth.guard';\nexport * from './error.interceptor';\nexport * from './fake-backend';\nexport * from './jwt.interceptor';"
  },
  {
    "path": "src/app/_helpers/jwt.interceptor.ts",
    "content": "import { Injectable } from '@angular/core';\nimport { HttpRequest, HttpHandler, HttpEvent, HttpInterceptor } from '@angular/common/http';\nimport { Observable } from 'rxjs';\n\nimport { AuthenticationService } from '@app/_services';\n\n@Injectable()\nexport class JwtInterceptor implements HttpInterceptor {\n    constructor(private authenticationService: AuthenticationService) { }\n\n    intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {\n        // add authorization header with jwt token if available\n        let currentUser = this.authenticationService.currentUserValue;\n        if (currentUser && currentUser.token) {\n            request = request.clone({\n                setHeaders: {\n                    Authorization: `Bearer ${currentUser.token}`\n                }\n            });\n        }\n\n        return next.handle(request);\n    }\n}"
  },
  {
    "path": "src/app/_models/index.ts",
    "content": "﻿export * from './user';"
  },
  {
    "path": "src/app/_models/user.ts",
    "content": "﻿export class User {\n    id: number;\n    username: string;\n    password: string;\n    firstName: string;\n    lastName: string;\n    token?: string;\n}"
  },
  {
    "path": "src/app/_services/authentication.service.ts",
    "content": "﻿import { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\nimport { BehaviorSubject, Observable } from 'rxjs';\nimport { map } from 'rxjs/operators';\n\nimport { environment } from '@environments/environment';\nimport { User } from '@app/_models';\n\n@Injectable({ providedIn: 'root' })\nexport class AuthenticationService {\n    private currentUserSubject: BehaviorSubject<User>;\n    public currentUser: Observable<User>;\n\n    constructor(private http: HttpClient) {\n        this.currentUserSubject = new BehaviorSubject<User>(JSON.parse(localStorage.getItem('currentUser')));\n        this.currentUser = this.currentUserSubject.asObservable();\n    }\n\n    public get currentUserValue(): User {\n        return this.currentUserSubject.value;\n    }\n\n    login(username: string, password: string) {\n        return this.http.post<any>(`${environment.apiUrl}/users/authenticate`, { username, password })\n            .pipe(map(user => {\n                // store user details and jwt token in local storage to keep user logged in between page refreshes\n                localStorage.setItem('currentUser', JSON.stringify(user));\n                this.currentUserSubject.next(user);\n                return user;\n            }));\n    }\n\n    logout() {\n        // remove user from local storage to log user out\n        localStorage.removeItem('currentUser');\n        this.currentUserSubject.next(null);\n    }\n}"
  },
  {
    "path": "src/app/_services/index.ts",
    "content": "﻿export * from './authentication.service';\nexport * from './user.service';"
  },
  {
    "path": "src/app/_services/user.service.ts",
    "content": "﻿import { Injectable } from '@angular/core';\nimport { HttpClient } from '@angular/common/http';\n\nimport { environment } from '@environments/environment';\nimport { User } from '@app/_models';\n\n@Injectable({ providedIn: 'root' })\nexport class UserService {\n    constructor(private http: HttpClient) { }\n\n    getAll() {\n        return this.http.get<User[]>(`${environment.apiUrl}/users`);\n    }\n}"
  },
  {
    "path": "src/app/app.component.html",
    "content": "﻿<!-- nav -->\n<nav class=\"navbar navbar-expand navbar-dark bg-dark\" *ngIf=\"currentUser\">\n    <div class=\"navbar-nav\">\n        <a class=\"nav-item nav-link\" routerLink=\"/\">Home</a>\n        <a class=\"nav-item nav-link\" (click)=\"logout()\">Logout</a>\n    </div>\n</nav>\n\n<!-- main app container -->\n<div class=\"container\">\n    <router-outlet></router-outlet>\n</div>\n\n<!-- credits -->\n<div class=\"text-center mt-4\">\n    <p>\n        <a href=\"https://jasonwatmore.com/post/2019/06/22/angular-8-jwt-authentication-example-tutorial\" target=\"_top\">Angular 8 - JWT Authentication Example & Tutorial</a>\n    </p>\n    <p>\n        <a href=\"http://jasonwatmore.com\" target=\"_top\">JasonWatmore.com</a>\n    </p>\n</div>"
  },
  {
    "path": "src/app/app.component.ts",
    "content": "﻿import { Component } from '@angular/core';\nimport { Router } from '@angular/router';\n\nimport { AuthenticationService } from './_services';\nimport { User } from './_models';\n\n@Component({ selector: 'app', templateUrl: 'app.component.html' })\nexport class AppComponent {\n    currentUser: User;\n\n    constructor(\n        private router: Router,\n        private authenticationService: AuthenticationService\n    ) {\n        this.authenticationService.currentUser.subscribe(x => this.currentUser = x);\n    }\n\n    logout() {\n        this.authenticationService.logout();\n        this.router.navigate(['/login']);\n    }\n}"
  },
  {
    "path": "src/app/app.module.ts",
    "content": "﻿import { NgModule } from '@angular/core';\nimport { BrowserModule } from '@angular/platform-browser';\nimport { ReactiveFormsModule } from '@angular/forms';\nimport { HttpClientModule, HTTP_INTERCEPTORS } from '@angular/common/http';\n\n// used to create fake backend\nimport { fakeBackendProvider } from './_helpers';\n\nimport { AppComponent } from './app.component';\nimport { appRoutingModule } from './app.routing';\n\nimport { JwtInterceptor, ErrorInterceptor } from './_helpers';\nimport { HomeComponent } from './home';\nimport { LoginComponent } from './login';\n\n@NgModule({\n    imports: [\n        BrowserModule,\n        ReactiveFormsModule,\n        HttpClientModule,\n        appRoutingModule\n    ],\n    declarations: [\n        AppComponent,\n        HomeComponent,\n        LoginComponent\n    ],\n    providers: [\n        { provide: HTTP_INTERCEPTORS, useClass: JwtInterceptor, multi: true },\n        { provide: HTTP_INTERCEPTORS, useClass: ErrorInterceptor, multi: true },\n\n        // provider used to create fake backend\n        fakeBackendProvider\n    ],\n    bootstrap: [AppComponent]\n})\nexport class AppModule { }"
  },
  {
    "path": "src/app/app.routing.ts",
    "content": "﻿import { Routes, RouterModule } from '@angular/router';\n\nimport { HomeComponent } from './home';\nimport { LoginComponent } from './login';\nimport { AuthGuard } from './_helpers';\n\nconst routes: Routes = [\n    { path: '', component: HomeComponent, canActivate: [AuthGuard] },\n    { path: 'login', component: LoginComponent },\n\n    // otherwise redirect to home\n    { path: '**', redirectTo: '' }\n];\n\nexport const appRoutingModule = RouterModule.forRoot(routes);"
  },
  {
    "path": "src/app/home/home.component.html",
    "content": "﻿<div class=\"card mt-4\">\n    <h4 class=\"card-header\">You're logged in with Angular 8 & JWT!!</h4>\n    <div class=\"card-body\">\n        <h6>Users from secure api end point</h6>\n        <div *ngIf=\"loading\" class=\"spinner-border spinner-border-sm\"></div>\n        <ul *ngIf=\"users\">\n            <li *ngFor=\"let user of users\">{{user.firstName}} {{user.lastName}}</li>\n        </ul>\n    </div>\n</div>"
  },
  {
    "path": "src/app/home/home.component.ts",
    "content": "﻿import { Component } from '@angular/core';\nimport { first } from 'rxjs/operators';\n\nimport { User } from '@app/_models';\nimport { UserService, AuthenticationService } from '@app/_services';\n\n@Component({ templateUrl: 'home.component.html' })\nexport class HomeComponent {\n    loading = false;\n    users: User[];\n\n    constructor(private userService: UserService) { }\n\n    ngOnInit() {\n        this.loading = true;\n        this.userService.getAll().pipe(first()).subscribe(users => {\n            this.loading = false;\n            this.users = users;\n        });\n    }\n}"
  },
  {
    "path": "src/app/home/index.ts",
    "content": "﻿export * from './home.component';"
  },
  {
    "path": "src/app/login/index.ts",
    "content": "﻿export * from './login.component';"
  },
  {
    "path": "src/app/login/login.component.html",
    "content": "﻿<div class=\"col-md-6 offset-md-3 mt-5\">\n    <div class=\"alert alert-info\">\n        Username: test<br />\n        Password: test\n    </div>\n    <div class=\"card\">\n        <h4 class=\"card-header\">Angular 8 JWT Login Example</h4>\n        <div class=\"card-body\">\n            <form [formGroup]=\"loginForm\" (ngSubmit)=\"onSubmit()\">\n                <div class=\"form-group\">\n                    <label for=\"username\">Username</label>\n                    <input type=\"text\" formControlName=\"username\" class=\"form-control\" [ngClass]=\"{ 'is-invalid': submitted && f.username.errors }\" />\n                    <div *ngIf=\"submitted && f.username.errors\" class=\"invalid-feedback\">\n                        <div *ngIf=\"f.username.errors.required\">Username is required</div>\n                    </div>\n                </div>\n                <div class=\"form-group\">\n                    <label for=\"password\">Password</label>\n                    <input type=\"password\" formControlName=\"password\" class=\"form-control\" [ngClass]=\"{ 'is-invalid': submitted && f.password.errors }\" />\n                    <div *ngIf=\"submitted && f.password.errors\" class=\"invalid-feedback\">\n                        <div *ngIf=\"f.password.errors.required\">Password is required</div>\n                    </div>\n                </div>\n                <button [disabled]=\"loading\" class=\"btn btn-primary\">\n                    <span *ngIf=\"loading\" class=\"spinner-border spinner-border-sm mr-1\"></span>\n                    Login\n                </button>\n                <div *ngIf=\"error\" class=\"alert alert-danger mt-3 mb-0\">{{error}}</div>\n            </form>\n        </div>\n    </div>\n</div>"
  },
  {
    "path": "src/app/login/login.component.ts",
    "content": "﻿import { Component, OnInit } from '@angular/core';\nimport { Router, ActivatedRoute } from '@angular/router';\nimport { FormBuilder, FormGroup, Validators } from '@angular/forms';\nimport { first } from 'rxjs/operators';\n\nimport { AuthenticationService } from '@app/_services';\n\n@Component({ templateUrl: 'login.component.html' })\nexport class LoginComponent implements OnInit {\n    loginForm: FormGroup;\n    loading = false;\n    submitted = false;\n    returnUrl: string;\n    error = '';\n\n    constructor(\n        private formBuilder: FormBuilder,\n        private route: ActivatedRoute,\n        private router: Router,\n        private authenticationService: AuthenticationService\n    ) { \n        // redirect to home if already logged in\n        if (this.authenticationService.currentUserValue) { \n            this.router.navigate(['/']);\n        }\n    }\n\n    ngOnInit() {\n        this.loginForm = this.formBuilder.group({\n            username: ['', Validators.required],\n            password: ['', Validators.required]\n        });\n\n        // get return url from route parameters or default to '/'\n        this.returnUrl = this.route.snapshot.queryParams['returnUrl'] || '/';\n    }\n\n    // convenience getter for easy access to form fields\n    get f() { return this.loginForm.controls; }\n\n    onSubmit() {\n        this.submitted = true;\n\n        // stop here if form is invalid\n        if (this.loginForm.invalid) {\n            return;\n        }\n\n        this.loading = true;\n        this.authenticationService.login(this.f.username.value, this.f.password.value)\n            .pipe(first())\n            .subscribe(\n                data => {\n                    this.router.navigate([this.returnUrl]);\n                },\n                error => {\n                    this.error = error;\n                    this.loading = false;\n                });\n    }\n}\n"
  },
  {
    "path": "src/assets/.gitkeep",
    "content": ""
  },
  {
    "path": "src/environments/environment.prod.ts",
    "content": "export const environment = {\n    production: true,\n    apiUrl: 'http://localhost:4000'\n};\n"
  },
  {
    "path": "src/environments/environment.ts",
    "content": "// This file can be replaced during build by using the `fileReplacements` array.\n// `ng build --prod` replaces `environment.ts` with `environment.prod.ts`.\n// The list of file replacements can be found in `angular.json`.\n\nexport const environment = {\n    production: false,\n    apiUrl: 'http://localhost:4000'\n};\n\n/*\n * For easier debugging in development mode, you can import the following file\n * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`.\n *\n * This import should be commented out in production mode because it will have a negative impact\n * on performance if an error is thrown.\n */\n// import 'zone.js/dist/zone-error';  // Included with Angular CLI.\n"
  },
  {
    "path": "src/index.html",
    "content": "﻿<!DOCTYPE html>\n<html>\n<head>\n    <base href=\"/\" />\n    <title>Angular 8 - JWT Authentication Tutorial & Example</title>\n    <meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\n    <!-- bootstrap css -->\n    <link href=\"//netdna.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\" rel=\"stylesheet\" />\n</head>\n<body>\n    <app>Loading...</app>\n</body>\n</html>\n"
  },
  {
    "path": "src/main.ts",
    "content": "import { enableProdMode } from '@angular/core';\nimport { platformBrowserDynamic } from '@angular/platform-browser-dynamic';\n\nimport { AppModule } from './app/app.module';\nimport { environment } from './environments/environment';\n\nif (environment.production) {\n    enableProdMode();\n}\n\nplatformBrowserDynamic().bootstrapModule(AppModule)\n    .catch(err => console.error(err));\n"
  },
  {
    "path": "src/polyfills.ts",
    "content": "/**\n * This file includes polyfills needed by Angular and is loaded before the app.\n * You can add your own extra polyfills to this file.\n *\n * This file is divided into 2 sections:\n *   1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers.\n *   2. Application imports. Files imported after ZoneJS that should be loaded before your main\n *      file.\n *\n * The current setup is for so-called \"evergreen\" browsers; the last versions of browsers that\n * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera),\n * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile.\n *\n * Learn more in https://angular.io/guide/browser-support\n */\n\n/***************************************************************************************************\n * BROWSER POLYFILLS\n */\n\n/** IE10 and IE11 requires the following for NgClass support on SVG elements */\n// import 'classlist.js';  // Run `npm install --save classlist.js`.\n\n/**\n * Web Animations `@angular/platform-browser/animations`\n * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari.\n * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0).\n */\n// import 'web-animations-js';  // Run `npm install --save web-animations-js`.\n\n/**\n * By default, zone.js will patch all possible macroTask and DomEvents\n * user can disable parts of macroTask/DomEvents patch by setting following flags\n * because those flags need to be set before `zone.js` being loaded, and webpack\n * will put import in the top of bundle, so user need to create a separate file\n * in this directory (for example: zone-flags.ts), and put the following flags\n * into that file, and then add the following code before importing zone.js.\n * import './zone-flags.ts';\n *\n * The flags allowed in zone-flags.ts are listed here.\n *\n * The following flags will work for all browsers.\n *\n * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame\n * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick\n * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames\n *\n *  in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js\n *  with the following flag, it will bypass `zone.js` patch for IE/Edge\n *\n *  (window as any).__Zone_enable_cross_context_check = true;\n *\n */\n\n/***************************************************************************************************\n * Zone JS is required by default for Angular itself.\n */\nimport 'zone.js/dist/zone';  // Included with Angular CLI.\n\n\n/***************************************************************************************************\n * APPLICATION IMPORTS\n */\n"
  },
  {
    "path": "src/styles.less",
    "content": "/* You can add global styles to this file, and also import other style files */\na { cursor: pointer }"
  },
  {
    "path": "src/test.ts",
    "content": "// This file is required by karma.conf.js and loads recursively all the .spec and framework files\n\nimport 'zone.js/dist/zone-testing';\nimport { getTestBed } from '@angular/core/testing';\nimport {\n  BrowserDynamicTestingModule,\n  platformBrowserDynamicTesting\n} from '@angular/platform-browser-dynamic/testing';\n\ndeclare const require: any;\n\n// First, initialize the Angular testing environment.\ngetTestBed().initTestEnvironment(\n  BrowserDynamicTestingModule,\n  platformBrowserDynamicTesting()\n);\n// Then we find all the tests.\nconst context = require.context('./', true, /\\.spec\\.ts$/);\n// And load the modules.\ncontext.keys().map(context);\n"
  },
  {
    "path": "tsconfig.app.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": {\n    \"outDir\": \"./out-tsc/app\",\n    \"types\": []\n  },\n  \"include\": [\n    \"src/**/*.ts\"\n  ],\n  \"exclude\": [\n    \"src/test.ts\",\n    \"src/**/*.spec.ts\"\n  ]\n}\n"
  },
  {
    "path": "tsconfig.json",
    "content": "{\n    \"compileOnSave\": false,\n    \"compilerOptions\": {\n        \"baseUrl\": \"./\",\n        \"outDir\": \"./dist/out-tsc\",\n        \"sourceMap\": true,\n        \"declaration\": false,\n        \"downlevelIteration\": true,\n        \"emitDecoratorMetadata\": true,\n        \"experimentalDecorators\": true,\n        \"module\": \"esnext\",\n        \"moduleResolution\": \"node\",\n        \"importHelpers\": true,\n        \"target\": \"es2015\",\n        \"typeRoots\": [\n            \"node_modules/@types\"\n        ],\n        \"lib\": [\n            \"es2018\",\n            \"dom\"\n        ],\n        \"paths\": {\n            \"@app/*\": [\"src/app/*\"],\n            \"@environments/*\": [\"src/environments/*\"]\n        }\n    }\n}"
  },
  {
    "path": "tsconfig.spec.json",
    "content": "{\n  \"extends\": \"./tsconfig.json\",\n  \"compilerOptions\": {\n    \"outDir\": \"./out-tsc/spec\",\n    \"types\": [\n      \"jasmine\",\n      \"node\"\n    ]\n  },\n  \"files\": [\n    \"src/test.ts\",\n    \"src/polyfills.ts\"\n  ],\n  \"include\": [\n    \"src/**/*.spec.ts\",\n    \"src/**/*.d.ts\"\n  ]\n}\n"
  },
  {
    "path": "tslint.json",
    "content": "{\n  \"extends\": \"tslint:recommended\",\n  \"rules\": {\n    \"array-type\": false,\n    \"arrow-parens\": false,\n    \"deprecation\": {\n      \"severity\": \"warn\"\n    },\n    \"component-class-suffix\": true,\n    \"contextual-lifecycle\": true,\n    \"directive-class-suffix\": true,\n    \"directive-selector\": [\n      true,\n      \"attribute\",\n      \"app\",\n      \"camelCase\"\n    ],\n    \"component-selector\": [\n      true,\n      \"element\",\n      \"app\",\n      \"kebab-case\"\n    ],\n    \"import-blacklist\": [\n      true,\n      \"rxjs/Rx\"\n    ],\n    \"interface-name\": false,\n    \"max-classes-per-file\": false,\n    \"max-line-length\": [\n      true,\n      140\n    ],\n    \"member-access\": false,\n    \"member-ordering\": [\n      true,\n      {\n        \"order\": [\n          \"static-field\",\n          \"instance-field\",\n          \"static-method\",\n          \"instance-method\"\n        ]\n      }\n    ],\n    \"no-consecutive-blank-lines\": false,\n    \"no-console\": [\n      true,\n      \"debug\",\n      \"info\",\n      \"time\",\n      \"timeEnd\",\n      \"trace\"\n    ],\n    \"no-empty\": false,\n    \"no-inferrable-types\": [\n      true,\n      \"ignore-params\"\n    ],\n    \"no-non-null-assertion\": true,\n    \"no-redundant-jsdoc\": true,\n    \"no-switch-case-fall-through\": true,\n    \"no-use-before-declare\": true,\n    \"no-var-requires\": false,\n    \"object-literal-key-quotes\": [\n      true,\n      \"as-needed\"\n    ],\n    \"object-literal-sort-keys\": false,\n    \"ordered-imports\": false,\n    \"quotemark\": [\n      true,\n      \"single\"\n    ],\n    \"trailing-comma\": false,\n    \"no-conflicting-lifecycle\": true,\n    \"no-host-metadata-property\": true,\n    \"no-input-rename\": true,\n    \"no-inputs-metadata-property\": true,\n    \"no-output-native\": true,\n    \"no-output-on-prefix\": true,\n    \"no-output-rename\": true,\n    \"no-outputs-metadata-property\": true,\n    \"template-banana-in-box\": true,\n    \"template-no-negated-async\": true,\n    \"use-lifecycle-interface\": true,\n    \"use-pipe-transform-interface\": true\n  },\n  \"rulesDirectory\": [\n    \"codelyzer\"\n  ]\n}"
  }
]