├── .browserslistrc ├── .editorconfig ├── .gitignore ├── .vscode ├── extensions.json ├── launch.json └── tasks.json ├── README.md ├── angular-14-refresh-token-jwt-interceptor-example.png ├── angular.json ├── karma.conf.js ├── package-lock.json ├── package.json ├── src ├── app │ ├── _helpers │ │ └── http.interceptor.ts │ ├── _services │ │ ├── auth.service.spec.ts │ │ ├── auth.service.ts │ │ ├── storage.service.spec.ts │ │ ├── storage.service.ts │ │ ├── user.service.spec.ts │ │ └── user.service.ts │ ├── _shared │ │ ├── event-bus.service.spec.ts │ │ ├── event-bus.service.ts │ │ └── event.class.ts │ ├── app-routing.module.ts │ ├── app.component.css │ ├── app.component.html │ ├── app.component.spec.ts │ ├── app.component.ts │ ├── app.module.ts │ ├── board-admin │ │ ├── board-admin.component.css │ │ ├── board-admin.component.html │ │ ├── board-admin.component.spec.ts │ │ └── board-admin.component.ts │ ├── board-moderator │ │ ├── board-moderator.component.css │ │ ├── board-moderator.component.html │ │ ├── board-moderator.component.spec.ts │ │ └── board-moderator.component.ts │ ├── board-user │ │ ├── board-user.component.css │ │ ├── board-user.component.html │ │ ├── board-user.component.spec.ts │ │ └── board-user.component.ts │ ├── home │ │ ├── home.component.css │ │ ├── home.component.html │ │ ├── home.component.spec.ts │ │ └── home.component.ts │ ├── login │ │ ├── login.component.css │ │ ├── login.component.html │ │ ├── login.component.spec.ts │ │ └── login.component.ts │ ├── profile │ │ ├── profile.component.css │ │ ├── profile.component.html │ │ ├── profile.component.spec.ts │ │ └── profile.component.ts │ └── register │ │ ├── register.component.css │ │ ├── register.component.html │ │ ├── register.component.spec.ts │ │ └── register.component.ts ├── assets │ └── .gitkeep ├── environments │ ├── environment.prod.ts │ └── environment.ts ├── favicon.ico ├── index.html ├── main.ts ├── polyfills.ts ├── styles.css └── test.ts ├── tsconfig.app.json ├── tsconfig.json └── tsconfig.spec.json /.browserslistrc: -------------------------------------------------------------------------------- 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 | # For the full list of supported browsers by the Angular framework, please see: 6 | # https://angular.io/guide/browser-support 7 | 8 | # You can see what browsers were selected by your queries by running: 9 | # npx browserslist 10 | 11 | last 1 Chrome version 12 | last 1 Firefox version 13 | last 2 Edge major versions 14 | last 2 Safari major versions 15 | last 2 iOS major versions 16 | Firefox ESR 17 | -------------------------------------------------------------------------------- /.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 | [*.ts] 12 | quote_type = single 13 | 14 | [*.md] 15 | max_line_length = off 16 | trim_trailing_whitespace = false 17 | -------------------------------------------------------------------------------- /.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 | /bazel-out 8 | 9 | # Node 10 | /node_modules 11 | npm-debug.log 12 | yarn-error.log 13 | 14 | # IDEs and editors 15 | .idea/ 16 | .project 17 | .classpath 18 | .c9/ 19 | *.launch 20 | .settings/ 21 | *.sublime-workspace 22 | 23 | # Visual Studio Code 24 | .vscode/* 25 | !.vscode/settings.json 26 | !.vscode/tasks.json 27 | !.vscode/launch.json 28 | !.vscode/extensions.json 29 | .history/* 30 | 31 | # Miscellaneous 32 | /.angular/cache 33 | .sass-cache/ 34 | /connect.lock 35 | /coverage 36 | /libpeerconnection.log 37 | testem.log 38 | /typings 39 | 40 | # System files 41 | .DS_Store 42 | Thumbs.db 43 | -------------------------------------------------------------------------------- /.vscode/extensions.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=827846 3 | "recommendations": ["angular.ng-template"] 4 | } 5 | -------------------------------------------------------------------------------- /.vscode/launch.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?linkid=830387 3 | "version": "0.2.0", 4 | "configurations": [ 5 | { 6 | "name": "ng serve", 7 | "type": "pwa-chrome", 8 | "request": "launch", 9 | "preLaunchTask": "npm: start", 10 | "url": "http://localhost:4200/" 11 | }, 12 | { 13 | "name": "ng test", 14 | "type": "chrome", 15 | "request": "launch", 16 | "preLaunchTask": "npm: test", 17 | "url": "http://localhost:9876/debug.html" 18 | } 19 | ] 20 | } 21 | -------------------------------------------------------------------------------- /.vscode/tasks.json: -------------------------------------------------------------------------------- 1 | { 2 | // For more information, visit: https://go.microsoft.com/fwlink/?LinkId=733558 3 | "version": "2.0.0", 4 | "tasks": [ 5 | { 6 | "type": "npm", 7 | "script": "start", 8 | "isBackground": true, 9 | "problemMatcher": { 10 | "owner": "typescript", 11 | "pattern": "$tsc", 12 | "background": { 13 | "activeOnStart": true, 14 | "beginsPattern": { 15 | "regexp": "(.*?)" 16 | }, 17 | "endsPattern": { 18 | "regexp": "bundle generation complete" 19 | } 20 | } 21 | } 22 | }, 23 | { 24 | "type": "npm", 25 | "script": "test", 26 | "isBackground": true, 27 | "problemMatcher": { 28 | "owner": "typescript", 29 | "pattern": "$tsc", 30 | "background": { 31 | "activeOnStart": true, 32 | "beginsPattern": { 33 | "regexp": "(.*?)" 34 | }, 35 | "endsPattern": { 36 | "regexp": "bundle generation complete" 37 | } 38 | } 39 | } 40 | } 41 | ] 42 | } 43 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Angular 14 JWT Refresh Token example with Http Interceptor 2 | 3 | Implementing Angular 14 Refresh Token before Expiration with Http Interceptor and JWT. 4 | You can take a look at following flow to have an overview of Requests and Responses that Angular 14 Client will make or receive. 5 | 6 | ## Angular JWT Refresh Token Flow 7 | ![angular-14-refresh-token-jwt-interceptor-example](angular-14-refresh-token-jwt-interceptor-example.png) 8 | 9 | For more detail, please visit: 10 | > [Angular 14 Refresh Token with Interceptor and JWT example](https://www.bezkoder.com/angular-14-refresh-token/) 11 | 12 | > [Angular 14 JWT Authentication & Authorization with Web API example](https://www.bezkoder.com/angular-14-jwt-auth/) 13 | 14 | ## Fullstack 15 | > [Angular 14 + Spring Boot: JWT Authentication and Authorization example](https://www.bezkoder.com/angular-14-spring-boot-jwt-auth/) 16 | 17 | > [Angular 14 + Node.js Express: JWT Authentication and Authorization example](https://www.bezkoder.com/node-js-angular-14-jwt-auth/) 18 | 19 | Run `ng serve --port 8081` for a dev server. Navigate to `http://localhost:8081/`. 20 | 21 | ## More practice 22 | > [Angular CRUD example with Web API](https://www.bezkoder.com/angular-14-crud-example/) 23 | 24 | > [Angular Pagination example](https://www.bezkoder.com/angular-14-pagination-ngx/) 25 | 26 | > [Angular File upload example with Progress bar](https://www.bezkoder.com/angular-14-file-upload/) 27 | 28 | Fullstack with Node: 29 | 30 | > [Angular + Node Express + MySQL example](https://www.bezkoder.com/angular-14-node-js-express-mysql/) 31 | 32 | > [Angular + Node Express + PostgreSQL example](https://www.bezkoder.com/angular-14-node-js-express-postgresql/) 33 | 34 | > [Angular + Node Express + MongoDB example](https://www.bezkoder.com/mean-stack-crud-example-angular-14/) 35 | 36 | > [Angular + Node Express: File upload example](https://www.bezkoder.com/angular-14-node-express-file-upload/) 37 | 38 | Fullstack with Spring Boot: 39 | 40 | > [Angular + Spring Boot + H2 Embedded Database example](https://www.bezkoder.com/spring-boot-angular-14-crud/) 41 | 42 | > [Angular + Spring Boot + MySQL example](https://www.bezkoder.com/spring-boot-angular-14-mysql/) 43 | 44 | > [Angular + Spring Boot + PostgreSQL example](https://www.bezkoder.com/spring-boot-angular-14-postgresql//) 45 | 46 | > [Angular + Spring Boot + MongoDB example](https://www.bezkoder.com/spring-boot-angular-14-mongodb/) 47 | 48 | > [Angular + Spring Boot: File upload example](https://www.bezkoder.com/angular-14-spring-boot-file-upload/) 49 | 50 | Fullstack with Django: 51 | > [Angular + Django example](https://www.bezkoder.com/django-angular-13-crud-rest-framework/) 52 | 53 | Serverless with Firebase: 54 | > [Angular 14 Firebase CRUD with Realtime DataBase](https://www.bezkoder.com/angular-14-firebase-crud/) 55 | 56 | > [Angular 14 Firestore CRUD example](https://www.bezkoder.com/angular-14-firestore-crud/) 57 | 58 | > [Angular 14 Firebase Storage: File Upload/Display/Delete example](https://www.bezkoder.com/angular-14-firebase-storage/) 59 | 60 | Integration (run back-end & front-end on same server/port) 61 | > [How to integrate Angular with Node Restful Services](https://www.bezkoder.com/integrate-angular-12-node-js/) 62 | 63 | > [How to Integrate Angular with Spring Boot Rest API](https://www.bezkoder.com/integrate-angular-12-spring-boot/) 64 | -------------------------------------------------------------------------------- /angular-14-refresh-token-jwt-interceptor-example.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-14-refresh-token/f2c1191481ac7feec644dad6ce026a13afbd1074/angular-14-refresh-token-jwt-interceptor-example.png -------------------------------------------------------------------------------- /angular.json: -------------------------------------------------------------------------------- 1 | { 2 | "$schema": "./node_modules/@angular/cli/lib/config/schema.json", 3 | "version": 1, 4 | "newProjectRoot": "projects", 5 | "projects": { 6 | "angular-14-refresh-token": { 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/angular-14-refresh-token", 17 | "index": "src/index.html", 18 | "main": "src/main.ts", 19 | "polyfills": "src/polyfills.ts", 20 | "tsConfig": "tsconfig.app.json", 21 | "assets": [ 22 | "src/favicon.ico", 23 | "src/assets" 24 | ], 25 | "styles": [ 26 | "src/styles.css" 27 | ], 28 | "scripts": [] 29 | }, 30 | "configurations": { 31 | "production": { 32 | "budgets": [ 33 | { 34 | "type": "initial", 35 | "maximumWarning": "500kb", 36 | "maximumError": "1mb" 37 | }, 38 | { 39 | "type": "anyComponentStyle", 40 | "maximumWarning": "2kb", 41 | "maximumError": "4kb" 42 | } 43 | ], 44 | "fileReplacements": [ 45 | { 46 | "replace": "src/environments/environment.ts", 47 | "with": "src/environments/environment.prod.ts" 48 | } 49 | ], 50 | "outputHashing": "all" 51 | }, 52 | "development": { 53 | "buildOptimizer": false, 54 | "optimization": false, 55 | "vendorChunk": true, 56 | "extractLicenses": false, 57 | "sourceMap": true, 58 | "namedChunks": true 59 | } 60 | }, 61 | "defaultConfiguration": "production" 62 | }, 63 | "serve": { 64 | "builder": "@angular-devkit/build-angular:dev-server", 65 | "configurations": { 66 | "production": { 67 | "browserTarget": "angular-14-refresh-token:build:production" 68 | }, 69 | "development": { 70 | "browserTarget": "angular-14-refresh-token:build:development" 71 | } 72 | }, 73 | "defaultConfiguration": "development" 74 | }, 75 | "extract-i18n": { 76 | "builder": "@angular-devkit/build-angular:extract-i18n", 77 | "options": { 78 | "browserTarget": "angular-14-refresh-token:build" 79 | } 80 | }, 81 | "test": { 82 | "builder": "@angular-devkit/build-angular:karma", 83 | "options": { 84 | "main": "src/test.ts", 85 | "polyfills": "src/polyfills.ts", 86 | "tsConfig": "tsconfig.spec.json", 87 | "karmaConfig": "karma.conf.js", 88 | "assets": [ 89 | "src/favicon.ico", 90 | "src/assets" 91 | ], 92 | "styles": [ 93 | "src/styles.css" 94 | ], 95 | "scripts": [] 96 | } 97 | } 98 | } 99 | } 100 | } 101 | } 102 | -------------------------------------------------------------------------------- /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'), 13 | require('@angular-devkit/build-angular/plugins/karma') 14 | ], 15 | client: { 16 | jasmine: { 17 | // you can add configuration options for Jasmine here 18 | // the possible options are listed at https://jasmine.github.io/api/edge/Configuration.html 19 | // for example, you can disable the random execution with `random: false` 20 | // or set a specific seed with `seed: 4321` 21 | }, 22 | clearContext: false // leave Jasmine Spec Runner output visible in browser 23 | }, 24 | jasmineHtmlReporter: { 25 | suppressAll: true // removes the duplicated traces 26 | }, 27 | coverageReporter: { 28 | dir: require('path').join(__dirname, './coverage/angular-14-refresh-token'), 29 | subdir: '.', 30 | reporters: [ 31 | { type: 'html' }, 32 | { type: 'text-summary' } 33 | ] 34 | }, 35 | reporters: ['progress', 'kjhtml'], 36 | port: 9876, 37 | colors: true, 38 | logLevel: config.LOG_INFO, 39 | autoWatch: true, 40 | browsers: ['Chrome'], 41 | singleRun: false, 42 | restartOnFileChange: true 43 | }); 44 | }; 45 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "angular-14-refresh-token", 3 | "version": "0.0.0", 4 | "scripts": { 5 | "ng": "ng", 6 | "start": "ng serve", 7 | "build": "ng build", 8 | "watch": "ng build --watch --configuration development", 9 | "test": "ng test" 10 | }, 11 | "private": true, 12 | "dependencies": { 13 | "@angular/animations": "^14.2.0", 14 | "@angular/common": "^14.2.0", 15 | "@angular/compiler": "^14.2.0", 16 | "@angular/core": "^14.2.0", 17 | "@angular/forms": "^14.2.0", 18 | "@angular/platform-browser": "^14.2.0", 19 | "@angular/platform-browser-dynamic": "^14.2.0", 20 | "@angular/router": "^14.2.0", 21 | "bootstrap": "^4.6.1", 22 | "rxjs": "~7.5.0", 23 | "tslib": "^2.3.0", 24 | "zone.js": "~0.11.4" 25 | }, 26 | "devDependencies": { 27 | "@angular-devkit/build-angular": "^14.2.2", 28 | "@angular/cli": "~14.2.2", 29 | "@angular/compiler-cli": "^14.2.0", 30 | "@types/jasmine": "~4.0.0", 31 | "jasmine-core": "~4.3.0", 32 | "karma": "~6.4.0", 33 | "karma-chrome-launcher": "~3.1.0", 34 | "karma-coverage": "~2.2.0", 35 | "karma-jasmine": "~5.1.0", 36 | "karma-jasmine-html-reporter": "~2.0.0", 37 | "typescript": "~4.7.2" 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/app/_helpers/http.interceptor.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpEvent, HttpInterceptor, HttpHandler, HttpRequest, HTTP_INTERCEPTORS, HttpErrorResponse } from '@angular/common/http'; 3 | 4 | import { StorageService } from '../_services/storage.service'; 5 | import { AuthService } from '../_services/auth.service'; 6 | 7 | import { Observable, throwError } from 'rxjs'; 8 | import { catchError, switchMap } from 'rxjs/operators'; 9 | 10 | import { EventBusService } from '../_shared/event-bus.service'; 11 | import { EventData } from '../_shared/event.class'; 12 | 13 | @Injectable() 14 | export class HttpRequestInterceptor implements HttpInterceptor { 15 | private isRefreshing = false; 16 | 17 | constructor( 18 | private storageService: StorageService, 19 | private authService: AuthService, 20 | private eventBusService: EventBusService 21 | ) {} 22 | 23 | intercept(req: HttpRequest, next: HttpHandler): Observable> { 24 | req = req.clone({ 25 | withCredentials: true, 26 | }); 27 | 28 | return next.handle(req).pipe( 29 | catchError((error) => { 30 | if ( 31 | error instanceof HttpErrorResponse && 32 | !req.url.includes('auth/signin') && 33 | error.status === 401 34 | ) { 35 | return this.handle401Error(req, next); 36 | } 37 | 38 | return throwError(() => error); 39 | }) 40 | ); 41 | } 42 | 43 | private handle401Error(request: HttpRequest, next: HttpHandler) { 44 | if (!this.isRefreshing) { 45 | this.isRefreshing = true; 46 | 47 | if (this.storageService.isLoggedIn()) { 48 | return this.authService.refreshToken().pipe( 49 | switchMap(() => { 50 | this.isRefreshing = false; 51 | 52 | return next.handle(request); 53 | }), 54 | catchError((error) => { 55 | this.isRefreshing = false; 56 | 57 | if (error.status == '403') { 58 | this.eventBusService.emit(new EventData('logout', null)); 59 | } 60 | 61 | return throwError(() => error); 62 | }) 63 | ); 64 | } 65 | } 66 | 67 | return next.handle(request); 68 | } 69 | } 70 | 71 | export const httpInterceptorProviders = [ 72 | { provide: HTTP_INTERCEPTORS, useClass: HttpRequestInterceptor, multi: true }, 73 | ]; 74 | -------------------------------------------------------------------------------- /src/app/_services/auth.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { AuthService } from './auth.service'; 4 | 5 | describe('AuthService', () => { 6 | let service: AuthService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(AuthService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/app/_services/auth.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient, HttpHeaders } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | 5 | const AUTH_API = 'http://localhost:8080/api/auth/'; 6 | 7 | const httpOptions = { 8 | headers: new HttpHeaders({ 'Content-Type': 'application/json' }) 9 | }; 10 | 11 | @Injectable({ 12 | providedIn: 'root', 13 | }) 14 | export class AuthService { 15 | constructor(private http: HttpClient) {} 16 | 17 | login(username: string, password: string): Observable { 18 | return this.http.post( 19 | AUTH_API + 'signin', 20 | { 21 | username, 22 | password, 23 | }, 24 | httpOptions 25 | ); 26 | } 27 | 28 | register(username: string, email: string, password: string): Observable { 29 | return this.http.post( 30 | AUTH_API + 'signup', 31 | { 32 | username, 33 | email, 34 | password, 35 | }, 36 | httpOptions 37 | ); 38 | } 39 | 40 | logout(): Observable { 41 | return this.http.post(AUTH_API + 'signout', { }, httpOptions); 42 | } 43 | 44 | refreshToken() { 45 | return this.http.post(AUTH_API + 'refreshtoken', { }, httpOptions); 46 | } 47 | } 48 | -------------------------------------------------------------------------------- /src/app/_services/storage.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { StorageService } from './storage.service'; 4 | 5 | describe('StorageService', () => { 6 | let service: StorageService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(StorageService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/app/_services/storage.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | 3 | const USER_KEY = 'auth-user'; 4 | 5 | @Injectable({ 6 | providedIn: 'root' 7 | }) 8 | export class StorageService { 9 | constructor() {} 10 | 11 | clean(): void { 12 | window.sessionStorage.clear(); 13 | } 14 | 15 | public saveUser(user: any): void { 16 | window.sessionStorage.removeItem(USER_KEY); 17 | window.sessionStorage.setItem(USER_KEY, JSON.stringify(user)); 18 | } 19 | 20 | public getUser(): any { 21 | const user = window.sessionStorage.getItem(USER_KEY); 22 | if (user) { 23 | return JSON.parse(user); 24 | } 25 | 26 | return {}; 27 | } 28 | 29 | public isLoggedIn(): boolean { 30 | const user = window.sessionStorage.getItem(USER_KEY); 31 | if (user) { 32 | return true; 33 | } 34 | 35 | return false; 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /src/app/_services/user.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { UserService } from './user.service'; 4 | 5 | describe('UserService', () => { 6 | let service: UserService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(UserService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/app/_services/user.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { HttpClient } from '@angular/common/http'; 3 | import { Observable } from 'rxjs'; 4 | 5 | const API_URL = 'http://localhost:8080/api/test/'; 6 | 7 | @Injectable({ 8 | providedIn: 'root', 9 | }) 10 | export class UserService { 11 | constructor(private http: HttpClient) { } 12 | 13 | getPublicContent(): Observable { 14 | return this.http.get(API_URL + 'all', { responseType: 'text' }); 15 | } 16 | 17 | getUserBoard(): Observable { 18 | return this.http.get(API_URL + 'user', { responseType: 'text' }); 19 | } 20 | 21 | getModeratorBoard(): Observable { 22 | return this.http.get(API_URL + 'mod', { responseType: 'text' }); 23 | } 24 | 25 | getAdminBoard(): Observable { 26 | return this.http.get(API_URL + 'admin', { responseType: 'text' }); 27 | } 28 | } 29 | -------------------------------------------------------------------------------- /src/app/_shared/event-bus.service.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | 3 | import { EventBusService } from './event-bus.service'; 4 | 5 | describe('EventBusService', () => { 6 | let service: EventBusService; 7 | 8 | beforeEach(() => { 9 | TestBed.configureTestingModule({}); 10 | service = TestBed.inject(EventBusService); 11 | }); 12 | 13 | it('should be created', () => { 14 | expect(service).toBeTruthy(); 15 | }); 16 | }); 17 | -------------------------------------------------------------------------------- /src/app/_shared/event-bus.service.ts: -------------------------------------------------------------------------------- 1 | import { Injectable } from '@angular/core'; 2 | import { Subject, Subscription } from 'rxjs'; 3 | import { filter, map } from 'rxjs/operators'; 4 | import { EventData } from './event.class'; 5 | 6 | @Injectable({ 7 | providedIn: 'root' 8 | }) 9 | export class EventBusService { 10 | private subject$ = new Subject(); 11 | 12 | constructor() { } 13 | 14 | emit(event: EventData) { 15 | this.subject$.next(event); 16 | } 17 | 18 | on(eventName: string, action: any): Subscription { 19 | return this.subject$.pipe( 20 | filter((e: EventData) => e.name === eventName), 21 | map((e: EventData) => e["value"])).subscribe(action); 22 | } 23 | } 24 | -------------------------------------------------------------------------------- /src/app/_shared/event.class.ts: -------------------------------------------------------------------------------- 1 | export class EventData { 2 | name: string; 3 | value: any; 4 | 5 | constructor(name: string, value: any) { 6 | this.name = name; 7 | this.value = value; 8 | } 9 | } -------------------------------------------------------------------------------- /src/app/app-routing.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { RouterModule, Routes } from '@angular/router'; 3 | 4 | import { RegisterComponent } from './register/register.component'; 5 | import { LoginComponent } from './login/login.component'; 6 | import { HomeComponent } from './home/home.component'; 7 | import { ProfileComponent } from './profile/profile.component'; 8 | import { BoardUserComponent } from './board-user/board-user.component'; 9 | import { BoardModeratorComponent } from './board-moderator/board-moderator.component'; 10 | import { BoardAdminComponent } from './board-admin/board-admin.component'; 11 | 12 | const routes: Routes = [ 13 | { path: 'home', component: HomeComponent }, 14 | { path: 'login', component: LoginComponent }, 15 | { path: 'register', component: RegisterComponent }, 16 | { path: 'profile', component: ProfileComponent }, 17 | { path: 'user', component: BoardUserComponent }, 18 | { path: 'mod', component: BoardModeratorComponent }, 19 | { path: 'admin', component: BoardAdminComponent }, 20 | { path: '', redirectTo: 'home', pathMatch: 'full' } 21 | ]; 22 | 23 | @NgModule({ 24 | imports: [RouterModule.forRoot(routes)], 25 | exports: [RouterModule] 26 | }) 27 | export class AppRoutingModule { } 28 | -------------------------------------------------------------------------------- /src/app/app.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-14-refresh-token/f2c1191481ac7feec644dad6ce026a13afbd1074/src/app/app.component.css -------------------------------------------------------------------------------- /src/app/app.component.html: -------------------------------------------------------------------------------- 1 |
2 | 37 | 38 |
39 | 40 |
41 |
42 | -------------------------------------------------------------------------------- /src/app/app.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { TestBed } from '@angular/core/testing'; 2 | import { RouterTestingModule } from '@angular/router/testing'; 3 | import { AppComponent } from './app.component'; 4 | 5 | describe('AppComponent', () => { 6 | beforeEach(async () => { 7 | await TestBed.configureTestingModule({ 8 | imports: [ 9 | RouterTestingModule 10 | ], 11 | declarations: [ 12 | AppComponent 13 | ], 14 | }).compileComponents(); 15 | }); 16 | 17 | it('should create the app', () => { 18 | const fixture = TestBed.createComponent(AppComponent); 19 | const app = fixture.componentInstance; 20 | expect(app).toBeTruthy(); 21 | }); 22 | 23 | it(`should have as title 'angular-14-refresh-token'`, () => { 24 | const fixture = TestBed.createComponent(AppComponent); 25 | const app = fixture.componentInstance; 26 | expect(app.title).toEqual('angular-14-refresh-token'); 27 | }); 28 | 29 | it('should render title', () => { 30 | const fixture = TestBed.createComponent(AppComponent); 31 | fixture.detectChanges(); 32 | const compiled = fixture.nativeElement as HTMLElement; 33 | expect(compiled.querySelector('.content span')?.textContent).toContain('angular-14-refresh-token app is running!'); 34 | }); 35 | }); 36 | -------------------------------------------------------------------------------- /src/app/app.component.ts: -------------------------------------------------------------------------------- 1 | import { Component } from '@angular/core'; 2 | import { Subscription } from 'rxjs'; 3 | import { StorageService } from './_services/storage.service'; 4 | import { AuthService } from './_services/auth.service'; 5 | import { EventBusService } from './_shared/event-bus.service'; 6 | 7 | @Component({ 8 | selector: 'app-root', 9 | templateUrl: './app.component.html', 10 | styleUrls: ['./app.component.css'] 11 | }) 12 | export class AppComponent { 13 | private roles: string[] = []; 14 | isLoggedIn = false; 15 | showAdminBoard = false; 16 | showModeratorBoard = false; 17 | username?: string; 18 | 19 | eventBusSub?: Subscription; 20 | 21 | constructor( 22 | private storageService: StorageService, 23 | private authService: AuthService, 24 | private eventBusService: EventBusService 25 | ) {} 26 | 27 | ngOnInit(): void { 28 | this.isLoggedIn = this.storageService.isLoggedIn(); 29 | 30 | if (this.isLoggedIn) { 31 | const user = this.storageService.getUser(); 32 | this.roles = user.roles; 33 | 34 | this.showAdminBoard = this.roles.includes('ROLE_ADMIN'); 35 | this.showModeratorBoard = this.roles.includes('ROLE_MODERATOR'); 36 | 37 | this.username = user.username; 38 | } 39 | 40 | this.eventBusSub = this.eventBusService.on('logout', () => { 41 | this.logout(); 42 | }); 43 | } 44 | 45 | logout(): void { 46 | this.authService.logout().subscribe({ 47 | next: res => { 48 | console.log(res); 49 | this.storageService.clean(); 50 | 51 | window.location.reload(); 52 | }, 53 | error: err => { 54 | console.log(err); 55 | } 56 | }); 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /src/app/app.module.ts: -------------------------------------------------------------------------------- 1 | import { NgModule } from '@angular/core'; 2 | import { BrowserModule } from '@angular/platform-browser'; 3 | import { FormsModule } from '@angular/forms'; 4 | import { HttpClientModule } from '@angular/common/http'; 5 | 6 | import { AppRoutingModule } from './app-routing.module'; 7 | import { AppComponent } from './app.component'; 8 | import { LoginComponent } from './login/login.component'; 9 | import { RegisterComponent } from './register/register.component'; 10 | import { HomeComponent } from './home/home.component'; 11 | import { ProfileComponent } from './profile/profile.component'; 12 | import { BoardAdminComponent } from './board-admin/board-admin.component'; 13 | import { BoardModeratorComponent } from './board-moderator/board-moderator.component'; 14 | import { BoardUserComponent } from './board-user/board-user.component'; 15 | 16 | import { httpInterceptorProviders } from './_helpers/http.interceptor'; 17 | 18 | @NgModule({ 19 | declarations: [ 20 | AppComponent, 21 | LoginComponent, 22 | RegisterComponent, 23 | HomeComponent, 24 | ProfileComponent, 25 | BoardAdminComponent, 26 | BoardModeratorComponent, 27 | BoardUserComponent 28 | ], 29 | imports: [ 30 | BrowserModule, 31 | AppRoutingModule, 32 | FormsModule, 33 | HttpClientModule 34 | ], 35 | providers: [httpInterceptorProviders], 36 | bootstrap: [AppComponent] 37 | }) 38 | export class AppModule { } 39 | -------------------------------------------------------------------------------- /src/app/board-admin/board-admin.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-14-refresh-token/f2c1191481ac7feec644dad6ce026a13afbd1074/src/app/board-admin/board-admin.component.css -------------------------------------------------------------------------------- /src/app/board-admin/board-admin.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

{{ content }}

4 |
5 |
6 | -------------------------------------------------------------------------------- /src/app/board-admin/board-admin.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { BoardAdminComponent } from './board-admin.component'; 4 | 5 | describe('BoardAdminComponent', () => { 6 | let component: BoardAdminComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ BoardAdminComponent ] 12 | }) 13 | .compileComponents(); 14 | 15 | fixture = TestBed.createComponent(BoardAdminComponent); 16 | component = fixture.componentInstance; 17 | fixture.detectChanges(); 18 | }); 19 | 20 | it('should create', () => { 21 | expect(component).toBeTruthy(); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/app/board-admin/board-admin.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-board-admin', 6 | templateUrl: './board-admin.component.html', 7 | styleUrls: ['./board-admin.component.css'] 8 | }) 9 | export class BoardAdminComponent implements OnInit { 10 | content?: string; 11 | 12 | constructor(private userService: UserService) { } 13 | 14 | ngOnInit(): void { 15 | this.userService.getAdminBoard().subscribe({ 16 | next: data => { 17 | this.content = data; 18 | }, 19 | error: err => { 20 | if (err.error) { 21 | try { 22 | const res = JSON.parse(err.error); 23 | this.content = res.message; 24 | } catch { 25 | this.content = `Error with status: ${err.status} - ${err.statusText}`; 26 | } 27 | } else { 28 | this.content = `Error with status: ${err.status}`; 29 | } 30 | } 31 | }); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/app/board-moderator/board-moderator.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-14-refresh-token/f2c1191481ac7feec644dad6ce026a13afbd1074/src/app/board-moderator/board-moderator.component.css -------------------------------------------------------------------------------- /src/app/board-moderator/board-moderator.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

{{ content }}

4 |
5 |
6 | -------------------------------------------------------------------------------- /src/app/board-moderator/board-moderator.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { BoardModeratorComponent } from './board-moderator.component'; 4 | 5 | describe('BoardModeratorComponent', () => { 6 | let component: BoardModeratorComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ BoardModeratorComponent ] 12 | }) 13 | .compileComponents(); 14 | 15 | fixture = TestBed.createComponent(BoardModeratorComponent); 16 | component = fixture.componentInstance; 17 | fixture.detectChanges(); 18 | }); 19 | 20 | it('should create', () => { 21 | expect(component).toBeTruthy(); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/app/board-moderator/board-moderator.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-board-moderator', 6 | templateUrl: './board-moderator.component.html', 7 | styleUrls: ['./board-moderator.component.css'] 8 | }) 9 | export class BoardModeratorComponent implements OnInit { 10 | content?: string; 11 | 12 | constructor(private userService: UserService) { } 13 | 14 | ngOnInit(): void { 15 | this.userService.getModeratorBoard().subscribe({ 16 | next: data => { 17 | this.content = data; 18 | }, 19 | error: err => { 20 | if (err.error) { 21 | try { 22 | const res = JSON.parse(err.error); 23 | this.content = res.message; 24 | } catch { 25 | this.content = `Error with status: ${err.status} - ${err.statusText}`; 26 | } 27 | } else { 28 | this.content = `Error with status: ${err.status}`; 29 | } 30 | } 31 | }); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/app/board-user/board-user.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-14-refresh-token/f2c1191481ac7feec644dad6ce026a13afbd1074/src/app/board-user/board-user.component.css -------------------------------------------------------------------------------- /src/app/board-user/board-user.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

{{ content }}

4 |
5 |
6 | -------------------------------------------------------------------------------- /src/app/board-user/board-user.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { BoardUserComponent } from './board-user.component'; 4 | 5 | describe('BoardUserComponent', () => { 6 | let component: BoardUserComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ BoardUserComponent ] 12 | }) 13 | .compileComponents(); 14 | 15 | fixture = TestBed.createComponent(BoardUserComponent); 16 | component = fixture.componentInstance; 17 | fixture.detectChanges(); 18 | }); 19 | 20 | it('should create', () => { 21 | expect(component).toBeTruthy(); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/app/board-user/board-user.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-board-user', 6 | templateUrl: './board-user.component.html', 7 | styleUrls: ['./board-user.component.css'] 8 | }) 9 | export class BoardUserComponent implements OnInit { 10 | content?: string; 11 | 12 | constructor(private userService: UserService) { } 13 | 14 | ngOnInit(): void { 15 | this.userService.getUserBoard().subscribe({ 16 | next: data => { 17 | this.content = data; 18 | }, 19 | error: err => { 20 | if (err.error) { 21 | try { 22 | const res = JSON.parse(err.error); 23 | this.content = res.message; 24 | } catch { 25 | this.content = `Error with status: ${err.status} - ${err.statusText}`; 26 | } 27 | } else { 28 | this.content = `Error with status: ${err.status}`; 29 | } 30 | } 31 | }); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/app/home/home.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-14-refresh-token/f2c1191481ac7feec644dad6ce026a13afbd1074/src/app/home/home.component.css -------------------------------------------------------------------------------- /src/app/home/home.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

{{ content }}

4 |
5 |
6 | -------------------------------------------------------------------------------- /src/app/home/home.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { HomeComponent } from './home.component'; 4 | 5 | describe('HomeComponent', () => { 6 | let component: HomeComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ HomeComponent ] 12 | }) 13 | .compileComponents(); 14 | 15 | fixture = TestBed.createComponent(HomeComponent); 16 | component = fixture.componentInstance; 17 | fixture.detectChanges(); 18 | }); 19 | 20 | it('should create', () => { 21 | expect(component).toBeTruthy(); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/app/home/home.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { UserService } from '../_services/user.service'; 3 | 4 | @Component({ 5 | selector: 'app-home', 6 | templateUrl: './home.component.html', 7 | styleUrls: ['./home.component.css'] 8 | }) 9 | export class HomeComponent implements OnInit { 10 | content?: string; 11 | 12 | constructor(private userService: UserService) { } 13 | 14 | ngOnInit(): void { 15 | this.userService.getPublicContent().subscribe({ 16 | next: data => { 17 | this.content = data; 18 | }, 19 | error: err => { 20 | if (err.error) { 21 | try { 22 | const res = JSON.parse(err.error); 23 | this.content = res.message; 24 | } catch { 25 | this.content = `Error with status: ${err.status} - ${err.statusText}`; 26 | } 27 | } else { 28 | this.content = `Error with status: ${err.status}`; 29 | } 30 | } 31 | }); 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /src/app/login/login.component.css: -------------------------------------------------------------------------------- 1 | label { 2 | display: block; 3 | margin-top: 10px; 4 | } 5 | 6 | .card-container.card { 7 | max-width: 400px !important; 8 | padding: 40px 40px; 9 | } 10 | 11 | .card { 12 | background-color: #f7f7f7; 13 | padding: 20px 25px 30px; 14 | margin: 0 auto 25px; 15 | margin-top: 50px; 16 | -moz-border-radius: 2px; 17 | -webkit-border-radius: 2px; 18 | border-radius: 2px; 19 | -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 20 | -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 21 | box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 22 | } 23 | 24 | .profile-img-card { 25 | width: 96px; 26 | height: 96px; 27 | margin: 0 auto 10px; 28 | display: block; 29 | -moz-border-radius: 50%; 30 | -webkit-border-radius: 50%; 31 | border-radius: 50%; 32 | } -------------------------------------------------------------------------------- /src/app/login/login.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 8 |
15 |
16 | 17 | 26 |
27 | Username is required! 28 |
29 |
30 |
31 | 32 | 42 |
43 |
Password is required
44 |
45 | Password must be at least 6 characters 46 |
47 |
48 |
49 |
50 | 53 |
54 |
55 | 58 |
59 |
60 | 61 |
62 | Logged in as {{ roles }}. 63 |
64 |
65 |
-------------------------------------------------------------------------------- /src/app/login/login.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { LoginComponent } from './login.component'; 4 | 5 | describe('LoginComponent', () => { 6 | let component: LoginComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ LoginComponent ] 12 | }) 13 | .compileComponents(); 14 | 15 | fixture = TestBed.createComponent(LoginComponent); 16 | component = fixture.componentInstance; 17 | fixture.detectChanges(); 18 | }); 19 | 20 | it('should create', () => { 21 | expect(component).toBeTruthy(); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/app/login/login.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from '../_services/auth.service'; 3 | import { StorageService } from '../_services/storage.service'; 4 | 5 | @Component({ 6 | selector: 'app-login', 7 | templateUrl: './login.component.html', 8 | styleUrls: ['./login.component.css'] 9 | }) 10 | export class LoginComponent implements OnInit { 11 | form: any = { 12 | username: null, 13 | password: null 14 | }; 15 | isLoggedIn = false; 16 | isLoginFailed = false; 17 | errorMessage = ''; 18 | roles: string[] = []; 19 | 20 | constructor(private authService: AuthService, private storageService: StorageService) { } 21 | 22 | ngOnInit(): void { 23 | if (this.storageService.isLoggedIn()) { 24 | this.isLoggedIn = true; 25 | this.roles = this.storageService.getUser().roles; 26 | } 27 | } 28 | 29 | onSubmit(): void { 30 | const { username, password } = this.form; 31 | 32 | this.authService.login(username, password).subscribe({ 33 | next: data => { 34 | this.storageService.saveUser(data); 35 | 36 | this.isLoginFailed = false; 37 | this.isLoggedIn = true; 38 | this.roles = this.storageService.getUser().roles; 39 | this.reloadPage(); 40 | }, 41 | error: err => { 42 | this.errorMessage = err.error.message; 43 | this.isLoginFailed = true; 44 | } 45 | }); 46 | } 47 | 48 | reloadPage(): void { 49 | window.location.reload(); 50 | } 51 | } 52 | -------------------------------------------------------------------------------- /src/app/profile/profile.component.css: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-14-refresh-token/f2c1191481ac7feec644dad6ce026a13afbd1074/src/app/profile/profile.component.css -------------------------------------------------------------------------------- /src/app/profile/profile.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 |

4 | {{ currentUser.username }} Profile 5 |

6 |
7 |

8 | Email: 9 | {{ currentUser.email }} 10 |

11 | Roles: 12 |
    13 |
  • 14 | {{ role }} 15 |
  • 16 |
17 |
18 | 19 | 20 | Please login. 21 | -------------------------------------------------------------------------------- /src/app/profile/profile.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { ProfileComponent } from './profile.component'; 4 | 5 | describe('ProfileComponent', () => { 6 | let component: ProfileComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ ProfileComponent ] 12 | }) 13 | .compileComponents(); 14 | 15 | fixture = TestBed.createComponent(ProfileComponent); 16 | component = fixture.componentInstance; 17 | fixture.detectChanges(); 18 | }); 19 | 20 | it('should create', () => { 21 | expect(component).toBeTruthy(); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/app/profile/profile.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { StorageService } from '../_services/storage.service'; 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 | currentUser: any; 11 | 12 | constructor(private storageService: StorageService) { } 13 | 14 | ngOnInit(): void { 15 | this.currentUser = this.storageService.getUser(); 16 | } 17 | } 18 | -------------------------------------------------------------------------------- /src/app/register/register.component.css: -------------------------------------------------------------------------------- 1 | label { 2 | display: block; 3 | margin-top: 10px; 4 | } 5 | 6 | .card-container.card { 7 | max-width: 400px !important; 8 | padding: 40px 40px; 9 | } 10 | 11 | .card { 12 | background-color: #f7f7f7; 13 | padding: 20px 25px 30px; 14 | margin: 0 auto 25px; 15 | margin-top: 50px; 16 | -moz-border-radius: 2px; 17 | -webkit-border-radius: 2px; 18 | border-radius: 2px; 19 | -moz-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 20 | -webkit-box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 21 | box-shadow: 0px 2px 2px rgba(0, 0, 0, 0.3); 22 | } 23 | 24 | .profile-img-card { 25 | width: 96px; 26 | height: 96px; 27 | margin: 0 auto 10px; 28 | display: block; 29 | -moz-border-radius: 50%; 30 | -webkit-border-radius: 50%; 31 | border-radius: 50%; 32 | } -------------------------------------------------------------------------------- /src/app/register/register.component.html: -------------------------------------------------------------------------------- 1 |
2 |
3 | 8 |
15 |
16 | 17 | 28 |
29 |
Username is required
30 |
31 | Username must be at least 3 characters 32 |
33 |
34 | Username must be at most 20 characters 35 |
36 |
37 |
38 |
39 | 40 | 50 |
51 |
Email is required
52 |
53 | Email must be a valid email address 54 |
55 |
56 |
57 |
58 | 59 | 69 |
70 |
Password is required
71 |
72 | Password must be at least 6 characters 73 |
74 |
75 |
76 |
77 | 78 |
79 | 80 |
81 | Signup failed!
{{ errorMessage }} 82 |
83 |
84 | 85 |
86 | Your registration is successful! 87 |
88 |
89 |
-------------------------------------------------------------------------------- /src/app/register/register.component.spec.ts: -------------------------------------------------------------------------------- 1 | import { ComponentFixture, TestBed } from '@angular/core/testing'; 2 | 3 | import { RegisterComponent } from './register.component'; 4 | 5 | describe('RegisterComponent', () => { 6 | let component: RegisterComponent; 7 | let fixture: ComponentFixture; 8 | 9 | beforeEach(async () => { 10 | await TestBed.configureTestingModule({ 11 | declarations: [ RegisterComponent ] 12 | }) 13 | .compileComponents(); 14 | 15 | fixture = TestBed.createComponent(RegisterComponent); 16 | component = fixture.componentInstance; 17 | fixture.detectChanges(); 18 | }); 19 | 20 | it('should create', () => { 21 | expect(component).toBeTruthy(); 22 | }); 23 | }); 24 | -------------------------------------------------------------------------------- /src/app/register/register.component.ts: -------------------------------------------------------------------------------- 1 | import { Component, OnInit } from '@angular/core'; 2 | import { AuthService } from '../_services/auth.service'; 3 | 4 | @Component({ 5 | selector: 'app-register', 6 | templateUrl: './register.component.html', 7 | styleUrls: ['./register.component.css'] 8 | }) 9 | export class RegisterComponent implements OnInit { 10 | form: any = { 11 | username: null, 12 | email: null, 13 | password: null 14 | }; 15 | isSuccessful = false; 16 | isSignUpFailed = false; 17 | errorMessage = ''; 18 | 19 | constructor(private authService: AuthService) { } 20 | 21 | ngOnInit(): void { 22 | } 23 | 24 | onSubmit(): void { 25 | const { username, email, password } = this.form; 26 | 27 | this.authService.register(username, email, password).subscribe({ 28 | next: data => { 29 | console.log(data); 30 | this.isSuccessful = true; 31 | this.isSignUpFailed = false; 32 | }, 33 | error: err => { 34 | this.errorMessage = err.error.message; 35 | this.isSignUpFailed = true; 36 | } 37 | }); 38 | } 39 | } 40 | -------------------------------------------------------------------------------- /src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-14-refresh-token/f2c1191481ac7feec644dad6ce026a13afbd1074/src/assets/.gitkeep -------------------------------------------------------------------------------- /src/environments/environment.prod.ts: -------------------------------------------------------------------------------- 1 | export const environment = { 2 | production: true 3 | }; 4 | -------------------------------------------------------------------------------- /src/environments/environment.ts: -------------------------------------------------------------------------------- 1 | // This file can be replaced during build by using the `fileReplacements` array. 2 | // `ng build` replaces `environment.ts` with `environment.prod.ts`. 3 | // The list of file replacements can be found in `angular.json`. 4 | 5 | export const environment = { 6 | production: false 7 | }; 8 | 9 | /* 10 | * For easier debugging in development mode, you can import the following file 11 | * to ignore zone related error stack frames such as `zone.run`, `zoneDelegate.invokeTask`. 12 | * 13 | * This import should be commented out in production mode because it will have a negative impact 14 | * on performance if an error is thrown. 15 | */ 16 | // import 'zone.js/plugins/zone-error'; // Included with Angular CLI. 17 | -------------------------------------------------------------------------------- /src/favicon.ico: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/bezkoder/angular-14-refresh-token/f2c1191481ac7feec644dad6ce026a13afbd1074/src/favicon.ico -------------------------------------------------------------------------------- /src/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Angular14RefreshToken 6 | 7 | 8 | 9 | 10 | 11 | 12 | 13 | 14 | -------------------------------------------------------------------------------- /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.error(err)); 13 | -------------------------------------------------------------------------------- /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 recent versions of Safari, Chrome (including 12 | * Opera), Edge on the desktop, and iOS and Chrome on mobile. 13 | * 14 | * Learn more in https://angular.io/guide/browser-support 15 | */ 16 | 17 | /*************************************************************************************************** 18 | * BROWSER POLYFILLS 19 | */ 20 | 21 | /** 22 | * By default, zone.js will patch all possible macroTask and DomEvents 23 | * user can disable parts of macroTask/DomEvents patch by setting following flags 24 | * because those flags need to be set before `zone.js` being loaded, and webpack 25 | * will put import in the top of bundle, so user need to create a separate file 26 | * in this directory (for example: zone-flags.ts), and put the following flags 27 | * into that file, and then add the following code before importing zone.js. 28 | * import './zone-flags'; 29 | * 30 | * The flags allowed in zone-flags.ts are listed here. 31 | * 32 | * The following flags will work for all browsers. 33 | * 34 | * (window as any).__Zone_disable_requestAnimationFrame = true; // disable patch requestAnimationFrame 35 | * (window as any).__Zone_disable_on_property = true; // disable patch onProperty such as onclick 36 | * (window as any).__zone_symbol__UNPATCHED_EVENTS = ['scroll', 'mousemove']; // disable patch specified eventNames 37 | * 38 | * in IE/Edge developer tools, the addEventListener will also be wrapped by zone.js 39 | * with the following flag, it will bypass `zone.js` patch for IE/Edge 40 | * 41 | * (window as any).__Zone_enable_cross_context_check = true; 42 | * 43 | */ 44 | 45 | /*************************************************************************************************** 46 | * Zone JS is required by default for Angular itself. 47 | */ 48 | import 'zone.js'; // Included with Angular CLI. 49 | 50 | 51 | /*************************************************************************************************** 52 | * APPLICATION IMPORTS 53 | */ 54 | -------------------------------------------------------------------------------- /src/styles.css: -------------------------------------------------------------------------------- 1 | /* You can add global styles to this file, and also import other style files */ 2 | @import "~bootstrap/dist/css/bootstrap.css"; -------------------------------------------------------------------------------- /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/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: { 11 | context(path: string, deep?: boolean, filter?: RegExp): { 12 | (id: string): T; 13 | keys(): string[]; 14 | }; 15 | }; 16 | 17 | // First, initialize the Angular testing environment. 18 | getTestBed().initTestEnvironment( 19 | BrowserDynamicTestingModule, 20 | platformBrowserDynamicTesting(), 21 | ); 22 | 23 | // Then we find all the tests. 24 | const context = require.context('./', true, /\.spec\.ts$/); 25 | // And load the modules. 26 | context.keys().forEach(context); 27 | -------------------------------------------------------------------------------- /tsconfig.app.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/app", 6 | "types": [] 7 | }, 8 | "files": [ 9 | "src/main.ts", 10 | "src/polyfills.ts" 11 | ], 12 | "include": [ 13 | "src/**/*.d.ts" 14 | ] 15 | } 16 | -------------------------------------------------------------------------------- /tsconfig.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "compileOnSave": false, 4 | "compilerOptions": { 5 | "baseUrl": "./", 6 | "outDir": "./dist/out-tsc", 7 | "forceConsistentCasingInFileNames": true, 8 | "strict": true, 9 | "noImplicitOverride": true, 10 | "noPropertyAccessFromIndexSignature": true, 11 | "noImplicitReturns": true, 12 | "noFallthroughCasesInSwitch": true, 13 | "sourceMap": true, 14 | "declaration": false, 15 | "downlevelIteration": true, 16 | "experimentalDecorators": true, 17 | "moduleResolution": "node", 18 | "importHelpers": true, 19 | "target": "es2020", 20 | "module": "es2020", 21 | "lib": [ 22 | "es2020", 23 | "dom" 24 | ] 25 | }, 26 | "angularCompilerOptions": { 27 | "enableI18nLegacyMessageIdFormat": false, 28 | "strictInjectionParameters": true, 29 | "strictInputAccessModifiers": true, 30 | "strictTemplates": true 31 | } 32 | } 33 | -------------------------------------------------------------------------------- /tsconfig.spec.json: -------------------------------------------------------------------------------- 1 | /* To learn more about this file see: https://angular.io/config/tsconfig. */ 2 | { 3 | "extends": "./tsconfig.json", 4 | "compilerOptions": { 5 | "outDir": "./out-tsc/spec", 6 | "types": [ 7 | "jasmine" 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 | --------------------------------------------------------------------------------