Skip to content

Commit

Permalink
handle google redirect logic
Browse files Browse the repository at this point in the history
  • Loading branch information
Codebmk committed Feb 25, 2025
1 parent 1798bec commit ee0e231
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/platform/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@
"fuse.js": "^7.0.0",
"html2canvas": "^1.4.1",
"i18n-iso-countries": "^7.7.0",
"js-cookie": "^3.0.5",
"json2csv": "^6.0.0-alpha.2",
"jspdf": "^2.5.2",
"jspdf-autotable": "^3.8.4",
Expand Down
91 changes: 91 additions & 0 deletions src/platform/src/pages/Home/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,18 @@ import {
import HomeSkeleton from '@/components/skeletons/HomeSkeleton';
import CustomModal from '@/components/Modal/videoModals/CustomModal';
import StepProgress from '@/components/steppers/CircularStepper';
import Cookies from 'js-cookie';
import jwt_decode from 'jwt-decode';
import { useRouter } from 'next/router';
import {
setUserInfo,
setSuccess,
} from '@/lib/store/services/account/LoginSlice';
import { getIndividualUserPreferences } from '@/lib/store/services/account/UserDefaultsSlice';
import { getUserDetails } from '@/core/apis/Account';

const MAX_RETRIES = 3;
const RETRY_DELAY = 1000;

// Video URL constant
const ANALYTICS_VIDEO_URL =
Expand Down Expand Up @@ -60,13 +72,16 @@ const createSteps = (handleModal, handleCardClick) => [

const Home = () => {
const dispatch = useDispatch();
const router = useRouter();

// Selectors
const checkListData = useSelector((state) => state.checklists.checklist);
const cardCheckList = useSelector((state) => state.cardChecklist.cards);
const checkListStatus = useSelector((state) => state.checklists.status);

// State hooks
const [loading, setLoading] = useState(false);

const [open, setOpen] = useState(false);
const [step, setStep] = useState(0);
const totalSteps = 4;
Expand All @@ -85,6 +100,82 @@ const Home = () => {
return null;
}, []);

const retryWithDelay = async (fn, retries = MAX_RETRIES) => {
try {
return await fn();
} catch (error) {
if (retries > 0 && error.response?.status === 429) {
await new Promise((resolve) => setTimeout(resolve, RETRY_DELAY));
return retryWithDelay(fn, retries - 1);
}
throw error;
}
};

// Refactored session setup logic for reuse
const setupUserSession = async (user) => {
if (!user.groups[0]?.grp_title) {
throw new Error(
'Server error. Contact support to add you to the AirQo Organisation',
);
}

localStorage.setItem('loggedUser', JSON.stringify(user));

const preferencesResponse = await retryWithDelay(() =>
dispatch(getIndividualUserPreferences({ identifier: user._id })),
);
if (preferencesResponse.payload.success) {
const preferences = preferencesResponse.payload.preferences;
const activeGroup = preferences[0]?.group_id
? user.groups.find((group) => group._id === preferences[0].group_id)
: user.groups.find((group) => group.grp_title === 'airqo');
localStorage.setItem('activeGroup', JSON.stringify(activeGroup));
}

dispatch(setUserInfo(user));
dispatch(setSuccess(true));
router.push('/Home');
};

// Handle Google redirect
useEffect(() => {
const handleGoogleRedirect = async () => {
if (router.query.success === 'google') {
setLoading(true);
try {
// Retrieve the access_token cookie using js-cookie
const token = Cookies.get('access_token');
if (!token) {
throw new Error('No access_token cookie found');
}

// Store the token in localStorage as 'token'
localStorage.setItem('token', token);
const decoded = jwt_decode(token);

// Fetch user details using the token
const response = await retryWithDelay(() =>
getUserDetails(decoded._id, token),
);
const user = response.users[0];

await setupUserSession(user);
} catch (error) {
dispatch(setSuccess(false));
setLoading(false);
throw error;
}
}
};

handleGoogleRedirect();
}, [router, dispatch]);

if (loading) {
return <HomeSkeleton />;
}

// Handlers
const handleModal = useCallback(() => {
setOpen((prev) => !prev);
Expand Down
5 changes: 5 additions & 0 deletions src/platform/yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5252,6 +5252,11 @@ js-cookie@^2.2.1:
resolved "https://registry.yarnpkg.com/js-cookie/-/js-cookie-2.2.1.tgz#69e106dc5d5806894562902aa5baec3744e9b2b8"
integrity sha512-HvdH2LzI/EAZcUwA8+0nKNtWHqS+ZmijLA30RwZA0bo7ToCckjK5MkGhjED9KoRcXO6BaGI3I9UIzSA1FKFPOQ==

js-cookie@^3.0.5:
version "3.0.5"
resolved "https://registry.yarnpkg.com/js-cookie/-/js-cookie-3.0.5.tgz#0b7e2fd0c01552c58ba86e0841f94dc2557dcdbc"
integrity sha512-cEiJEAEoIbWfCZYKWhVwFuvPX1gETRYPw6LlaTKoxD3s2AkXzkCjnp6h0V77ozyqj0jakteJ4YqDJT830+lVGw==

"js-tokens@^3.0.0 || ^4.0.0", js-tokens@^4.0.0:
version "4.0.0"
resolved "https://registry.yarnpkg.com/js-tokens/-/js-tokens-4.0.0.tgz#19203fb59991df98e3a287050d4647cdeaf32499"
Expand Down

0 comments on commit ee0e231

Please sign in to comment.