daily pastebin goal
10%
SHARE
TWEET

Untitled

a guest Mar 17th, 2018 81 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { Injectable } from '@angular/core';
  2. import { HttpRequest, HttpResponse, HttpHandler, HttpEvent, HttpInterceptor, HTTP_INTERCEPTORS } from '@angular/common/http';
  3. import { Observable } from 'rxjs/Observable';
  4. import 'rxjs/add/observable/of';
  5. import 'rxjs/add/observable/throw';
  6. import 'rxjs/add/operator/delay';
  7. import 'rxjs/add/operator/mergeMap';
  8. import 'rxjs/add/operator/materialize';
  9. import 'rxjs/add/operator/dematerialize';
  10.  
  11. @Injectable()
  12. export class FakeBackendInterceptor implements HttpInterceptor {
  13.  
  14.   constructor() { }
  15.  
  16.   intercept(request: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
  17.     // array in local storage for registered users
  18.     const users: any[] = JSON.parse(localStorage.getItem('users')) || [];
  19.  
  20.     // wrap in delayed observable to simulate server api call
  21.     return Observable.of(null).mergeMap(() => {
  22.  
  23.       // authenticate
  24.       if (request.url.endsWith('/api/authenticate') && request.method === 'POST') {
  25.         // find if any user matches login credentials
  26.         const filteredUsers = users.filter(user => {
  27.           return user.username === request.body.username && user.password === request.body.password;
  28.         });
  29.  
  30.         if (filteredUsers.length) {
  31.           // if login details are valid return 200 OK with user details and fake jwt token
  32.           const user = filteredUsers[0];
  33.           const body = {
  34.             id: user.id,
  35.             username: user.username,
  36.             firstName: user.firstName,
  37.             lastName: user.lastName,
  38.             token: 'fake-jwt-token'
  39.           };
  40.  
  41.           return Observable.of(new HttpResponse({ status: 200, body: body }));
  42.         } else {
  43.           // else return 400 bad request
  44.           return Observable.throw('Username or password is incorrect');
  45.         }
  46.       }
  47.  
  48.       // get users
  49.       if (request.url.endsWith('/api/users') && request.method === 'GET') {
  50.         // check for fake auth token in header and return users if valid, this security is implemented server side in a real application
  51.         if (request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
  52.           return Observable.of(new HttpResponse({ status: 200, body: users }));
  53.         } else {
  54.           // return 401 not authorised if token is null or invalid
  55.           return Observable.throw('Unauthorised');
  56.         }
  57.       }
  58.  
  59.       // get user by id
  60.       if (request.url.match(/\/api\/users\/\d+$/) && request.method === 'GET') {
  61.         // check for fake auth token in header and return user if valid, this security is implemented server side in a real application
  62.         if (request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
  63.           // find user by id in users array
  64.           const urlParts = request.url.split('/');
  65.           const id = parseInt(urlParts[urlParts.length - 1]);
  66.           const matchedUsers = users.filter(user => user.id === id);
  67.           const user = matchedUsers.length ? matchedUsers[0] : null;
  68.  
  69.           return Observable.of(new HttpResponse({ status: 200, body: user }));
  70.         } else {
  71.           // return 401 not authorised if token is null or invalid
  72.           return Observable.throw('Unauthorised');
  73.         }
  74.       }
  75.  
  76.       // create user
  77.       if (request.url.endsWith('/api/users') && request.method === 'POST') {
  78.         // get new user object from post body
  79.         const newUser = request.body;
  80.  
  81.         // validation
  82.         const duplicateUser = users.filter(user => user.username === newUser.username).length;
  83.         if (duplicateUser) {
  84.           return Observable.throw('Username "' + newUser.username + '" is already taken');
  85.         }
  86.  
  87.         // save new user
  88.         newUser.id = users.length + 1;
  89.         users.push(newUser);
  90.         localStorage.setItem('users', JSON.stringify(users));
  91.  
  92.         // respond 200 OK
  93.         return Observable.of(new HttpResponse({ status: 200 }));
  94.       }
  95.  
  96.       // delete user
  97.       if (request.url.match(/\/api\/users\/\d+$/) && request.method === 'DELETE') {
  98.         // check for fake auth token in header and return user if valid, this security is implemented server side in a real application
  99.         if (request.headers.get('Authorization') === 'Bearer fake-jwt-token') {
  100.           // find user by id in users array
  101.           const urlParts = request.url.split('/');
  102.           const id = parseInt(urlParts[urlParts.length - 1]);
  103.           for (let i = 0; i < users.length; i++) {
  104.             const user = users[i];
  105.             if (user.id === id) {
  106.               // delete user
  107.               users.splice(i, 1);
  108.               localStorage.setItem('users', JSON.stringify(users));
  109.               break;
  110.             }
  111.           }
  112.  
  113.           // respond 200 OK
  114.           return Observable.of(new HttpResponse({ status: 200 }));
  115.         } else {
  116.           // return 401 not authorised if token is null or invalid
  117.           return Observable.throw('Unauthorised');
  118.         }
  119.       }
  120.  
  121.       // pass through any requests not handled above
  122.       return next.handle(request);
  123.  
  124.     })
  125.  
  126.     // call materialize and dematerialize to ensure delay even if an error is thrown (https://github.com/Reactive-Extensions/RxJS/issues/648)
  127.       .materialize()
  128.       .delay(500)
  129.       .dematerialize();
  130.   }
  131. }
  132.  
  133. export let fakeBackendProvider = {
  134.   // use fake backend in place of Http service for backend-less development
  135.   provide: HTTP_INTERCEPTORS,
  136.   useClass: FakeBackendInterceptor,
  137.   multi: true
  138. };
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
 
Top