Browse Source

token update

master
Alex Cheung 1 year ago
parent
commit
d483714a4b
3 changed files with 228 additions and 181 deletions
  1. +33
    -0
      src/auth/index.js
  2. +12
    -5
      src/components/AutoLogoutProvider.js
  3. +183
    -176
      src/pages/Payment/index.js

+ 33
- 0
src/auth/index.js View File

@@ -203,3 +203,36 @@ export const SetupAxiosInterceptors = () => {
) )
} }

export const handleRefreshTokenFunction = () => {
// const token = localStorage.getItem('accessToken');
let isRefresh = false;
if (!isRefresh) {
const refreshToken = localStorage.getItem('refreshToken');
isRefresh = true;
axios.post(`${apiPath}${REFRESH_TOKEN}`, {
refreshToken: refreshToken
}).then((response) => {
if (response.status === 200) {
const newAccessToken = response.data.accessToken;
const newRefreshToken = response.data.refreshToken;
localStorage.setItem('accessToken', newAccessToken);
localStorage.setItem('refreshToken', newRefreshToken);
// token = newAccessToken;
isRefresh = false;
} else {
// token = null;
isRefresh = false;
}
})
.catch((refreshError) => {
console.log('Failed to refresh token');
console.log(refreshError)
// token = null
isRefresh = false;
});
}

return isRefresh;
}

+ 12
- 5
src/components/AutoLogoutProvider.js View File

@@ -22,6 +22,7 @@ const AutoLogoutProvider = ({ children }) => {
const [lastRequestTime, setLastRequestTime] = useState(Date.now()); const [lastRequestTime, setLastRequestTime] = useState(Date.now());
const navigate = useNavigate(); const navigate = useNavigate();
const [logoutInterval, setLogoutInterval] = useState(1); const [logoutInterval, setLogoutInterval] = useState(1);
// const [remainingInterval] = useState(5);
const [state, setState] = useState('Active'); const [state, setState] = useState('Active');
const dispatch = useDispatch() const dispatch = useDispatch()


@@ -36,7 +37,7 @@ const AutoLogoutProvider = ({ children }) => {
} }


const { const {
getRemainingTime,
// getRemainingTime,
//getTabId, //getTabId,
isLastActiveTab, isLastActiveTab,
} = useIdleTimer({ } = useIdleTimer({
@@ -88,11 +89,13 @@ const AutoLogoutProvider = ({ children }) => {
// console.log(logoutInterval) // console.log(logoutInterval)
const interval = setInterval(async () => { const interval = setInterval(async () => {
const currentTime = Date.now(); const currentTime = Date.now();
getRemainingTime();
// getRemainingTime();
if(state !== "Active" && lastActiveTab){ if(state !== "Active" && lastActiveTab){
const timeElapsed = currentTime - lastRequestTime; const timeElapsed = currentTime - lastRequestTime;
// console.log(parseInt(timeElapsed/1000)); // console.log(parseInt(timeElapsed/1000));
// console.log(logoutInterval* 60); // console.log(logoutInterval* 60);
// console.log(remainingInterval * 60);
// console.log(logoutInterval * 60 * 1000 - timeElapsed)
if (timeElapsed >= logoutInterval * 60 * 1000) { if (timeElapsed >= logoutInterval * 60 * 1000) {
if(isUserLoggedIn()){ if(isUserLoggedIn()){
alert("登入驗證已過期,請重新登入。") alert("登入驗證已過期,請重新登入。")
@@ -102,9 +105,13 @@ const AutoLogoutProvider = ({ children }) => {
} }
} }
} }
else if(state === "Active"){
//TODO: if is active and remaining time < 5 min then refresh token
}
// else if(state === "Active"){
// const timeElapsed = currentTime - lastRequestTime;
// if ( (logoutInterval * 60 * 1000 - timeElapsed) <= remainingInterval * 60 * 1000){

// }
// //TODO: if is active and remaining time < 5 min then refresh token
// }
}, 1000); // Check every second }, 1000); // Check every second


return () => { return () => {


+ 183
- 176
src/pages/Payment/index.js View File

@@ -10,6 +10,7 @@ import { useNavigate, useLocation } from "react-router-dom";
// import * as FormatUtils from "utils/FormatUtils"; // import * as FormatUtils from "utils/FormatUtils";
// const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent'))); // const LoadingComponent = Loadable(React.lazy(() => import('pages/extra-pages/LoadingComponent')));
import * as Utils from "auth/utils"; import * as Utils from "auth/utils";
import { handleRefreshTokenFunction } from 'auth/index';


import { import {
Button, Button,
@@ -148,30 +149,11 @@ const Index = () => {
paymentMethod = "01,PPSB,PPS"; paymentMethod = "01,PPSB,PPS";
} }
if (paymentMethod != "") {
HttpUtils.post({
url: UrlUtils.PAYMENT_CREATE,
params: {
transNo: transactionData.transactionid,
payMethod: paymentMethod,
payAmount: totalAmount,
appIdList: location.state?.appIdList ?? []
},
onSuccess: function (responData) {
localStorage.removeItem("paymentId");
localStorage.setItem("paymentId", responData.id)
setOnPayment(false)
navigate(page, stateParams);
}
});
}

//For testing
// if (paymentMethod != "") { // if (paymentMethod != "") {
// HttpUtils.post({ // HttpUtils.post({
// url: UrlUtils.PAYMENT_CREATE, // url: UrlUtils.PAYMENT_CREATE,
// params: { // params: {
// transNo: "test0002",
// transNo: transactionData.transactionid,
// payMethod: paymentMethod, // payMethod: paymentMethod,
// payAmount: totalAmount, // payAmount: totalAmount,
// appIdList: location.state?.appIdList ?? [] // appIdList: location.state?.appIdList ?? []
@@ -179,44 +161,69 @@ const Index = () => {
// onSuccess: function (responData) { // onSuccess: function (responData) {
// localStorage.removeItem("paymentId"); // localStorage.removeItem("paymentId");
// localStorage.setItem("paymentId", responData.id) // localStorage.setItem("paymentId", responData.id)
// setOnPayment(false)
// const result = handleRefreshTokenFunction();
// console.log(result)
// navigate(page, stateParams); // navigate(page, stateParams);
// } // }
// }); // });
// } // }
}
}, [afterConfirmPayment]);


const getAvailablePayment = () =>{
HttpUtils.post({
url: UrlUtils.PAYMENT_AVAILABLE_PAYMENT,
params: {
"locale": locale === 'en' ?Utils.local.en:locale === 'zh-HK' ?Utils.local.zh:Utils.local.cn,
"amount": totalAmount,
// "eserviceids": [
// "<eserviceid>", "<eserviceid>"
// ],
"preferpaymentmethods": Utils.preferpaymentmethods
},
onSuccess: (responseData) => {
let availableMethods = responseData.availablepaymentmethods;
setAvailableMethods(availableMethods);
HttpUtils.get({
url: UrlUtils.PAYMENT_LIMIT_SETTING_LIST,
params: {},
onSuccess: (responseData) => {
// console.log(responseData)
setPaymentLimit(responseData)
//For testing
if (paymentMethod != "") {
HttpUtils.post({
url: UrlUtils.PAYMENT_CREATE,
params: {
transNo: "test0002",
payMethod: paymentMethod,
payAmount: totalAmount,
appIdList: location.state?.appIdList ?? []
}, },
onError: () =>{
// setOnReady(true)
onSuccess: function (responData) {
localStorage.removeItem("paymentId");
localStorage.setItem("paymentId", responData.id)
let result = handleRefreshTokenFunction();
console.log(result)
if(result){
navigate(page, stateParams);
}
} }
}); });
},
onError: () =>{
setOnReady(true)
} }
});
}
}, [afterConfirmPayment]);

const getAvailablePayment = () =>{
// HttpUtils.post({
// url: UrlUtils.PAYMENT_AVAILABLE_PAYMENT,
// params: {
// "locale": locale === 'en' ?Utils.local.en:locale === 'zh-HK' ?Utils.local.zh:Utils.local.cn,
// "amount": totalAmount,
// // "eserviceids": [
// // "<eserviceid>", "<eserviceid>"
// // ],
// "preferpaymentmethods": Utils.preferpaymentmethods
// },
// onSuccess: (responseData) => {
// let availableMethods = responseData.availablepaymentmethods;
// setAvailableMethods(availableMethods);
// HttpUtils.get({
// url: UrlUtils.PAYMENT_LIMIT_SETTING_LIST,
// params: {},
// onSuccess: (responseData) => {
// // console.log(responseData)
// setPaymentLimit(responseData)
// },
// onError: () =>{
// // setOnReady(true)
// }
// });
// },
// onError: () =>{
// setOnReady(true)
// }
// });
HttpUtils.get({ HttpUtils.get({
url: UrlUtils.PAYMENT_LIMIT_SETTING_LIST, url: UrlUtils.PAYMENT_LIMIT_SETTING_LIST,
@@ -231,133 +238,133 @@ const Index = () => {
} }
}); });


// const responseData = {
// "availablepaymentmethods": [
// {
// "active": "Y",
// "code": "04,BCFP,FPS",
// "pointstonote": [
// {
// "content": "Please take note of the transaction reference number or PRINT this page for making enquiry on the payment status when necessary.",
// "order": 10,
// "type": "INFO"
// },
// {
// "content": "After pressing the 'Pay' button, please DO NOT leave this e-service until you receive the acknowledgement page, otherwise your transaction may not be successful.",
// "order": 11,
// "type": "INFO"
// }
// ],
// "subtype": "FPS"
// },
// {
// "active": "Y",
// "code": "02,BCMP,CreditCard",
// "pointstonote": [
// {
// "content": "Please take note of the transaction reference number or PRINT this page for making enquiry on the payment status when necessary.",
// "order": 10,
// "type": "INFO"
// },
// {
// "content": "After pressing the 'Pay' button, please DO NOT leave this e-service until you receive the acknowledgement page, otherwise your transaction may not be successful.",
// "order": 11,
// "type": "INFO"
// },
// {
// "content": "Merchant Name is applicable to credit card payment method only.",
// "order": 40,
// "type": "INFO"
// },
// {
// "content": "Under exceptional conditions, a refund may need to be arranged. If the payment is made by Credit Card, the refund can normally be made to the Credit Card account that is used for the payment.",
// "order": 41,
// "type": "INFO"
// },
// {
// "content": "Some users may receive an error page or have to wait for several minutes before they get a response from the credit card payment gateway. If you experience such a problem, please wait a moment and retry, or change to use other available payment methods. We apologise for any inconvenience caused.",
// "order": 42,
// "type": "INFO"
// },
// {
// "content": "Different credit card issuers may have implemented different mechanisms to authenticate the cardholder's identity during online payment. Please contact your card issuer if you want to learn more about the J/Secure, MasterCard SecureCode and Verified by Visa service. ",
// "order": 43,
// "type": "INFO"
// }
// ],
// "subtype": "CreditCard",
// "supportedcard": [
// "JCB",
// "MasterCard",
// "Visa"
// ]
// },
// {
// "active": "Y",
// "code": "03,BCMP,CreditCard",
// "pointstonote": [
// {
// "content": "Please take note of the transaction reference number or PRINT this page for making enquiry on the payment status when necessary.",
// "order": 10,
// "type": "INFO"
// },
// {
// "content": "After pressing the 'Pay' button, please DO NOT leave this e-service until you receive the acknowledgement page, otherwise your transaction may not be successful.",
// "order": 11,
// "type": "INFO"
// },
// {
// "content": "Merchant Name is applicable to credit card payment method only.",
// "order": 40,
// "type": "INFO"
// },
// {
// "content": "Under exceptional conditions, a refund may need to be arranged. If the payment is made by Credit Card, the refund can normally be made to the Credit Card account that is used for the payment.",
// "order": 41,
// "type": "INFO"
// },
// {
// "content": "Some users may receive an error page or have to wait for several minutes before they get a response from the credit card payment gateway. If you experience such a problem, please wait a moment and retry, or change to use other available payment methods. We apologise for any inconvenience caused.",
// "order": 42,
// "type": "INFO"
// },
// {
// "content": "Different credit card issuers may have implemented different mechanisms to authenticate the cardholder's identity during online payment. Please contact your card issuer if you want to learn more about the J/Secure, MasterCard SecureCode and Verified by Visa service. ",
// "order": 43,
// "type": "INFO"
// }
// ],
// "subtype": "CreditCard",
// "supportedcard": [
// "UnionPay"
// ]
// },
// {
// "active": "Y",
// "code": "01,PPSB,PPS",
// "pointstonote": [
// {
// "content": "Please take note of the transaction reference number or PRINT this page for making enquiry on the payment status when necessary.",
// "order": 10,
// "type": "INFO"
// },
// {
// "content": "After pressing the 'Pay' button, please DO NOT leave this e-service until you receive the acknowledgement page, otherwise your transaction may not be successful.",
// "order": 11,
// "type": "INFO"
// },
// {
// "content": "PPS Shop&Buy (PPS) does not support payment via browsers of mobile devices (including mobile phones and tablets) at the moment. If you wish to pay by PPS, please change to use desktop computer. ",
// "order": 21,
// "type": "INFO"
// }
// ],
// "subtype": "PPS"
// }
// ]
// };
// let availableMethods = responseData.availablepaymentmethods;
// setAvailableMethods(availableMethods);
const responseData = {
"availablepaymentmethods": [
{
"active": "Y",
"code": "04,BCFP,FPS",
"pointstonote": [
{
"content": "Please take note of the transaction reference number or PRINT this page for making enquiry on the payment status when necessary.",
"order": 10,
"type": "INFO"
},
{
"content": "After pressing the 'Pay' button, please DO NOT leave this e-service until you receive the acknowledgement page, otherwise your transaction may not be successful.",
"order": 11,
"type": "INFO"
}
],
"subtype": "FPS"
},
{
"active": "Y",
"code": "02,BCMP,CreditCard",
"pointstonote": [
{
"content": "Please take note of the transaction reference number or PRINT this page for making enquiry on the payment status when necessary.",
"order": 10,
"type": "INFO"
},
{
"content": "After pressing the 'Pay' button, please DO NOT leave this e-service until you receive the acknowledgement page, otherwise your transaction may not be successful.",
"order": 11,
"type": "INFO"
},
{
"content": "Merchant Name is applicable to credit card payment method only.",
"order": 40,
"type": "INFO"
},
{
"content": "Under exceptional conditions, a refund may need to be arranged. If the payment is made by Credit Card, the refund can normally be made to the Credit Card account that is used for the payment.",
"order": 41,
"type": "INFO"
},
{
"content": "Some users may receive an error page or have to wait for several minutes before they get a response from the credit card payment gateway. If you experience such a problem, please wait a moment and retry, or change to use other available payment methods. We apologise for any inconvenience caused.",
"order": 42,
"type": "INFO"
},
{
"content": "Different credit card issuers may have implemented different mechanisms to authenticate the cardholder's identity during online payment. Please contact your card issuer if you want to learn more about the J/Secure, MasterCard SecureCode and Verified by Visa service. ",
"order": 43,
"type": "INFO"
}
],
"subtype": "CreditCard",
"supportedcard": [
"JCB",
"MasterCard",
"Visa"
]
},
{
"active": "Y",
"code": "03,BCMP,CreditCard",
"pointstonote": [
{
"content": "Please take note of the transaction reference number or PRINT this page for making enquiry on the payment status when necessary.",
"order": 10,
"type": "INFO"
},
{
"content": "After pressing the 'Pay' button, please DO NOT leave this e-service until you receive the acknowledgement page, otherwise your transaction may not be successful.",
"order": 11,
"type": "INFO"
},
{
"content": "Merchant Name is applicable to credit card payment method only.",
"order": 40,
"type": "INFO"
},
{
"content": "Under exceptional conditions, a refund may need to be arranged. If the payment is made by Credit Card, the refund can normally be made to the Credit Card account that is used for the payment.",
"order": 41,
"type": "INFO"
},
{
"content": "Some users may receive an error page or have to wait for several minutes before they get a response from the credit card payment gateway. If you experience such a problem, please wait a moment and retry, or change to use other available payment methods. We apologise for any inconvenience caused.",
"order": 42,
"type": "INFO"
},
{
"content": "Different credit card issuers may have implemented different mechanisms to authenticate the cardholder's identity during online payment. Please contact your card issuer if you want to learn more about the J/Secure, MasterCard SecureCode and Verified by Visa service. ",
"order": 43,
"type": "INFO"
}
],
"subtype": "CreditCard",
"supportedcard": [
"UnionPay"
]
},
{
"active": "Y",
"code": "01,PPSB,PPS",
"pointstonote": [
{
"content": "Please take note of the transaction reference number or PRINT this page for making enquiry on the payment status when necessary.",
"order": 10,
"type": "INFO"
},
{
"content": "After pressing the 'Pay' button, please DO NOT leave this e-service until you receive the acknowledgement page, otherwise your transaction may not be successful.",
"order": 11,
"type": "INFO"
},
{
"content": "PPS Shop&Buy (PPS) does not support payment via browsers of mobile devices (including mobile phones and tablets) at the moment. If you wish to pay by PPS, please change to use desktop computer. ",
"order": 21,
"type": "INFO"
}
],
"subtype": "PPS"
}
]
};
let availableMethods = responseData.availablepaymentmethods;
setAvailableMethods(availableMethods);
} }


useEffect(() => { useEffect(() => {


Loading…
Cancel
Save