Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import { STORAGEKEY } from '../config/app.config';
- class Auth {
- /**
- * Authenticate a user. Save a token string in Local Storage
- *
- * @param {string} token
- */
- static setAuthToken(token: string) {
- localStorage.setItem(STORAGEKEY.token, token);
- }
- /*
- * Sets AuthData to localStorage
- * */
- static setAuthData(data: Array<any> | Record<any, any>) {
- localStorage.setItem(STORAGEKEY.authData, JSON.stringify(data));
- }
- /*
- * Get userData
- *
- * */
- static getAuthData() {
- try {
- return JSON.parse(localStorage.getItem(STORAGEKEY.authData)!);
- } catch (e: unknown) {
- return {};
- }
- }
- /**
- * Check if a user is authenticated - check if a token is saved in Local Storage
- *
- * @returns {boolean}
- */
- static isUserAuthenticated(): boolean {
- return localStorage.getItem(STORAGEKEY.token) !== null;
- }
- /**
- * Deauthenticate a user. Remove a token from Local Storage.
- *
- */
- static deauthenticateUser() {
- localStorage.removeItem(STORAGEKEY.token);
- localStorage.removeItem(STORAGEKEY.authData);
- localStorage.removeItem(STORAGEKEY.userData);
- localStorage.removeItem(STORAGEKEY.layoutData);
- }
- /**
- * Get a token value.
- *
- * @returns {string}
- */
- static getToken() {
- return 'Bearer ' + localStorage.getItem(STORAGEKEY.token);
- }
- /*
- * Sets userData to localStorage
- * */
- static setUserData(data: any) {
- localStorage.setItem(STORAGEKEY.userData, JSON.stringify(data));
- if (this.subscribers && this.subscribers.userInfo) {
- this.subscribers.userInfo.forEach((subscriber: any) => {
- subscriber();
- });
- }
- }
- /*
- * Get userData
- * */
- //TODO: refactor
- static getUserData() {
- try {
- console.log('getUserData');
- // debugger;
- const data = JSON.parse(localStorage.getItem(STORAGEKEY.userData)!);
- return data;
- } catch (e) {
- return {};
- }
- }
- static clearLocalStorage() {
- localStorage.clear();
- if (this.subscribers && this.subscribers.userInfo) {
- this.subscribers.userInfo.forEach((subscriber: any) => {
- subscriber();
- });
- }
- }
- static subscribers: Record<any, any> = {
- userInfo: [],
- };
- static addSubscriber(event: any, fn: any) {
- this.subscribers[event].push(fn);
- }
- static clearAllSubscriptions() {
- Object.keys(this.subscribers).forEach((event) => {
- if (this.subscribers && this.subscribers[event]) {
- this.subscribers[event] = [];
- }
- });
- }
- }
- export default Auth;
- //================================================================================//
- export const ApiGet = (type: any) => {
- return new Promise((resolve, reject) => {
- axios
- .get(BaseURL + type, getHttpOptions())
- .then((responseJson: any) => {
- resolve(responseJson);
- })
- .catch((error: any) => {
- if (
- error &&
- error.hasOwnProperty('response') &&
- error.response &&
- error.response.hasOwnProperty('data') &&
- error.response.data
- ) {
- let errorMessage = 'Server Error Please try again';
- if (
- error.response.data.hasOwnProperty('error') &&
- error.response.data.error
- ) {
- errorMessage = error.response.data.error;
- }
- if (
- error.response.data.hasOwnProperty('message') &&
- error.response.data.message
- ) {
- errorMessage = error.response.data.message;
- }
- if (error.response.status === 401) {
- localStorage.clear();
- // window.location.reload();
- return;
- }
- reject({ message: errorMessage, ...error });
- } else {
- reject(error);
- }
- });
- });
- };
- export const ApiPost = <T = unknown>(
- type: any,
- userData: any,
- options?: any,
- ) => {
- return new Promise<AxiosResponse<T>>((resolve, reject) => {
- axios
- .post(BaseURL + type, userData, { ...getHttpOptions(), ...options })
- .then((responseJson: AxiosResponse<T>) => {
- resolve(responseJson);
- })
- .catch((error: any) => {
- if (
- error &&
- error.hasOwnProperty('response') &&
- error.response &&
- error.response.hasOwnProperty('data') &&
- error.response.data
- ) {
- let errorMessage = 'Server Error Please try again';
- if (
- error.response.data.hasOwnProperty('error') &&
- error.response.data.error
- ) {
- errorMessage = error.response.data.error;
- }
- if (
- error.response.data.hasOwnProperty('message') &&
- error.response.data.message
- ) {
- errorMessage = error.response.data.message;
- }
- if (error.response.status === 401) {
- localStorage.clear();
- // window.location.reload();
- return;
- }
- reject({ ...error, message: errorMessage });
- } else {
- reject(error);
- }
- });
- });
- };
- interface RequstHeaders {
- Authorization?: string;
- 'Content-Type'?: 'application/json';
- }
- export const getHttpOptions = (options = defaultHeaders) => {
- let headers: RequstHeaders = {};
- if (options.hasOwnProperty('isAuth') && options.isAuth) {
- headers['Authorization'] = Auth.getToken();
- }
- if (options.hasOwnProperty('isJsonRequest') && options.isJsonRequest) {
- headers['Content-Type'] = 'application/json';
- }
- if (options.hasOwnProperty('AdditionalParams') && options.AdditionalParams) {
- headers = { ...headers, ...options.AdditionalParams };
- }
- return { headers };
- };
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement