All files / src/background/api auth.ts

14.63% Statements 6/41
0% Branches 0/6
0% Functions 0/13
14.63% Lines 6/41

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127                                    2x                         2x                     2x                                                             2x                                                                     2x                   2x                
import Axios, { AxiosResponse } from "axios";
 
import { hostname, userPath } from "./api";
 
import { UserState } from "../redux/actions/userTypes";
import store from "../redux/store";
import {
  addAccessToken,
  addRefreshToken,
  checkedCookies,
  removeTokens
} from "../redux/actions/tokens";
import { AccessToken, CookieStatus } from "../redux/actions/tokenTypes";
import { deleteCookie, getCookie, setCookie } from "../methods/cookies";
import {updateUser} from "../redux/actions/user";
 
// reference: https://daveceddia.com/access-redux-store-outside-react/
 
const cookieName: string = "refreshToken";
 
export interface BackendLoginData {
  tokenValue: string;
  user: UserState;
}
 
export interface BackendAuthData {
  tokenValue: string;
  userId: number;
  validUntil: number;
}
 
export const checkForCookie = () => {
  let refreshTokenCookieValue = getCookie(cookieName);
  if (refreshTokenCookieValue) {
    store.dispatch(addRefreshToken(refreshTokenCookieValue));
    store.dispatch(checkedCookies(CookieStatus.LOADING));
    getAccessTokenWithRefreshToken();
  } else {
    store.dispatch(checkedCookies(CookieStatus.FINISHED));
  }
};
 
export const loginWithUsernameAndPassword = (
  userName: string,
  password: string,
  stayLoggedIn: boolean
): Promise<BackendLoginData> => {
  console.log("[Auth] loginWithUsernameAndPassword", userName, password);
  return new Promise<BackendLoginData>((resolve, reject) => {
    let config = {
      headers: {
        Authorization: `Basic ${btoa(userName + ":" + password)}`
      }
    };
 
    return Axios.get<BackendLoginData>(hostname + userPath + "/login", config)
      .then((data: AxiosResponse<BackendLoginData>) => {
        console.log(data.data);
        store.dispatch(addRefreshToken(data.data.tokenValue));
        store.dispatch(updateUser(data.data.user as UserState));
 
        if (stayLoggedIn) {
          setCookie(cookieName, data.data.tokenValue, 60);
        }
 
        getAccessTokenWithRefreshToken();
      })
      .catch((error) => {
        reject(error);
      });
  });
};
 
export const getAccessTokenWithRefreshToken = () => {
  console.log("getAccessTokenWithRefreshToken");
 
  let refreshToken: string | null = store.getState().tokens.refreshToken;
 
  let config = {
    headers: {
      Authorization: `Bearer ${refreshToken}`
    }
  };
 
  Axios.get<BackendAuthData>(hostname + userPath + "/auth", config)
    .then((data: AxiosResponse<BackendAuthData>) => {
      store.dispatch(checkedCookies(CookieStatus.FINISHED));
      setAuthHeaderToAxios(data.data.tokenValue);
 
      store.dispatch(
        addAccessToken({
          token: data.data.tokenValue,
          timestamp: data.data.validUntil
        } as AccessToken)
      );
      if (!store.getState().user.username) {
        getOwnUserData(data.data.userId);
      }
    })
    .catch((error) => {
      store.dispatch(removeTokens());
      store.dispatch(checkedCookies(CookieStatus.FINISHED));
 
      console.log(error);
      //you probably want to notify the user, maybe with a toast or similar
    });
};
 
const getOwnUserData = (userId: number) => {
  Axios.get<UserState>(`${hostname}${userPath}/${userId}/info`)
    .then((response: AxiosResponse<UserState>) => {
      store.dispatch(updateUser(response.data));
    })
    .catch((error) => {
      console.log(error);
    });
};
 
export const logout = () => {
  store.dispatch(removeTokens());
  deleteCookie(cookieName);
};
 
function setAuthHeaderToAxios(accessToken: string) {
  Axios.defaults.headers.common["Authorization"] = `Bearer ${accessToken}`;
}