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

Undo file changes in analytics platform #2532

Merged
merged 1 commit into from
Feb 26, 2025
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
125 changes: 8 additions & 117 deletions src/platform/src/core/utils/protectedRoute.js
Original file line number Diff line number Diff line change
@@ -1,138 +1,29 @@
import React, { useEffect, useState } from 'react';
import React, { useEffect } from 'react';
import { useRouter } from 'next/router';
import { useSelector, useDispatch } from 'react-redux';
import Cookies from 'js-cookie';
import jwt_decode from 'jwt-decode';
import {
setUserInfo,
setSuccess,
resetStore,
} from '@/lib/store/services/account/LoginSlice';
import { getIndividualUserPreferences } from '@/lib/store/services/account/UserDefaultsSlice';
import { getUserDetails } from '@/core/apis/Account';
import Spinner from '../../common/components/Spinner';

const MAX_RETRIES = 3;
const RETRY_DELAY = 1000;
const LOGIN_ROUTE = '/account/login';
import LogoutUser from '@/core/utils/LogoutUser';

export default function withAuth(Component) {
return function WithAuthComponent(props) {
const dispatch = useDispatch();
const router = useRouter();
const userCredentials = useSelector((state) => state.login);
const [isRedirecting, setIsRedirecting] = useState(
router.query.success === 'google',
);
const [redirectToLogin, setRedirectToLogin] = useState(false);
const [isMounted, setIsMounted] = useState(false);

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;
}
};

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));
setIsRedirecting(false); // Clear redirecting state after success
};

useEffect(() => {
// Mark as mounted only once
if (!isMounted) {
setIsMounted(true);
}

if (typeof window === 'undefined') return;

const handleAuth = async () => {
// Handle Google redirect
if (router.query.success === 'google') {
try {
const token = Cookies.get('temp_access_token');
if (!token) {
throw new Error('No access_token cookie found');
}

localStorage.setItem('token', token);
const decoded = jwt_decode(token);
const response = await retryWithDelay(() =>
getUserDetails(decoded._id, token),
);
await setupUserSession(response.users[0]);
} catch (error) {
console.error('Google auth error:', error);
setIsRedirecting(false);
setRedirectToLogin(true);
}
return;
}

// Handle authentication checks
if (typeof window !== 'undefined') {
const storedUserGroup = localStorage.getItem('activeGroup');

if (!userCredentials.success) {
setRedirectToLogin(true);
return;
router.push('/account/login');
}

if (!storedUserGroup) {
dispatch(resetStore());
if (typeof window !== 'undefined') {
localStorage.clear();
}
const store = router.store || window.__NEXT_REDUX_STORE__;
if (store?.__persistor) {
await store.__persistor.purge();
}
setRedirectToLogin(true);
LogoutUser(dispatch, router);
}
};

handleAuth();
}, [
userCredentials.success,
dispatch,
router.query.success,
retryWithDelay,
]);

useEffect(() => {
if (isMounted && redirectToLogin) {
router.push(LOGIN_ROUTE);
}
}, [isMounted, redirectToLogin, router]);

if (isRedirecting) {
return <Spinner width={20} height={20} />;
}
}, [userCredentials, dispatch, router]);

// Render the component if the user is authenticated
return userCredentials.success ? <Component {...props} /> : null;
};
}
Expand Down
4 changes: 2 additions & 2 deletions src/platform/src/pages/Home/index.jsx
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import dynamic from 'next/dynamic';
// Import statements
import withAuth from '@/core/utils/protectedRoute';
import React, { useState, useEffect, useCallback, useMemo } from 'react';
import Layout from '@/components/Layout';
Expand Down Expand Up @@ -302,4 +302,4 @@ const Home = () => {
);
};

export default dynamic(() => Promise.resolve(withAuth(Home)), { ssr: false });
export default withAuth(Home);
24 changes: 0 additions & 24 deletions src/platform/src/pages/account/login/index.jsx
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,6 @@ import {
} from '@/lib/store/services/account/LoginSlice';
import { getIndividualUserPreferences } from '@/lib/store/services/account/UserDefaultsSlice';
import { postUserLoginDetails, getUserDetails } from '@/core/apis/Account';
import { GOOGLE_AUTH_URL } from '@/core/urls/authentication';

const MAX_RETRIES = 3;
const RETRY_DELAY = 1000;
Expand Down Expand Up @@ -111,15 +110,6 @@ const UserLogin = () => {
dispatch(setUserData({ key, value }));
};

const handleGoogleLogin = async () => {
try {
// Redirect to Google auth URL
window.location.href = GOOGLE_AUTH_URL;
} catch (error) {
console.error('Login error:', error);
}
};

return (
<AccountPageLayout
pageTitle="AirQo Analytics | Login"
Expand Down Expand Up @@ -178,7 +168,6 @@ const UserLogin = () => {
</div>
</div>
</div>

<div className="mt-10">
<button
data-testid="login-btn"
Expand All @@ -192,19 +181,6 @@ const UserLogin = () => {
'Login'
)}
</button>

<button
data-testid="google-login-btn"
className="w-full btn border-blue-900 rounded-[12px] text-white text-sm outline-none border"
disabled={loading}
onClick={handleGoogleLogin}
>
{loading ? (
<Spinner data-testid="spinner" width={25} height={25} />
) : (
'Login with Google'
)}
</button>
</div>
</form>
<div className="mt-8 w-full flex justify-center">
Expand Down
Loading