Skip to content

Commit

Permalink
update and adjust code
Browse files Browse the repository at this point in the history
  • Loading branch information
Clue355 committed Jul 10, 2024
1 parent d66ad9d commit 409a89f
Show file tree
Hide file tree
Showing 3 changed files with 75 additions and 65 deletions.
49 changes: 41 additions & 8 deletions context/AuthContextProvider.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ import { account } from '../api/config';
import Alert from '../components/AlertNotification/AlertNotification';
import { AlertVariants } from '../components/AlertNotification/Alerts.enum';
import { toast } from 'react-hot-toast';
import { loginAccount } from './AuthHelper';
import { loginAccount, logoutAccount } from './AuthHelper';
import { NextRouter } from 'next/router';

const mockCreateEmailPasswordSession = jest.fn();
Expand Down Expand Up @@ -32,21 +32,29 @@ describe('AuthContextProvider', () => {
password: 'password1234',
});

const setIsSignedIn = jest.fn();
const resetUser = jest.fn();

beforeEach(() => {
jest.clearAllMocks();
});

test('should show success notification after a successful login', async () => {

mockCreateEmailPasswordSession.mockResolvedValue({});

await loginAccount({user, router, getUser});
await loginAccount({ user, router, getUser });

expect(mockCreateEmailPasswordSession).toHaveBeenCalledWith(user.email, user.password);
expect(mockCreateEmailPasswordSession).toHaveBeenCalledWith(
user.email,
user.password,
);
expect(getUser).toHaveBeenCalled();
expect(router.push).toHaveBeenCalledWith('/league/all');
expect(toast.custom).toHaveBeenCalledWith(
<Alert variant={AlertVariants.Success} message="You've successfully logged in!" />,
<Alert
variant={AlertVariants.Success}
message="You've successfully logged in!"
/>,
);
});

Expand All @@ -55,11 +63,36 @@ describe('AuthContextProvider', () => {

mockCreateEmailPasswordSession.mockRejectedValue(mockError);

const error = await loginAccount({user, router, getUser});
const error = await loginAccount({ user, router, getUser });

expect(error).toEqual(mockError);
expect(toast.custom).toHaveBeenCalledWith(
<Alert variant={AlertVariants.Error} message="Something went wrong!" />,
);
});

//logout tests
test('after a successful logout it shows success notification', async () => {
await logoutAccount({ resetUser, setIsSignedIn, router });

expect(setIsSignedIn).toHaveBeenCalledWith(false);
expect(resetUser).toHaveBeenCalled();
expect(router.push).toHaveBeenCalledWith('/login');
expect(toast.custom).toHaveBeenCalledWith(
<Alert variant={AlertVariants.Success} message="Logged Out" />,
);
});

test('after logout attempt errors it shows error notification', async () => {
const mockError = new Error('Logout error');

account.deleteSession = jest.fn().mockRejectedValue(mockError);

const error = await logoutAccount({ resetUser, setIsSignedIn, router });

expect(error).toEqual(mockError);
expect(toast.custom).toHaveBeenCalledWith(
<Alert variant={AlertVariants.Error} message="Something went wrong!" />,
<Alert variant={AlertVariants.Error} message="Logout failed!" />,
);
});
});
});
17 changes: 12 additions & 5 deletions context/AuthContextProvider.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ type AuthContextType = {
isSignedIn: boolean;
setIsSignedIn: React.Dispatch<React.SetStateAction<boolean>>;
loginAccount: (user: UserCredentials) => Promise<void | Error>; // eslint-disable-line no-unused-vars
logoutAccount: () => Promise<void>;
logoutAccount: () => Promise<void | Error>;
getUser: () => Promise<IUser | undefined>;
};

Expand Down Expand Up @@ -62,8 +62,8 @@ export const AuthContextProvider = ({
const loginAccount = async (user: UserCredentials): Promise<void | Error> => {
try {
await account.createEmailPasswordSession(user.email, user.password);
await getUser(); // Fetch user data and update state
router.push('/league/all');
getUser();
router.push('/weeklyPicks');
toast.custom(
<Alert
variant={AlertVariants.Success}
Expand All @@ -81,16 +81,23 @@ export const AuthContextProvider = ({

/**
* Log out and clear session state
* @returns {Promise<void>}
* @returns {Promise<void | Error>}
*/
const logoutAccount = async (): Promise<void> => {
const logoutAccount = async (): Promise<void | Error> => {
try {
await account.deleteSession('current');
setIsSignedIn(false);
resetUser(); // Reset user data in the store
toast.custom(
<Alert variant={AlertVariants.Success} message="Logged Out" />,
);
router.push('/login');
} catch (error) {
toast.custom(
<Alert variant={AlertVariants.Error} message="Logout failed!" />,
);
console.error('Logout error:', error);
return error as Error;
}
};

Expand Down
74 changes: 22 additions & 52 deletions context/AuthHelper.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -15,21 +15,6 @@ type UserCredentials = {
password: string;
};

/**
* Authenticate and set session state
* @param user.user
* @param user.email
* @param user.password
* @param user - the user credentials
* @param router - router function
* @param getUser - getUser() function
* @param user.router
* @param user.getUser
* @param getUser.user
* @param getUser.router
* @param getUser.getUser
* @returns The error if there is one
*/
export const loginAccount = async ({
user,
router,
Expand Down Expand Up @@ -59,46 +44,31 @@ export const loginAccount = async ({
};

/**
* Get user data from the session
* @param router - router to navigate the page
* @param updateUser - updateUser() function
* @param resetUser - resetUser() function
* @param setIsSignedIn - changes to false if errors
* Log out and clear session state
* @returns {Promise<void>}
*/
export const getUser = async (
router: NextRouter,
updateUser: (id: string, email: string, leagues: any) => void,
resetUser: () => void,
setIsSignedIn: (value: boolean) => void,
) => {
if (!isSessionInLocalStorage()) {
router.push('/login');
return;
}

export const logoutAccount = async ({
resetUser,
setIsSignedIn,
router,
}: {
resetUser: () => void;
setIsSignedIn: (bool: false) => void;
router: NextRouter;
}): Promise<void | Error> => {
try {
const user = await account.get();
const userData: IUser = await getCurrentUser(user.$id);
updateUser(userData.id, userData.email, userData.leagues);
return userData;
} catch (error) {
resetUser();
await account.deleteSession('current');
setIsSignedIn(false);
resetUser(); // Reset user data in the store
toast.custom(
<Alert variant={AlertVariants.Success} message="Logged Out" />,
);
router.push('/login');
} catch (error) {
toast.custom(
<Alert variant={AlertVariants.Error} message="Logout failed!" />,
);
console.error('Logout error:', error);
return error as Error;
}
};

/**
* Helper function to validate session data in local storage
* @returns {boolean} - Whether the session is in local storage.
*/
const isSessionInLocalStorage = (): boolean => {
const loadedDataString = localStorage.getItem('cookieFallback');

if (!loadedDataString || loadedDataString === '[]') {
localStorage.removeItem('cookieFallback');
return false;
}

return true;
};

0 comments on commit 409a89f

Please sign in to comment.