Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(global): ✨ update access token by refresh token #254

Merged
merged 1 commit into from
Jun 27, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions package/components/inputs/forms/CoreForm.js
Original file line number Diff line number Diff line change
Expand Up @@ -81,9 +81,9 @@ class CoreForm extends Component {
let rawFormStatus = this.props.rawFormStatus;

// eslint-disable-next-line id-length
let formOb = await getForm(this.props.formId, this.props.authenticated, {
let formOb = await this.props.GetForm(this.props.formId, this.props.authenticated, {
rawForm,
rawFormStatus,
rawFormStatus
});

formJson = formOb.formJson;
Expand Down Expand Up @@ -706,7 +706,7 @@ class CoreForm extends Component {
let rawForm = this.props.rawFormSchema;
let rawFormStatus = this.props.rawFormStatus;
// eslint-disable-next-line id-length
let t = await getForm(this.props.formId, this.props.authenticated, {
let t = await this.props.GetForm(this.props.formId, this.props.authenticated, {
rawForm,
rawFormStatus,
});
Expand Down Expand Up @@ -1199,6 +1199,16 @@ const mapDispatchToProps = dispatch => {
FormReset: data => {
dispatch(resetFormReducer(data));
},
GetForm: (formId, authenticated, {
rawForm,
rawFormStatus
}) => {
return getForm(formId, authenticated, {
rawForm,
rawFormStatus
},
dispatch);
},
HandleFormSubmit: (
method,
endpoint,
Expand Down
52 changes: 26 additions & 26 deletions package/components/layouts/_system/AppContainerLayout.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,10 +19,7 @@ import { apiRequestAction } from "../../../store/action/appActions";
import { toggleLeftMenuState } from "../../../store/action/menuAction";
import { GET_ROLE_PERMISSION_ERROR, GET_ROLE_PERMISSION_SUCCESS } from "../../../store/types/authTypes";
import { BUILD_MENU_ROLE_PERMISSIONS } from "../../../store/types/menuTypes";
import {
RECALL_TOKEN_REJUVINDATED,
REMOVE_PENDING_REQUESTS
} from "../../../store/types/pendingRequestTypes";
import { REMOVE_PENDING_REQUESTS } from "../../../store/types/pendingRequestTypes";
import { SELECT_OPTION_SUCCESS } from "../../../store/types/selectOptionsTypes";
import {
GET_SETTING_META_ERROR,
Expand All @@ -45,7 +42,7 @@ export default function AppContainerLayout() {
// eslint-disable-next-line etc/no-commented-out-code
const { leftMenuOpen } = useSelector((state) => state?.menu);
const { routes: _routes } = useSelector((state) => state?.route);
const { recall: recallState, pendingRequest: currentPendingRequest } = useSelector((state) => state?.pendingRequests);
const { recall: recallState, requests: allPendingReq } = useSelector((state) => state?.pendingRequests);
const { uid, accessToken } = useSelector((state) => state?.auth || {});

const [leftMenuOpenSmallScreen, setLeftDrawerSmallScreen] = React.useState(false);
Expand Down Expand Up @@ -120,29 +117,32 @@ export default function AppContainerLayout() {
};

React.useEffect(() => {
if (currentPendingRequest && recallState === RECALL_TOKEN_REJUVINDATED) {
dispatch(
apiRequestAction(
currentPendingRequest.method,
currentPendingRequest.endpoint,
currentPendingRequest.authRequired,
currentPendingRequest.data,
currentPendingRequest.successType,
currentPendingRequest.errorType,
currentPendingRequest.localAction,
currentPendingRequest.includeFile,
currentPendingRequest.file,
currentPendingRequest.formId,
currentPendingRequest.reload,
currentPendingRequest.reduxData,
currentPendingRequest.pushSnack,
currentPendingRequest.loadingType,
currentPendingRequest.resetLoadingType
)
);
if (allPendingReq?.length > 0 && recallState === "rejuvinated") {
allPendingReq.forEach(currentPendingRequest => {
dispatch(
apiRequestAction(
currentPendingRequest.method,
currentPendingRequest.endpoint,
currentPendingRequest.authRequired,
currentPendingRequest.data,
currentPendingRequest.successType,
currentPendingRequest.errorType,
currentPendingRequest.localAction,
currentPendingRequest.includeFile,
currentPendingRequest.file,
currentPendingRequest.formId,
currentPendingRequest.reload,
currentPendingRequest.reduxData,
currentPendingRequest.pushSnack,
currentPendingRequest.loadingType,
currentPendingRequest.resetLoadingType
)
);
});
dispatch({ type: REMOVE_PENDING_REQUESTS });
}
});

}, [accessToken]);

React.useEffect(() => {
let components =
Expand Down
2 changes: 1 addition & 1 deletion package/layout/PageContainer.js
Original file line number Diff line number Diff line change
Expand Up @@ -147,7 +147,7 @@ export default function PageContainer(props) {
};

return sessionExpired && !uid && route?.authRequired ? (
<CoreDomNavigate to="/" replace={true} />
<CoreDomNavigate to="checkUserExist" replace={true} />
) : (
<>
{/* <CoreThemeProvider themeID={pageTheme()}> */}
Expand Down
7 changes: 6 additions & 1 deletion package/middleware/axiosInterceptor.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,6 @@
// eslint-disable-next-line import/namespace
import { reloadToken } from "../utils/appUtils";

async function tempFetch(apiConfig) {
// -- console.log("API CALLL", apiConfig);
try {
Expand Down Expand Up @@ -51,7 +54,9 @@ async function tempFetch(apiConfig) {
}
} catch (error) {
// eslint-disable-next-line no-console
console.error(error);
if(error?.response?.status === 401 || error?.response?.status === 403){
reloadToken(apiConfig?.dispatch);
}
throw error;
}

Expand Down
6 changes: 4 additions & 2 deletions package/service/AppService.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,8 @@ class AppService {
authRequired,
data,
includeFile = false,
file = null
file = null,
dispatch = null
) {
try {
let response = await axiosInterceptor({
Expand All @@ -24,10 +25,11 @@ class AppService {
? createFormData(file, data)
: JSON.stringify(data)
: null,
dispatch : dispatch,
externalApi: await this.isUrl(endpoint),
headers : await authHeader(authRequired, includeFile),
method : method.toUpperCase(),
url : await this.getEndpoint(method, endpoint, data),
url : await this.getEndpoint(method, endpoint, data)
});

// -- console.log("API Endpoint = " + endpoint);
Expand Down
17 changes: 2 additions & 15 deletions package/store/action/appActions.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,15 +5,8 @@ import {
LOGIN_WITH_URL_API
} from "../../config/api";
import { HTTP, MESSAGE_TYPE } from "../../config/constants";
import {
globalAccessToken,
globalRefreshToken,
globalTokenRequested,
globalTokenRequestTimeStamp
} from "../../CoreRoutes";
import { formStore } from "../../layout/PageContainer";
import AppService from "../../service/AppService";
import { reloadToken } from "../../utils/appUtils";
import { getForm } from "../../utils/formUtils";
import {
CLEAR_SNACK_MESSAGE,
Expand Down Expand Up @@ -79,7 +72,8 @@ export const apiRequestAction =
authRequired,
data,
includeFile,
file
file,
dispatch
)
.then(async response => {
let formJson = null;
Expand Down Expand Up @@ -231,13 +225,6 @@ export const apiRequestAction =
endpoint !== LOGIN_WITH_URL_API &&
endpoint !== LOGIN_WITH_RESET_PASSWORD_API
) {
reloadToken(
globalRefreshToken,
globalAccessToken,
globalTokenRequested,
globalTokenRequestTimeStamp,
dispatch
);
dispatch({
payload: {
authRequired,
Expand Down
18 changes: 10 additions & 8 deletions package/utils/appUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import moment from "moment";

import { REFRESH_TOKEN_API } from "../config/api";
import { HTTP } from "../config/constants";
import { globalAccessToken, globalRefreshToken, globalTokenRequestTimeStamp, globalTokenRequested } from "../CoreRoutes";
import {
LOGOUT_SUCCESS,
SESSION_EXPIRED,
Expand Down Expand Up @@ -37,23 +38,24 @@ export const getTimestamp = () => {
};

export async function reloadToken(
refreshToken,
accessToken,
tokenRequested,
tokenRequestTimeStamp,
// eslint-disable-next-line etc/no-commented-out-code
// refreshToken,
// accessToken,
// tokenRequested,
// tokenRequestTimeStamp,
dispatch
) {
let diff = moment().diff(tokenRequestTimeStamp, "seconds");
let diff = moment().diff(globalTokenRequestTimeStamp, "seconds");

// -- console.log("__tokenRequested__", tokenRequested, diff);
if (!tokenRequested || diff > 60) {
if (!globalTokenRequested || diff > 60) {
const backendUrl = WrappidData?.config?.backendUrl;

dispatch({ type: TOKEN_REQUESTED });
fetch(backendUrl + REFRESH_TOKEN_API, {
body : JSON.stringify({ refreshToken }),
body : JSON.stringify({ refreshToken: globalRefreshToken }),
headers: {
Authorization : "Bearer " + accessToken,
Authorization : "Bearer " + globalAccessToken,
"Content-Type": "application/json",
},
method: HTTP.POST,
Expand Down
20 changes: 18 additions & 2 deletions package/utils/formUtils.js
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@ import {
UPDATE_DATA_ERROR,
UPDATE_DATA_SUCCESS
} from "../store/types/dataManagementTypes";
import { SET_PENDING_REQUESTS } from "../store/types/pendingRequestTypes";
import CoreClasses from "../styles/CoreClasses";

export function getFormikRequiredMessage(name = "", isShort = false) {
Expand Down Expand Up @@ -717,7 +718,7 @@ export function hookcallCheck(
}
}

export async function getForm(formId, auth = true, formReducer) {
export async function getForm(formId, auth = true, formReducer, dispatch) {
let { config: configuration } = WrappidData;

if (formReducer?.rawForm && formReducer?.rawForm[formId]) {
Expand Down Expand Up @@ -764,7 +765,22 @@ export async function getForm(formId, auth = true, formReducer) {
};
}
} catch (err) {
// eslint-disable-next-line no-console
let url = auth ? GET_FORM_API_AUTHENTICATED : GET_FORM_API;

if(err.status === 401 || err.status === 403){
dispatch({
payload: {
authRequired: auth,
endpoint : url + formId,
formId : formId,
includeFile : false,
localAction : false,
method : HTTP.GET,
reload : false, // need review
},
type: SET_PENDING_REQUESTS,
});
} // eslint-disable-next-line no-console
console.error("Error in form fetch");
return {
formId,
Expand Down
Loading