Advertisement
jakiro

Untitled

Mar 22nd, 2023
766
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import { STORAGEKEY } from '../config/app.config';
  2.  
  3. class Auth {
  4.   /**
  5.    * Authenticate a user. Save a token string in Local Storage
  6.    *
  7.    * @param {string} token
  8.    */
  9.   static setAuthToken(token: string) {
  10.     localStorage.setItem(STORAGEKEY.token, token);
  11.   }
  12.   /*
  13.    * Sets AuthData to localStorage
  14.    * */
  15.   static setAuthData(data: Array<any> | Record<any, any>) {
  16.     localStorage.setItem(STORAGEKEY.authData, JSON.stringify(data));
  17.   }
  18.  
  19.   /*
  20.    * Get userData
  21.    *
  22.    * */
  23.   static getAuthData() {
  24.     try {
  25.       return JSON.parse(localStorage.getItem(STORAGEKEY.authData)!);
  26.     } catch (e: unknown) {
  27.       return {};
  28.     }
  29.   }
  30.  
  31.   /**
  32.    * Check if a user is authenticated - check if a token is saved in Local Storage
  33.    *
  34.    * @returns {boolean}
  35.    */
  36.   static isUserAuthenticated(): boolean {
  37.     return localStorage.getItem(STORAGEKEY.token) !== null;
  38.   }
  39.  
  40.   /**
  41.    * Deauthenticate a user. Remove a token from Local Storage.
  42.    *
  43.    */
  44.   static deauthenticateUser() {
  45.     localStorage.removeItem(STORAGEKEY.token);
  46.     localStorage.removeItem(STORAGEKEY.authData);
  47.     localStorage.removeItem(STORAGEKEY.userData);
  48.     localStorage.removeItem(STORAGEKEY.layoutData);
  49.   }
  50.  
  51.   /**
  52.    * Get a token value.
  53.    *
  54.    * @returns {string}
  55.    */
  56.   static getToken() {
  57.     return 'Bearer ' + localStorage.getItem(STORAGEKEY.token);
  58.   }
  59.  
  60.   /*
  61.    * Sets userData to localStorage
  62.    * */
  63.   static setUserData(data: any) {
  64.     localStorage.setItem(STORAGEKEY.userData, JSON.stringify(data));
  65.     if (this.subscribers && this.subscribers.userInfo) {
  66.       this.subscribers.userInfo.forEach((subscriber: any) => {
  67.         subscriber();
  68.       });
  69.     }
  70.   }
  71.  
  72.   /*
  73.    * Get userData
  74.    * */
  75.   //TODO: refactor
  76.   static getUserData() {
  77.     try {
  78.       console.log('getUserData');
  79.       // debugger;
  80.       const data = JSON.parse(localStorage.getItem(STORAGEKEY.userData)!);
  81.       return data;
  82.     } catch (e) {
  83.       return {};
  84.     }
  85.   }
  86.  
  87.   static clearLocalStorage() {
  88.     localStorage.clear();
  89.     if (this.subscribers && this.subscribers.userInfo) {
  90.       this.subscribers.userInfo.forEach((subscriber: any) => {
  91.         subscriber();
  92.       });
  93.     }
  94.   }
  95.  
  96.   static subscribers: Record<any, any> = {
  97.     userInfo: [],
  98.   };
  99.  
  100.   static addSubscriber(event: any, fn: any) {
  101.     this.subscribers[event].push(fn);
  102.   }
  103.  
  104.   static clearAllSubscriptions() {
  105.     Object.keys(this.subscribers).forEach((event) => {
  106.       if (this.subscribers && this.subscribers[event]) {
  107.         this.subscribers[event] = [];
  108.       }
  109.     });
  110.   }
  111. }
  112.  
  113. export default Auth;
  114.  
  115.  
  116. //================================================================================//
  117.  
  118. export const ApiGet = (type: any) => {
  119.   return new Promise((resolve, reject) => {
  120.     axios
  121.       .get(BaseURL + type, getHttpOptions())
  122.       .then((responseJson: any) => {
  123.         resolve(responseJson);
  124.       })
  125.       .catch((error: any) => {
  126.         if (
  127.           error &&
  128.           error.hasOwnProperty('response') &&
  129.           error.response &&
  130.           error.response.hasOwnProperty('data') &&
  131.           error.response.data
  132.         ) {
  133.           let errorMessage = 'Server Error Please try again';
  134.           if (
  135.             error.response.data.hasOwnProperty('error') &&
  136.             error.response.data.error
  137.           ) {
  138.             errorMessage = error.response.data.error;
  139.           }
  140.  
  141.           if (
  142.             error.response.data.hasOwnProperty('message') &&
  143.             error.response.data.message
  144.           ) {
  145.             errorMessage = error.response.data.message;
  146.           }
  147.  
  148.           if (error.response.status === 401) {
  149.             localStorage.clear();
  150.             // window.location.reload();
  151.             return;
  152.           }
  153.           reject({ message: errorMessage, ...error });
  154.         } else {
  155.           reject(error);
  156.         }
  157.       });
  158.   });
  159. };
  160.  
  161. export const ApiPost = <T = unknown>(
  162.   type: any,
  163.   userData: any,
  164.   options?: any,
  165. ) => {
  166.   return new Promise<AxiosResponse<T>>((resolve, reject) => {
  167.     axios
  168.       .post(BaseURL + type, userData, { ...getHttpOptions(), ...options })
  169.       .then((responseJson: AxiosResponse<T>) => {
  170.         resolve(responseJson);
  171.       })
  172.       .catch((error: any) => {
  173.         if (
  174.           error &&
  175.           error.hasOwnProperty('response') &&
  176.           error.response &&
  177.           error.response.hasOwnProperty('data') &&
  178.           error.response.data
  179.         ) {
  180.           let errorMessage = 'Server Error Please try again';
  181.           if (
  182.             error.response.data.hasOwnProperty('error') &&
  183.             error.response.data.error
  184.           ) {
  185.             errorMessage = error.response.data.error;
  186.           }
  187.  
  188.           if (
  189.             error.response.data.hasOwnProperty('message') &&
  190.             error.response.data.message
  191.           ) {
  192.             errorMessage = error.response.data.message;
  193.           }
  194.  
  195.           if (error.response.status === 401) {
  196.             localStorage.clear();
  197.             // window.location.reload();
  198.             return;
  199.           }
  200.           reject({ ...error, message: errorMessage });
  201.         } else {
  202.           reject(error);
  203.         }
  204.       });
  205.   });
  206. };
  207.  
  208. interface RequstHeaders {
  209.   Authorization?: string;
  210.   'Content-Type'?: 'application/json';
  211. }
  212.  
  213. export const getHttpOptions = (options = defaultHeaders) => {
  214.   let headers: RequstHeaders = {};
  215.  
  216.   if (options.hasOwnProperty('isAuth') && options.isAuth) {
  217.     headers['Authorization'] = Auth.getToken();
  218.   }
  219.  
  220.   if (options.hasOwnProperty('isJsonRequest') && options.isJsonRequest) {
  221.     headers['Content-Type'] = 'application/json';
  222.   }
  223.  
  224.   if (options.hasOwnProperty('AdditionalParams') && options.AdditionalParams) {
  225.     headers = { ...headers, ...options.AdditionalParams };
  226.   }
  227.  
  228.   return { headers };
  229. };
  230.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement