Refresh Token

This commit is contained in:
yonghyon
2024-05-16 18:38:03 +09:00
parent 014bfca774
commit 1ddbfb272e
12 changed files with 96 additions and 150 deletions

View File

@@ -13,10 +13,10 @@ import {
getSystemSettings,
setExitApp,
} from "../actions/commonActions";
import { getAuthenticationCode } from "../actions/deviceActions";
import { getHomeMenu, getHomeTerms } from "../actions/homeActions";
import {
getMyRecommandedKeyword,
getMyUpcomingAlertShow,
setMyTermsWithdraw,
} from "../actions/myPageActions";
import { pushPanel } from "../actions/panelActions";
@@ -39,9 +39,9 @@ function AppBase(props) {
const panels = useSelector((state) => state.panels.panels);
const [isValidCountry, setIsValidCountry] = useState(false);
const [changedCountry, setChangedCountry] = useState(false);
const { httpHeader, appStatus, introTermsAgree } = useSelector(
(state) => state.common
);
const httpHeader = useSelector((state) => state.common.httpHeader);
const appStatus = useSelector((state) => state.common.appStatus);
const introTermsAgree = useSelector((state) => state.common.introTermsAgree);
const termsData = useSelector((state) => state.home.termsData);
const introTermsAgreeRef = usePrevious(introTermsAgree);
@@ -69,6 +69,7 @@ function AppBase(props) {
dispatch(getHomeMenu());
dispatch(getMyRecommandedKeyword());
dispatch(getMyUpcomingAlertShow());
}
//todo deeplink
const launchParams = getLaunchParams();
@@ -98,7 +99,6 @@ function AppBase(props) {
const handleRelaunchEvent = useCallback(() => {
console.log("handleRelaunchEvent started");
dispatch(getAuthenticationCode());
if (introTermsAgreeRef.current) {
initService(false);
}
@@ -186,8 +186,6 @@ function AppBase(props) {
dispatch(
changeAppStatus({ showLoadingPanel: { show: true, type: "launching" } })
);
dispatch(getAuthenticationCode());
dispatch(
getHomeTerms({
mbrNo: appStatus.loginUserData.userInfo,

View File

@@ -8,7 +8,6 @@ export const types = {
// device actions
GET_AUTHENTICATION_CODE: "GET_AUTHENTICATION_CODE",
GET_RE_AUTHENTICATION_CODE: "GET_RE_AUTHENTICATION_CODE",
REGISTER_DEVICE: "REGISTER_DEVICE",
REGISTER_DEVICE_INFO: "REGISTER_DEVICE_INFO",
GET_DEVICE_INFO: "GET_DEVICE_INFO",

View File

@@ -112,6 +112,7 @@ export const getHttpHeaderForServiceRequest =
convertedRes["publish_flag"] = "Y";
const version = res["X-Device-Netcast-Platform-Version"] || "";
convertedRes["os_ver"] = version;
convertedRes["dvc_auth"] = res["X-Authentication"];
//todo: for test
if (serverType !== "system") {
convertedRes["cntry_cd"] = "US";

View File

@@ -1,32 +1,23 @@
import { URLS } from '../api/apiConfig';
import { TAxios } from '../api/TAxios';
import { TAxios, setTokenRefreshing } from '../api/TAxios';
import { types } from './actionTypes';
import { changeLocalSettings } from './commonActions';
// IF-LGSP-000 인증코드 요청
export const getAuthenticationCode = () => (dispatch, getState) => {
const { accessToken } = getState().localSettings;
if (accessToken) {
return;
}
setTokenRefreshing(true);
const onSuccess = (response) => {
console.log("getAuthenticationCode onSuccess: ", response.data);
const accessToken = response.data.data.accessToken;
const refreshToken = response.data.data.refreshToken;
/* TOKEN 발급 관련 변경 시 추후 작업 필요 */
// dispatch({
// type: types.GET_AUTHENTICATION_CODE,
// payload: response.data.data.accessToken,
// });
dispatch(changeLocalSettings({ accessToken }));
dispatch(changeLocalSettings({ accessToken, refreshToken }));
setTokenRefreshing(false);
};
const onFail = (error) => {
console.error("getAuthenticationCode onFail: ", error);
setTokenRefreshing(false);
};
TAxios(
@@ -37,7 +28,8 @@ export const getAuthenticationCode = () => (dispatch, getState) => {
{},
{},
onSuccess,
onFail
onFail,
true
);
};
@@ -53,6 +45,7 @@ export const registerDevice = (params) => (dispatch, getState) => {
payload: response.data.data,
retCode: response.data.retCode,
});
dispatch(getAuthenticationCode());
};
const onFail = (error) => {
@@ -67,7 +60,8 @@ export const registerDevice = (params) => (dispatch, getState) => {
{},
{ agreeTerms },
onSuccess,
onFail
onFail,
true
);
};
@@ -130,17 +124,17 @@ export const getDeviceAdditionInfo = () => (dispatch, getState) => {
// 인증번호 재요청 IF-LGSP-096
export const getReAuthenticationCode = () => (dispatch, getState) => {
setTokenRefreshing(true);
const onSuccess = (response) => {
console.log("getReAuthenticationCode onSuccess: ", response.data);
dispatch({
type: types.GET_RE_AUTHENTICATION_CODE,
payload: response.data.data,
});
const accessToken = response.data.data.accessToken;
dispatch(changeLocalSettings({ accessToken }));
setTokenRefreshing(false);
};
const onFail = (error) => {
console.error("getReAuthenticationCode onFail: ", error);
setTokenRefreshing(false);
};
TAxios(
@@ -151,6 +145,7 @@ export const getReAuthenticationCode = () => (dispatch, getState) => {
{},
{},
onSuccess,
onFail
onFail,
true
);
};

View File

@@ -30,7 +30,8 @@ export const getHomeTerms = (props) => (dispatch, getState) => {
{ trmsTpCdList, mbrNo },
{},
onSuccess,
onFail
onFail,
true
);
};

View File

@@ -2,80 +2,17 @@ import axios from 'axios';
import * as HelperMethods from '../utils/helperMethods';
import {
getUrl,
URLS,
getUrl
} from './apiConfig';
import { types } from '../actions/actionTypes';
import { changeLocalSettings } from '../actions/commonActions';
import { getAuthenticationCode, getReAuthenticationCode } from '../actions/deviceActions';
// refresh-token 구현 필요
let tokenRefreshing = false;
export const tokenRefresh = (dispatch, getState, autoLogin, callback) => {
return new Promise((resolve, reject) => {
// console.log('getState ', getState());
// const {serverType} = getState().common.localSettings;
// const url = getUrl(URLS.TOKEN_REFRESH, serverType);
// const webOSVersionReal = getState().common.appStatus.webOSVersionReal;
// const {authenticationResult, tokenRequiredTime, userId} = getState().common.localSettings;
// const deviceId = getState().common.appStatus.deviceId;
// if(!userId){
// console.warn('tokenRefresh : not logged');
// if(callback){
// callback(false);
// }
// return;
// }
// const currentTime = new Date();
// const gap = (currentTime - tokenRequiredTime)/1000;
// const ExpiredIn = Number(authenticationResult.ExpiresIn);
// const limitTime = ExpiredIn - (ExpiredIn * THRESHOLD_AUTH_REFRESH);
// if(!autoLogin && (gap < limitTime || tokenRefreshing)){
// if(callback){
// callback(false);
// }
// return;
// }
// const tokenInfo =
// {
// "authenticationResult": authenticationResult,
// deviceInfo: {
// "deviceId": deviceId,
// "deviceName": "deviceName01",
// "os": "webos",
// "model": webOSVersionReal,
// "serialNumber": "xxxx-xxxx-xxxx-xxxx"
// }
// , "userId" : userId
// };
// if(useQAServerURL !== 'prd'){
// console.log('tokenInfo...', tokenInfo, gap, ExpiredIn);
// }
// try{
// tokenRefreshing = true;
// const response = await axios.put(url, tokenInfo, AUTHORIZATION);
// console.log(' tokenRefresh response....', response);
// Actions.AUTHORIZATION.headers.authorization = response.data.authenticationResult.AccessToken;
// dispatch(CommonActions.changeLocalSettings({authenticationResult:response.data.authenticationResult, tokenRequiredTime: new Date()}));
// console.log('토큰 갱신 완료...');
// if(callback){
// callback(true);
// }
// }catch(res) {
// const error = res && res.toJSON ? res.toJSON() : {};
// console.error('tokenRefresh', error, res);
// if(error.message ){
// if(error.message.indexOf('code 400')
// || error.message.indexOf('code 401')
// || error.message.indexOf('code 403')){
// dispatch(Actions.logout());
// }
// }
// if(callback){
// callback(false);
// }
// };
tokenRefreshing = false;
resolve();
});
export const setTokenRefreshing = (value) =>{
console.log('TAxios setTokenRefreshing ', value);
tokenRefreshing = value;
};
export const TAxios = (
@@ -93,12 +30,14 @@ export const TAxios = (
return new Promise((resolve) => {
const accessToken = getState().localSettings.accessToken;
if (
accessToken ||
baseUrl === URLS.GET_AUTHENTICATION_CODE ||
noTokenRefresh
noTokenRefresh ||
(!tokenRefreshing && accessToken)
) {
resolve(accessToken);
} else {
if(!accessToken && !tokenRefreshing){
dispatch(getAuthenticationCode());
}
HelperMethods.wait(100).then(() => {
resolve(checkAccessToken());
});
@@ -106,15 +45,17 @@ export const TAxios = (
});
};
const executeRequest = (accessToken, getState) => {
const executeRequest = (accessToken, dispatch, getState) => {
const httpHeader = getState().common.httpHeader;
const { mbr_no, deviceId } = getState().common.appStatus;
const refreshToken = getState().localSettings.refreshToken;
const AUTHORIZATION = { headers: { ...httpHeader } };
if (accessToken) {
AUTHORIZATION.headers["lgsp_auth"] = accessToken;
}
AUTHORIZATION.headers["dvc_id"] = deviceId;
AUTHORIZATION.headers["refresh-token"] = refreshToken;
if (typeof window === "object") {
let url = Array.isArray(baseUrl)
@@ -145,6 +86,28 @@ export const TAxios = (
axiosInstance
.then((res) => {
console.log("TAxios response", url, res);
if(res?.data?.retCode === 501){
//약관 비동의
dispatch(changeLocalSettings({accessToken: null}));
dispatch({type: types.GET_TERMS_AGREE_YN, payload: {}});
return;
}
//AccessToken 만료
if(res?.data?.retCode === 401){
dispatch(getReAuthenticationCode());
checkAccessToken().then((accessToken) => {
executeRequest(accessToken, dispatch, getState);
});
return;
}
//RefreshToken 만료
if(res?.data?.retCode === 402 ){
dispatch(getAuthenticationCode());
checkAccessToken().then((accessToken) => {
executeRequest(accessToken, dispatch, getState);
});
return;
}
if (onSuccess) onSuccess(res);
})
.catch((error) => {
@@ -156,15 +119,6 @@ export const TAxios = (
};
checkAccessToken().then((accessToken) => {
if (!noTokenRefresh) {
tokenRefresh(dispatch, getState)
.then(() => executeRequest(accessToken, getState))
.catch((e) => {
/* 토큰 갱신 실패 처리 */
console.error("tokenRefresh error", e);
});
} else {
executeRequest(accessToken, getState);
}
executeRequest(accessToken, dispatch, getState);
});
};

View File

@@ -1,18 +1,12 @@
import { types } from "../actions/actionTypes";
const initialState = {
accessToken: null,
regDeviceData: {},
regDeviceInfoData: {},
};
export const deviceReducer = (state = initialState, action) => {
switch (action.type) {
case types.GET_AUTHENTICATION_CODE:
return {
...state,
accessToken: action.payload,
};
case types.REGISTER_DEVICE:
return {
...state,

View File

@@ -30,22 +30,23 @@ export const homeReducer = (state = initialState, action) => {
let menuItems = [];
const menuData = action.payload.data;
const info = menuData.gnb.map((item) => {
return {
menuNm: item.menuNm,
menuId: item.menuId,
};
});
for (let i = 0; i < info.length; i++) {
const title = info[i].menuNm;
const menuId = info[i].menuId;
menuItems.push({
title: title,
menuId: menuId,
if(menuData?.gnb){
const info = menuData.gnb.map((item) => {
return {
menuNm: item.menuNm,
menuId: item.menuId,
};
});
}
for (let i = 0; i < info.length; i++) {
const title = info[i].menuNm;
const menuId = info[i].menuId;
menuItems.push({
title: title,
menuId: menuId,
});
}
}
return {
...state,
menuData: action.payload,
@@ -63,7 +64,7 @@ export const homeReducer = (state = initialState, action) => {
return {
...state,
mainContentsData: action.payload,
bannerData: action.payload.homeMainContentsBannerInfos[0],
bannerData: action.payload.homeMainContentsBannerInfos ? action.payload.homeMainContentsBannerInfos[0]: initialState.bannerData,
};
case types.GET_THEME_CURATION_INFO:

View File

@@ -6,6 +6,7 @@ const initialLocalSettings = {
serverType: Config.DEFAULT_SERVERTYPE,
ricCodeSetting: Config.DEFAULT_RIC_CODE,
accessToken: null,
refreshToken: null,
phoneNumbers: {},
};

View File

@@ -141,13 +141,19 @@ export default function IntroPanel({
panelInfo: { eventInfos: eventInfos },
})
);
} else if (
eventInfos &&
eventInfos.welcomeEventFlag === "N" &&
eventInfos.welcomeBillCpnEventFlag === "N"
) {
dispatch(popPanel(panel_names.INTRO_PANEL));
}
// } else if (
// eventInfos &&
// eventInfos.welcomeEventFlag === "N" &&
// eventInfos.welcomeBillCpnEventFlag === "N"
// ) {
// dispatch(popPanel(panel_names.INTRO_PANEL));
// }
} else if ( //todo yhcho 조건체크 ??
eventInfos &&
eventInfos.welcomeEventFlag === "N"
) {
dispatch(popPanel(panel_names.INTRO_PANEL));
}
}, [eventInfos, dispatch]);
const description = $L(

View File

@@ -213,10 +213,6 @@ export default function MainView() {
};
}, []);
useEffect(() => {
dispatch(getMyUpcomingAlertShow());
}, [dispatch]);
const [watchPopOpen, setWatchPopOpen] = useState(false);
const onWatchClose = useCallback(() => {
setIntervalActive((prev) => !prev);

View File

@@ -28,7 +28,7 @@ export default function OrderList({ orderInfo }) {
{orderInfo &&
orderInfo.map((order, index) => {
return (
<div className={css.orderBorder}>
<div className={css.orderBorder} key={index}>
<div className={css.orderNmInfo}>
<p className={css.orderTitle}>
ORDER NUMBER :{" "}