· 6 years ago · Dec 02, 2019, 03:32 AM
1
2import { HttpErrorResponse, HttpEvent, HttpHandler, HttpHeaders, HttpInterceptor, HttpRequest } from '@angular/common/http';
3import { Injectable } from '@angular/core';
4import { Observable, throwError } from 'rxjs';
5import { catchError } from 'rxjs/operators';
6import { AuthService } from './shared/services/auth/auth.service';
7import * as Oauth1 from 'oauth-1.0a';
8import * as crypto from 'crypto-js'
9
10
11/* SERVICES */
12
13@Injectable({
14 providedIn: 'root'
15})
16export class HttpInterceptorService implements HttpInterceptor {
17 public tokenArray: string[];
18 public accessToken: string;
19 public refreshToken: string;
20 public tokenType: string;
21 private Consumer_key: 'ck_ed9e9ddcb0de3e185e663ebbe099b10b7173fbe4'
22 private Consumer_secret: 'cs_7ce494faef631784f09ae2199512065afb5f4e72'
23
24 constructor(public authService: AuthService) { }
25
26 intercept(req: HttpRequest<any>, next: HttpHandler): Observable<HttpEvent<any>> {
27 // INTERCEPT AND REMAKE HEADER
28 if (this.validateToken()) {
29 this.tokenArray = this.authService.loadUserCredentials();
30 this.accessToken = this.tokenArray[0];
31 this.tokenType = this.tokenArray[2];
32
33 const headers = new HttpHeaders({
34 Authorization: this.tokenType + ' ' + this.accessToken
35 });
36
37 const reqClone = req.clone({ headers });
38
39
40 // INTERCEPT HEADER AND PUT JWT BEARER OWN API REQUEST
41 if (req.url.split('.com')[0] === 'SAYMEE') {
42 console.log("No deberia de entrar aqui")
43 return next.handle(reqClone).pipe(catchError(this.manejarError));
44 }
45
46 // INTERCEPT HEADER AND PUT WOOCOMERCE BEARER TO EXTERNAL API
47
48
49 let oauthee = new Oauth1({
50 consumer: { key: this.Consumer_key, secret: this.Consumer_secret },
51 signature_method: 'HMAC-SHA1',
52 hash_function(base_string, key) {
53 return crypto
54 .HmacSHA1(base_string, key).toString(crypto.enc.Base64)
55
56 },
57 })
58
59 let autheader = oauthee.toHeader(oauthee.authorize(req)).Authorization
60
61
62 const headersWoo = new HttpHeaders({
63 'Content-Type': 'application/json',
64 'Authorization': autheader
65 })
66
67 const reqClone2 = req.clone({ headers: headersWoo });
68 console.log("Llegando aqui")
69 return next.handle(reqClone2).pipe(catchError(this.manejarError));
70 } else {
71 // INTERCEPT AND RETURN SAME HEADER OF THE REQUEST
72 return next.handle(req).pipe(catchError(this.manejarError));
73 }
74 }
75
76 private validateToken(): boolean {
77 if (this.authService.loadUserCredentials()) {
78 return true;
79 } else {
80 return false;
81 }
82 }
83
84 private manejarError(error: HttpErrorResponse) {
85 return throwError(error);
86 }
87}