├── .editorconfig ├── .gitignore ├── README.md ├── angular.json ├── browserslist ├── e2e ├── protractor.conf.js ├── src │ ├── app.e2e-spec.ts │ └── app.po.ts └── tsconfig.json ├── karma.conf.js ├── package-lock.json ├── package.json ├── src ├── app │ ├── admin │ │ ├── admin-routing.module.ts │ │ ├── admin.module.ts │ │ └── dashboard │ │ │ ├── dashboard.component.css │ │ │ ├── dashboard.component.html │ │ │ └── dashboard.component.ts │ ├── app-routing.guard.ts │ ├── app-routing.module.ts │ ├── app.module.ts │ ├── app │ │ ├── app.component.css │ │ ├── app.component.html │ │ └── app.component.ts │ ├── directives │ │ ├── user-role.directive.ts │ │ └── user.directive.ts │ ├── error │ │ └── not-found │ │ │ ├── not-found.component.css │ │ │ ├── not-found.component.html │ │ │ └── not-found.component.ts │ ├── home │ │ ├── home.component.css │ │ ├── home.component.html │ │ └── home.component.ts │ ├── login │ │ ├── login.component.css │ │ ├── login.component.html │ │ └── login.component.ts │ ├── models │ │ ├── role.ts │ │ └── user.ts │ ├── profile │ │ ├── profile.component.css │ │ ├── profile.component.html │ │ └── profile.component.ts │ └── services │ │ └── auth.service.ts ├── index.html ├── karma.conf.js ├── main.ts ├── polyfills.ts ├── styles.css ├── tsconfig.app.json └── tsconfig.spec.json ├── tsconfig.app.json ├── tsconfig.json ├── tsconfig.spec.json └── tslint.json /.editorconfig: -------------------------------------------------------------------------------- 1 | # Editor configuration, see https://editorconfig.org 2 | root = true 3 | 4 | [*] 5 | charset = utf-8 6 | indent_style = space 7 | indent_size = 2 8 | insert_final_newline = true 9 | trim_trailing_whitespace = true 10 | 11 | [*.md] 12 | max_line_length = off 13 | trim_trailing_whitespace = false 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # See http://help.github.com/ignore-files/ for more about ignoring files. 2 | 3 | # compiled output 4 | /dist 5 | /tmp 6 | /out-tsc 7 | # Only exists if Bazel was run 8 | /bazel-out 9 | 10 | # dependencies 11 | /node_modules 12 | 13 | # profiling files 14 | chrome-profiler-events.json 15 | speed-measure-plugin.json 16 | 17 | # IDEs and editors 18 | /.idea 19 | .project 20 | .classpath 21 | .c9/ 22 | *.launch 23 | .settings/ 24 | *.sublime-workspace 25 | 26 | # IDE - VSCode 27 | .vscode/* 28 | !.vscode/settings.json 29 | !.vscode/tasks.json 30 | !.vscode/launch.json 31 | !.vscode/extensions.json 32 | .history/* 33 | 34 | # misc 35 | /.sass-cache 36 | /connect.lock 37 | /coverage 38 | /libpeerconnection.log 39 | npm-debug.log 40 | yarn-error.log 41 | testem.log 42 | /typings 43 | 44 | # System Files 45 | .DS_Store 46 | Thumbs.db 47 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Angular 8 - Role-based authorization sample 2 | 3 | Tutorial and live demo: https://fsou1.github.io/Angular_8_role_based_authorization/ 4 | -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "ang-rba": { 7 | "projectType": "application", 8 | "schematics": {}, 9 | "root": "", 10 | "sourceRoot": "src", 11 | "prefix": "app", 12 | "architect": { 13 | "build": { 14 | "builder": "@angular-devkit/build-angular:browser", 15 | "options": { 16 | "outputPath": "dist/ang-rba", 17 | "index": "src/index.html", 18 | "main": "src/main.ts", 19 | "polyfills": "src/polyfills.ts", 20 | "tsConfig": "tsconfig.app.json", 21 | "aot": false, 22 | "assets": [ 23 | "src/favicon.ico", 24 | "src/assets" 25 | ], 26 | "styles": [ 27 | "src/styles.css" 28 | ], 29 | "scripts": [] 30 | }, 31 | "configurations": { 32 | "production": { 33 | "fileReplacements": [ 34 | { 35 | "replace": "src/environments/environment.ts", 36 | "with": "src/environments/environment.prod.ts" 37 | } 38 | ], 39 | "optimization": true, 40 | "outputHashing": "all", 41 | "sourceMap": false, 42 | "extractCss": true, 43 | "namedChunks": false, 44 | "aot": true, 45 | "extractLicenses": true, 46 | "vendorChunk": false, 47 | "buildOptimizer": true, 48 | "budgets": [ 49 | { 50 | "type": "initial", 51 | "maximumWarning": "2mb", 52 | "maximumError": "5mb" 53 | } 54 | ] 55 | } 56 | } 57 | }, 58 | "serve": { 59 | "builder": "@angular-devkit/build-angular:dev-server", 60 | "options": { 61 | "browserTarget": "ang-rba:build" 62 | }, 63 | "configurations": { 64 | "production": { 65 | "browserTarget": "ang-rba:build:production" 66 | } 67 | } 68 | }, 69 | "extract-i18n": { 70 | "builder": "@angular-devkit/build-angular:extract-i18n", 71 | "options": { 72 | "browserTarget": "ang-rba:build" 73 | } 74 | }, 75 | "test": { 76 | "builder": "@angular-devkit/build-angular:karma", 77 | "options": { 78 | "main": "src/test.ts", 79 | "polyfills": "src/polyfills.ts", 80 | "tsConfig": "tsconfig.spec.json", 81 | "karmaConfig": "karma.conf.js", 82 | "assets": [ 83 | "src/favicon.ico", 84 | "src/assets" 85 | ], 86 | "styles": [ 87 | "src/styles.css" 88 | ], 89 | "scripts": [] 90 | } 91 | }, 92 | "lint": { 93 | "builder": "@angular-devkit/build-angular:tslint", 94 | "options": { 95 | "tsConfig": [ 96 | "tsconfig.app.json", 97 | "tsconfig.spec.json", 98 | "e2e/tsconfig.json" 99 | ], 100 | "exclude": [ 101 | "**/node_modules/**" 102 | ] 103 | } 104 | }, 105 | "e2e": { 106 | "builder": "@angular-devkit/build-angular:protractor", 107 | "options": { 108 | "protractorConfig": "e2e/protractor.conf.js", 109 | "devServerTarget": "ang-rba:serve" 110 | }, 111 | "configurations": { 112 | "production": { 113 | "devServerTarget": "ang-rba:serve:production" 114 | } 115 | } 116 | } 117 | } 118 | }}, 119 | "defaultProject": "ang-rba" 120 | } -------------------------------------------------------------------------------- /browserslist: -------------------------------------------------------------------------------- 1 | # This file is used by the build system to adjust CSS and JS output to support the specified browsers below. 2 | # For additional information regarding the format and rule options, please see: 3 | # https://github.com/browserslist/browserslist#queries 4 | 5 | # You can see what browsers were selected by your queries by running: 6 | # npx browserslist 7 | 8 | > 0.5% 9 | last 2 versions 10 | Firefox ESR 11 | not dead 12 | not IE 9-11 # For IE 9-11 support, remove 'not'. -------------------------------------------------------------------------------- /e2e/protractor.conf.js: -------------------------------------------------------------------------------- 1 | // @ts-check 2 | // Protractor configuration file, see link for more information 3 | // https://github.com/angular/protractor/blob/master/lib/config.ts 4 | 5 | const { SpecReporter } = require('jasmine-spec-reporter'); 6 | 7 | /** 8 | * @type { import("protractor").Config } 9 | */ 10 | exports.config = { 11 | allScriptsTimeout: 11000, 12 | specs: [ 13 | './src/**/*.e2e-spec.ts' 14 | ], 15 | capabilities: { 16 | 'browserName': 'chrome' 17 | }, 18 | directConnect: true, 19 | baseUrl: 'http://localhost:4200/', 20 | framework: 'jasmine', 21 | jasmineNodeOpts: { 22 | showColors: true, 23 | defaultTimeoutInterval: 30000, 24 | print: function() {} 25 | }, 26 | onPrepare() { 27 | require('ts-node').register({ 28 | project: require('path').join(__dirname, './tsconfig.json') 29 | }); 30 | jasmine.getEnv().addReporter(new SpecReporter({ spec: { displayStacktrace: true } })); 31 | } 32 | }; -------------------------------------------------------------------------------- /e2e/src/app.e2e-spec.ts: -------------------------------------------------------------------------------- 1 | import { AppPage } from './app.po'; 2 | import { browser, logging } from 'protractor'; 3 | 4 | describe('workspace-project App', () => { 5 | let page: AppPage; 6 | 7 | beforeEach(() => { 8 | page = new AppPage(); 9 | }); 10 | 11 | it('should display welcome message', () => { 12 | page.navigateTo(); 13 | expect(page.getTitleText()).toEqual('Welcome to ang-rba!'); 14 | }); 15 | 16 | afterEach(async () => { 17 | // Assert that there are no errors emitted from the browser 18 | const logs = await browser.manage().logs().get(logging.Type.BROWSER); 19 | expect(logs).not.toContain(jasmine.objectContaining({ 20 | level: logging.Level.SEVERE, 21 | } as logging.Entry)); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /e2e/src/app.po.ts: -------------------------------------------------------------------------------- 1 | import { browser, by, element } from 'protractor'; 2 | 3 | export class AppPage { 4 | navigateTo() { 5 | return browser.get(browser.baseUrl) as Promise; 6 | } 7 | 8 | getTitleText() { 9 | return element(by.css('app-root h1')).getText() as Promise; 10 | } 11 | } 12 | -------------------------------------------------------------------------------- /e2e/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/e2e", 5 | "module": "commonjs", 6 | "target": "es5", 7 | "types": [ 8 | "jasmine", 9 | "jasminewd2", 10 | "node" 11 | ] 12 | } 13 | } 14 | -------------------------------------------------------------------------------- /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-devkit/build-angular'], 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-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, './coverage/ang-rba'), 20 | reports: ['html', 'lcovonly', 'text-summary'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false, 30 | restartOnFileChange: true 31 | }); 32 | }; 33 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "ang-rba", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "test": "ng test", 9 | "lint": "ng lint", 10 | "e2e": "ng e2e" 11 | }, 12 | "private": true, 13 | "dependencies": { 14 | "@angular/animations": "~8.1.1", 15 | "@angular/common": "~8.1.1", 16 | "@angular/compiler": "~8.1.1", 17 | "@angular/core": "~8.1.1", 18 | "@angular/forms": "~8.1.1", 19 | "@angular/platform-browser": "~8.1.1", 20 | "@angular/platform-browser-dynamic": "~8.1.1", 21 | "@angular/router": "~8.1.1", 22 | "rxjs": "~6.4.0", 23 | "tslib": "^1.9.0", 24 | "zone.js": "~0.9.1" 25 | }, 26 | "devDependencies": { 27 | "@angular-devkit/build-angular": "~0.801.1", 28 | "@angular/cli": "~8.1.1", 29 | "@angular/compiler-cli": "~8.1.1", 30 | "@angular/language-service": "~8.1.1", 31 | "@types/node": "~8.9.4", 32 | "@types/jasmine": "~3.3.8", 33 | "@types/jasminewd2": "~2.0.3", 34 | "codelyzer": "^5.0.0", 35 | "jasmine-core": "~3.4.0", 36 | "jasmine-spec-reporter": "~4.2.1", 37 | "karma": "~4.1.0", 38 | "karma-chrome-launcher": "~2.2.0", 39 | "karma-coverage-istanbul-reporter": "~2.0.1", 40 | "karma-jasmine": "~2.0.1", 41 | "karma-jasmine-html-reporter": "^1.4.0", 42 | "protractor": "~5.4.0", 43 | "ts-node": "~7.0.0", 44 | "tslint": "~5.15.0", 45 | "typescript": "~3.4.3" 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/app/admin/admin-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { Routes } from '@angular/router'; 2 | import { DashboardComponent } from './dashboard/dashboard.component'; 3 | 4 | export const routes: Routes = [ 5 | { path: 'dashboard', component: DashboardComponent } 6 | ]; 7 | -------------------------------------------------------------------------------- /src/app/admin/admin.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | 3 | import { DashboardComponent } from './dashboard/dashboard.component'; 4 | import { RouterModule } from '@angular/router'; 5 | import { routes } from './admin-routing.module'; 6 | 7 | @NgModule({ 8 | declarations: [ 9 | DashboardComponent 10 | ], 11 | imports: [ 12 | RouterModule.forChild(routes) 13 | ], 14 | providers: [] 15 | }) 16 | export class AdminModule { } 17 | -------------------------------------------------------------------------------- /src/app/admin/dashboard/dashboard.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FSou1/angular-8-role-based-authorization-sample/09b6a0992118d01163e1eaa5cd5b9c0610d7d05d/src/app/admin/dashboard/dashboard.component.css -------------------------------------------------------------------------------- /src/app/admin/dashboard/dashboard.component.html: -------------------------------------------------------------------------------- 1 | 4 | 5 | -------------------------------------------------------------------------------- /src/app/admin/dashboard/dashboard.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-dashboard', 5 | templateUrl: './dashboard.component.html', 6 | styleUrls: ['./dashboard.component.css'] 7 | }) 8 | export class DashboardComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit() { 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /src/app/app-routing.guard.ts: -------------------------------------------------------------------------------- 1 | import { CanActivate, Router, ActivatedRouteSnapshot, CanLoad, Route } from '@angular/router'; 2 | import { Observable } from 'rxjs'; 3 | import { Injectable } from '@angular/core'; 4 | import { AuthService } from './services/auth.service'; 5 | import { Role } from './models/role'; 6 | 7 | @Injectable() 8 | export class AuthGuard implements CanActivate, CanLoad { 9 | constructor( 10 | private router: Router, 11 | private authService: AuthService 12 | ) { } 13 | 14 | canActivate(route: ActivatedRouteSnapshot): Observable | Promise | boolean { 15 | if (!this.authService.isAuthorized()) { 16 | this.router.navigate(['login']); 17 | return false; 18 | } 19 | 20 | const roles = route.data.roles as Role[]; 21 | if (roles && !roles.some(r => this.authService.hasRole(r))) { 22 | this.router.navigate(['error', 'not-found']); 23 | return false; 24 | } 25 | 26 | return true; 27 | } 28 | 29 | canLoad(route: Route): Observable | Promise | boolean { 30 | if (!this.authService.isAuthorized()) { 31 | return false; 32 | } 33 | 34 | const roles = route.data && route.data.roles as Role[]; 35 | if (roles && !roles.some(r => this.authService.hasRole(r))) { 36 | return false; 37 | } 38 | 39 | return true; 40 | } 41 | } 42 | -------------------------------------------------------------------------------- /src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { Routes, RouterModule } from '@angular/router'; 3 | import { HomeComponent } from './home/home.component'; 4 | import { ProfileComponent } from './profile/profile.component'; 5 | import { NotFoundComponent } from './error/not-found/not-found.component'; 6 | import { AuthGuard } from './app-routing.guard'; 7 | import { AuthService } from './services/auth.service'; 8 | import { LoginComponent } from './login/login.component'; 9 | import { Role } from './models/role'; 10 | 11 | 12 | const routes: Routes = [ 13 | { 14 | path: '', 15 | children: [ 16 | { 17 | path: '', 18 | component: HomeComponent 19 | }, 20 | 21 | { 22 | path: 'profile', 23 | canActivate: [AuthGuard], 24 | component: ProfileComponent 25 | }, 26 | 27 | { 28 | path: 'login', 29 | component: LoginComponent 30 | } 31 | ] 32 | }, 33 | { 34 | path: 'admin', 35 | canLoad: [AuthGuard], 36 | canActivate: [AuthGuard], 37 | data: { 38 | roles: [ 39 | Role.Admin, 40 | ] 41 | }, 42 | loadChildren: () => import('./admin/admin.module').then(m => m.AdminModule) 43 | }, 44 | { 45 | path: '**', 46 | component: NotFoundComponent 47 | } 48 | ]; 49 | 50 | @NgModule({ 51 | imports: [RouterModule.forRoot(routes)], 52 | exports: [RouterModule], 53 | providers: [ 54 | AuthGuard, 55 | AuthService 56 | ] 57 | }) 58 | export class AppRoutingModule { } 59 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { BrowserModule } from '@angular/platform-browser'; 2 | import { NgModule } from '@angular/core'; 3 | 4 | import { AppRoutingModule } from './app-routing.module'; 5 | import { AppComponent } from './app/app.component'; 6 | import { HomeComponent } from './home/home.component'; 7 | import { ProfileComponent } from './profile/profile.component'; 8 | import { NotFoundComponent } from './error/not-found/not-found.component'; 9 | import { LoginComponent } from './login/login.component'; 10 | import { UserRoleDirective } from './directives/user-role.directive'; 11 | import { UserDirective } from './directives/user.directive'; 12 | import { AuthService } from './services/auth.service'; 13 | 14 | @NgModule({ 15 | declarations: [ 16 | AppComponent, 17 | HomeComponent, 18 | ProfileComponent, 19 | NotFoundComponent, 20 | LoginComponent, 21 | UserDirective, 22 | UserRoleDirective 23 | ], 24 | imports: [ 25 | BrowserModule, 26 | AppRoutingModule 27 | ], 28 | exports: [ 29 | UserDirective, 30 | UserRoleDirective 31 | ], 32 | providers: [AuthService], 33 | bootstrap: [AppComponent] 34 | }) 35 | export class AppModule { } 36 | -------------------------------------------------------------------------------- /src/app/app/app.component.css: -------------------------------------------------------------------------------- 1 | .badge { 2 | margin: 2px; 3 | } -------------------------------------------------------------------------------- /src/app/app/app.component.html: -------------------------------------------------------------------------------- 1 | 33 | 34 |
35 |
36 | 37 |
38 |
39 | 40 |
41 |

42 | @maximzhukov_dev, 2020 43 |

44 | 45 |

46 | Angular 8 - Role-based authorization with sample 47 |

48 |
-------------------------------------------------------------------------------- /src/app/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { Role } from '../models/role'; 4 | import { AuthService } from '../services/auth.service'; 5 | 6 | @Component({ 7 | selector: 'app-root', 8 | templateUrl: './app.component.html', 9 | styleUrls: ['./app.component.css'] 10 | }) 11 | export class AppComponent implements OnInit { 12 | Role = Role; 13 | 14 | constructor(private router: Router, private authService: AuthService) { } 15 | 16 | ngOnInit() { 17 | } 18 | 19 | get isAuthorized() { 20 | return this.authService.isAuthorized(); 21 | } 22 | 23 | get isAdmin() { 24 | return this.authService.hasRole(Role.Admin); 25 | } 26 | 27 | logout() { 28 | this.authService.logout(); 29 | this.router.navigate(['login']); 30 | } 31 | } 32 | -------------------------------------------------------------------------------- /src/app/directives/user-role.directive.ts: -------------------------------------------------------------------------------- 1 | import { Directive, OnInit, TemplateRef, ViewContainerRef, Input } from '@angular/core'; 2 | import { AuthService } from '../services/auth.service'; 3 | import { Role } from '../models/role'; 4 | 5 | @Directive({ selector: '[appUserRole]'}) 6 | export class UserRoleDirective implements OnInit { 7 | constructor( 8 | private templateRef: TemplateRef, 9 | private authService: AuthService, 10 | private viewContainer: ViewContainerRef 11 | ) { } 12 | 13 | userRoles: Role[]; 14 | 15 | @Input() 16 | set appUserRole(roles: Role[]) { 17 | if (!roles || !roles.length) { 18 | throw new Error('Roles value is empty or missed'); 19 | } 20 | 21 | this.userRoles = roles; 22 | } 23 | 24 | ngOnInit() { 25 | let hasAccess = false; 26 | 27 | if (this.authService.isAuthorized() && this.userRoles) { 28 | hasAccess = this.userRoles.some(r => this.authService.hasRole(r)); 29 | } 30 | 31 | if (hasAccess) { 32 | this.viewContainer.createEmbeddedView(this.templateRef); 33 | } else { 34 | this.viewContainer.clear(); 35 | } 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/app/directives/user.directive.ts: -------------------------------------------------------------------------------- 1 | import { Directive, OnInit, TemplateRef, ViewContainerRef, Input } from '@angular/core'; 2 | import { AuthService } from '../services/auth.service'; 3 | 4 | @Directive({ selector: '[appUser]'}) 5 | export class UserDirective implements OnInit { 6 | constructor( 7 | private templateRef: TemplateRef, 8 | private authService: AuthService, 9 | private viewContainer: ViewContainerRef 10 | ) { } 11 | 12 | ngOnInit() { 13 | const hasAccess = this.authService.isAuthorized(); 14 | 15 | if (hasAccess) { 16 | this.viewContainer.createEmbeddedView(this.templateRef); 17 | } else { 18 | this.viewContainer.clear(); 19 | } 20 | } 21 | } 22 | -------------------------------------------------------------------------------- /src/app/error/not-found/not-found.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FSou1/angular-8-role-based-authorization-sample/09b6a0992118d01163e1eaa5cd5b9c0610d7d05d/src/app/error/not-found/not-found.component.css -------------------------------------------------------------------------------- /src/app/error/not-found/not-found.component.html: -------------------------------------------------------------------------------- 1 |

2 | not-found works! 3 |

-------------------------------------------------------------------------------- /src/app/error/not-found/not-found.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-not-found', 5 | templateUrl: './not-found.component.html', 6 | styleUrls: ['./not-found.component.css'] 7 | }) 8 | export class NotFoundComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit() { 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /src/app/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FSou1/angular-8-role-based-authorization-sample/09b6a0992118d01163e1eaa5cd5b9c0610d7d05d/src/app/home/home.component.css -------------------------------------------------------------------------------- /src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 | -------------------------------------------------------------------------------- /src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | 3 | @Component({ 4 | selector: 'app-home', 5 | templateUrl: './home.component.html', 6 | styleUrls: ['./home.component.css'] 7 | }) 8 | export class HomeComponent implements OnInit { 9 | 10 | constructor() { } 11 | 12 | ngOnInit() { 13 | } 14 | 15 | } -------------------------------------------------------------------------------- /src/app/login/login.component.css: -------------------------------------------------------------------------------- 1 | button { 2 | margin: 0 2px; 3 | } -------------------------------------------------------------------------------- /src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 | 4 | 5 | 8 | 9 | -------------------------------------------------------------------------------- /src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Router } from '@angular/router'; 3 | import { Role } from '../models/role'; 4 | import { AuthService } from '../services/auth.service'; 5 | 6 | @Component({ 7 | selector: 'app-login', 8 | templateUrl: './login.component.html', 9 | styleUrls: ['./login.component.css'] 10 | }) 11 | export class LoginComponent implements OnInit { 12 | Role = Role; 13 | 14 | constructor(private router: Router, private authService: AuthService) { } 15 | 16 | ngOnInit() { 17 | } 18 | 19 | login(role: Role) { 20 | this.authService.login(role); 21 | this.router.navigate(['/']); 22 | } 23 | 24 | logout() { 25 | this.authService.logout(); 26 | } 27 | } -------------------------------------------------------------------------------- /src/app/models/role.ts: -------------------------------------------------------------------------------- 1 | export enum Role { 2 | User = 1, 3 | Admin = 2 4 | } 5 | -------------------------------------------------------------------------------- /src/app/models/user.ts: -------------------------------------------------------------------------------- 1 | import { Role } from './role'; 2 | 3 | export class User { 4 | Role: Role; 5 | } 6 | -------------------------------------------------------------------------------- /src/app/profile/profile.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FSou1/angular-8-role-based-authorization-sample/09b6a0992118d01163e1eaa5cd5b9c0610d7d05d/src/app/profile/profile.component.css -------------------------------------------------------------------------------- /src/app/profile/profile.component.html: -------------------------------------------------------------------------------- 1 | 4 | 5 | 8 | 9 | -------------------------------------------------------------------------------- /src/app/profile/profile.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { Role } from '../models/role'; 3 | 4 | @Component({ 5 | selector: 'app-profile', 6 | templateUrl: './profile.component.html', 7 | styleUrls: ['./profile.component.css'] 8 | }) 9 | export class ProfileComponent implements OnInit { 10 | Role = Role; 11 | 12 | constructor() { } 13 | 14 | ngOnInit() { 15 | } 16 | 17 | } -------------------------------------------------------------------------------- /src/app/services/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { User } from '../models/user'; 3 | import { Role } from '../models/role'; 4 | 5 | @Injectable() 6 | export class AuthService { 7 | private user: User; 8 | 9 | isAuthorized() { 10 | return !!this.user; 11 | } 12 | 13 | hasRole(role: Role) { 14 | return this.isAuthorized() && this.user.Role === role; 15 | } 16 | 17 | login(role: Role) { 18 | this.user = { Role: role }; 19 | } 20 | 21 | logout() { 22 | this.user = null; 23 | } 24 | } 25 | -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | RolesAngular 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /src/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-devkit/build-angular'], 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-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | clearContext: false // leave Jasmine Spec Runner output visible in browser 17 | }, 18 | coverageIstanbulReporter: { 19 | dir: require('path').join(__dirname, '../coverage'), 20 | reports: ['html', 'lcovonly'], 21 | fixWebpackSourcePaths: true 22 | }, 23 | reporters: ['progress', 'kjhtml'], 24 | port: 9876, 25 | colors: true, 26 | logLevel: config.LOG_INFO, 27 | autoWatch: true, 28 | browsers: ['Chrome'], 29 | singleRun: false 30 | }); 31 | }; -------------------------------------------------------------------------------- /src/main.ts: -------------------------------------------------------------------------------- 1 | import './polyfills'; 2 | 3 | import { enableProdMode } from '@angular/core'; 4 | import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; 5 | import { AppModule } from './app/app.module'; 6 | 7 | platformBrowserDynamic().bootstrapModule(AppModule).then(ref => { 8 | // Ensure Angular destroys itself on hot reloads. 9 | if (window['ngRef']) { 10 | window['ngRef'].destroy(); 11 | } 12 | window['ngRef'] = ref; 13 | 14 | // Otherwise, log the boot error 15 | }).catch(err => console.error(err)); -------------------------------------------------------------------------------- /src/polyfills.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * This file includes polyfills needed by Angular and is loaded before the app. 3 | * You can add your own extra polyfills to this file. 4 | * 5 | * This file is divided into 2 sections: 6 | * 1. Browser polyfills. These are applied before loading ZoneJS and are sorted by browsers. 7 | * 2. Application imports. Files imported after ZoneJS that should be loaded before your main 8 | * file. 9 | * 10 | * The current setup is for so-called "evergreen" browsers; the last versions of browsers that 11 | * automatically update themselves. This includes Safari >= 10, Chrome >= 55 (including Opera), 12 | * Edge >= 13 on the desktop, and iOS 10 and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/docs/ts/latest/guide/browser-support.html 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** IE9, IE10 and IE11 requires all of the following polyfills. **/ 22 | // import 'core-js/es6/symbol'; 23 | // import 'core-js/es6/object'; 24 | // import 'core-js/es6/function'; 25 | // import 'core-js/es6/parse-int'; 26 | // import 'core-js/es6/parse-float'; 27 | // import 'core-js/es6/number'; 28 | // import 'core-js/es6/math'; 29 | // import 'core-js/es6/string'; 30 | // import 'core-js/es6/date'; 31 | // import 'core-js/es6/array'; 32 | // import 'core-js/es6/regexp'; 33 | // import 'core-js/es6/map'; 34 | // import 'core-js/es6/set'; 35 | 36 | /** IE10 and IE11 requires the following for NgClass support on SVG elements */ 37 | // import 'classlist.js'; // Run `npm install --save classlist.js`. 38 | 39 | /** IE10 and IE11 requires the following to support `@angular/animation`. */ 40 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 41 | 42 | 43 | /** Evergreen browsers require these. **/ 44 | // import 'core-js/es6/reflect'; 45 | // import 'core-js/es7/reflect'; 46 | 47 | 48 | /** 49 | * Web Animations `@angular/platform-browser/animations` 50 | * Only required if AnimationBuilder is used within the application and using IE/Edge or Safari. 51 | * Standard animation support in Angular DOES NOT require any polyfills (as of Angular 6.0). 52 | */ 53 | // import 'web-animations-js'; // Run `npm install --save web-animations-js`. 54 | 55 | 56 | 57 | /*************************************************************************************************** 58 | * Zone JS is required by Angular itself. 59 | */ 60 | import 'zone.js/dist/zone'; // Included with Angular CLI. 61 | 62 | 63 | /*************************************************************************************************** 64 | * APPLICATION IMPORTS 65 | */ 66 | 67 | /** 68 | * Date, currency, decimal and percent pipes. 69 | * Needed for: All but Chrome, Firefox, Edge, IE11 and Safari 10 70 | */ 71 | // import 'intl'; // Run `npm install --save intl`. -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/FSou1/angular-8-role-based-authorization-sample/09b6a0992118d01163e1eaa5cd5b9c0610d7d05d/src/styles.css -------------------------------------------------------------------------------- /src/tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/app", 5 | "types": [] 6 | }, 7 | "exclude": [ 8 | "test.ts", 9 | "**/*.spec.ts" 10 | ] 11 | } -------------------------------------------------------------------------------- /src/tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "../tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "../out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "test.ts", 12 | "polyfills.ts" 13 | ], 14 | "include": [ 15 | "**/*.spec.ts", 16 | "**/*.d.ts" 17 | ] 18 | } -------------------------------------------------------------------------------- /tsconfig.app.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/app", 5 | "types": [] 6 | }, 7 | "include": [ 8 | "src/**/*.ts" 9 | ], 10 | "exclude": [ 11 | "src/test.ts", 12 | "src/**/*.spec.ts" 13 | ] 14 | } 15 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "compileOnSave": false, 3 | "compilerOptions": { 4 | "baseUrl": "./", 5 | "outDir": "./dist/out-tsc", 6 | "sourceMap": true, 7 | "declaration": false, 8 | "downlevelIteration": true, 9 | "experimentalDecorators": true, 10 | "module": "esnext", 11 | "moduleResolution": "node", 12 | "importHelpers": true, 13 | "target": "es2015", 14 | "typeRoots": [ 15 | "node_modules/@types" 16 | ], 17 | "lib": [ 18 | "es2018", 19 | "dom" 20 | ] 21 | }, 22 | "angularCompilerOptions": { 23 | "fullTemplateTypeCheck": true, 24 | "strictInjectionParameters": true 25 | } 26 | } 27 | -------------------------------------------------------------------------------- /tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./tsconfig.json", 3 | "compilerOptions": { 4 | "outDir": "./out-tsc/spec", 5 | "types": [ 6 | "jasmine", 7 | "node" 8 | ] 9 | }, 10 | "files": [ 11 | "src/test.ts", 12 | "src/polyfills.ts" 13 | ], 14 | "include": [ 15 | "src/**/*.spec.ts", 16 | "src/**/*.d.ts" 17 | ] 18 | } 19 | -------------------------------------------------------------------------------- /tslint.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "tslint:recommended", 3 | "rules": { 4 | "array-type": false, 5 | "arrow-parens": false, 6 | "deprecation": { 7 | "severity": "warning" 8 | }, 9 | "component-class-suffix": true, 10 | "contextual-lifecycle": true, 11 | "directive-class-suffix": true, 12 | "directive-selector": [ 13 | true, 14 | "attribute", 15 | "app", 16 | "camelCase" 17 | ], 18 | "component-selector": [ 19 | true, 20 | "element", 21 | "app", 22 | "kebab-case" 23 | ], 24 | "import-blacklist": [ 25 | true, 26 | "rxjs/Rx" 27 | ], 28 | "interface-name": false, 29 | "max-classes-per-file": false, 30 | "max-line-length": [ 31 | true, 32 | 140 33 | ], 34 | "member-access": false, 35 | "member-ordering": [ 36 | true, 37 | { 38 | "order": [ 39 | "static-field", 40 | "instance-field", 41 | "static-method", 42 | "instance-method" 43 | ] 44 | } 45 | ], 46 | "no-consecutive-blank-lines": false, 47 | "no-console": [ 48 | true, 49 | "debug", 50 | "info", 51 | "time", 52 | "timeEnd", 53 | "trace" 54 | ], 55 | "no-empty": false, 56 | "no-inferrable-types": [ 57 | true, 58 | "ignore-params" 59 | ], 60 | "no-non-null-assertion": true, 61 | "no-redundant-jsdoc": true, 62 | "no-switch-case-fall-through": true, 63 | "no-use-before-declare": true, 64 | "no-var-requires": false, 65 | "object-literal-key-quotes": [ 66 | true, 67 | "as-needed" 68 | ], 69 | "object-literal-sort-keys": false, 70 | "ordered-imports": false, 71 | "quotemark": [ 72 | true, 73 | "single" 74 | ], 75 | "trailing-comma": false, 76 | "no-conflicting-lifecycle": true, 77 | "no-host-metadata-property": true, 78 | "no-input-rename": true, 79 | "no-inputs-metadata-property": true, 80 | "no-output-native": true, 81 | "no-output-on-prefix": true, 82 | "no-output-rename": true, 83 | "no-outputs-metadata-property": true, 84 | "template-banana-in-box": true, 85 | "template-no-negated-async": true, 86 | "use-lifecycle-interface": true, 87 | "use-pipe-transform-interface": true 88 | }, 89 | "rulesDirectory": [ 90 | "codelyzer" 91 | ] 92 | } --------------------------------------------------------------------------------