All files / lib/apis/auth index.ts

0% Statements 0/18
0% Branches 0/4
0% Functions 0/1
0% Lines 0/18

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                                                                                                                   
import {
  AuthApi,
  Configuration as AuthInterfaceConfiguration
} from '@uniquegood/realworld-auth-interface';
import { APP_ENV, getLoginUrl } from '@lib/config';
import { memoizedPostRefreshAccessToken } from '@lib/apis/core/postRefreshAccessToken';
import axios from 'axios';
import { decodeJwt } from 'jose';
import { getLocalStorage, setLocalStorage } from '@lib/utils/localStorage';
import { memoizedApiAuthReissueGet } from '@lib/apis/auth/apiAuthReissueGet';
 
export const AUTH_SERVER_HOST = {
  production: 'auth.realworld.to',
  development: 'auth-test.realworld.to'
}[APP_ENV];
 
const configuration = new AuthInterfaceConfiguration({
  basePath: `https://${AUTH_SERVER_HOST}`
});
 
const defaultAxiosInstance = axios.create({
  withCredentials: true,
  baseURL: `https://${AUTH_SERVER_HOST}`
});
const tokenRefreshAxiosInstance = axios.create({
  withCredentials: true,
  baseURL: `https://${AUTH_SERVER_HOST}`
});
tokenRefreshAxiosInstance.interceptors.request.use(async (config) => {
  let token: string | undefined;
 
  try {
    const {
      data: { token: newAccessToken, refreshToken: newRefreshToken }
    } = await memoizedApiAuthReissueGet();
 
    if (newAccessToken && newRefreshToken) {
      setLocalStorage('accessToken', newAccessToken);
      setLocalStorage('refreshToken', newRefreshToken);
    } else {
      throw new Error('No token or refreshToken');
    }
 
    token = newAccessToken;
  } catch (e) {
    alert('리얼월드 로그인이 필요한 콘텐츠입니다. 로그인 페이지로 이동합니다.');
 
    window.location.href = getLoginUrl(window.location.href);
  }
 
  config.headers.Authorization = `Bearer ${token}`;
 
  return config;
});
 
export const authWithTokenApi = new AuthApi(configuration, undefined, tokenRefreshAxiosInstance);
export const authApi = new AuthApi(configuration, undefined, defaultAxiosInstance);