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

fix things #97

Merged
merged 8 commits into from
Dec 27, 2023
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
3 changes: 1 addition & 2 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -28,12 +28,10 @@
"@mui/material": "^5.11.6",
"@next/env": "^13.2.4",
"@svgr/webpack": "^6.5.1",
"@types/totp-generator": "^0.0.5",
"axios": "^1.6.0",
"axios-middleware": "^0.3.1",
"cookies-next": "^2.1.1",
"cypress": "^13.2.0",
"lodash": "^4.17.21",
"luxon": "^3.3.0",
"next": "^13.2.5-canary.30",
"next-themes": "^0.2.1",
Expand All @@ -49,6 +47,7 @@
"validator": "^13.9.0"
},
"devDependencies": {
"@types/totp-generator": "^0.0.5",
"@types/lodash": "^4.14.191",
"@types/luxon": "^3.3.0",
"@types/node": "18.8.1",
Expand Down
11 changes: 11 additions & 0 deletions src/lib/api/AuthAPI.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import type {
LoginResponse,
PrivateProfile,
RegistrationResponse,
ResendEmailVerificationResponse,
ResetPasswordResponse,
SendPasswordResetEmailResponse,
VerifyEmailResponse,
Expand Down Expand Up @@ -47,6 +48,16 @@ export const sendPasswordResetEmail = async (email: string): Promise<void> => {
await axios.get<SendPasswordResetEmailResponse>(requestUrl);
};

/**
* Resend an email to verify the user's email address.
* @param {string} email The email address to send the password reset email to
*/
export const resendEmailVerification = async (email: string): Promise<void> => {
const requestUrl = `${config.api.baseUrl}${config.api.endpoints.auth.emailVerification}/${email}`;

await axios.get<ResendEmailVerificationResponse>(requestUrl);
};

/**
* Verifies account email by access code to enable full account access
* @param accessCode The access code provided to the user via the link on the email.
Expand Down
32 changes: 18 additions & 14 deletions src/lib/hoc/withAccessType.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import { CookieService } from '@/lib/services';
import type { URL } from '@/lib/types';
import type { PrivateProfile } from '@/lib/types/apiResponses';
import { CookieType, UserAccessType } from '@/lib/types/enums';
import * as _ from 'lodash';
import type { GetServerSideProps, GetServerSidePropsContext } from 'next';
/**
* Redirects to login if user is not logged in and allowed to see the specified page
Expand Down Expand Up @@ -52,31 +51,36 @@ export default function withAccessType(
return loginRedirect;
}

let user: PrivateProfile = JSON.parse(userCookie);
let userAccessLevel = user.accessType;

// If no user cookie, try to re-generate one
if (!userCookie) {
if (!userCookie || !userAccessLevel) {
try {
const userObj = await UserAPI.getCurrentUser(authTokenCookie);
userCookie = JSON.stringify(userObj);
user = await UserAPI.getCurrentUser(authTokenCookie);
userAccessLevel = user.accessType;
userCookie = JSON.stringify(user);
CookieService.setServerCookie(CookieType.USER, JSON.stringify(userCookie), { req, res });
} catch (err: any) {
return loginRedirect;
}
}

/* If the user does not have the right access, redirect as specified */
const user: PrivateProfile = JSON.parse(userCookie);
if (!validAccessTypes.includes(user.accessType)) return missingAccessRedirect;
if (!validAccessTypes.includes(userAccessLevel)) return missingAccessRedirect;

// If we haven't short-circuited, user has valid access. Show the page and add the user prop.
const propsWithUser = {
props: {
user,
},
};
const originalReturnValue = await gssp(context);
// Append user at the start of the originally defined props object so it can be overridden if necessary using deep merge and we don't delete the whole props object
const finalObj = _.merge(propsWithUser, originalReturnValue);
return finalObj;
// Insert the user object to the original return value if it doesn't exist already
if ('props' in originalReturnValue) {
const existingProps = await Promise.resolve(originalReturnValue.props);
if (!existingProps.user) {
existingProps.user = user;
originalReturnValue.props = existingProps;
}
}

return originalReturnValue;
};
return modified;
}
24 changes: 22 additions & 2 deletions src/pages/login.tsx
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
import { SignInButton, SignInFormItem, SignInTitle } from '@/components/auth';
import { VerticalForm } from '@/components/common';
import { config, showToast } from '@/lib';
import { resendEmailVerification } from '@/lib/api/AuthAPI';
import { AuthManager } from '@/lib/managers';
import { CookieService, ValidationService } from '@/lib/services';
import { URL } from '@/lib/types';
import type { LoginRequest } from '@/lib/types/apiRequests';
import { CookieType } from '@/lib/types/enums';
import type { PrivateProfile } from '@/lib/types/apiResponses';
import { CookieType, UserState } from '@/lib/types/enums';
import { getMessagesFromError } from '@/lib/utils';
import type { GetServerSideProps, NextPage } from 'next';
import { useRouter } from 'next/router';
Expand All @@ -30,7 +32,25 @@ const LoginPage: NextPage<LoginProps> = ({ destination }) => {
AuthManager.login({
email,
password,
onSuccessCallback: () => router.push(destination),
onSuccessCallback: (user: PrivateProfile) => {
if (user.state === UserState.PENDING) {
showToast('Account Not Verified', 'Click to resend a verification email', [
{
text: 'Send Email',
onClick: async () => {
await resendEmailVerification(user.email);
showToast(`Verification email sent to ${user.email}!`);
},
},
]);

CookieService.deleteClientCookie(CookieType.USER);

return;
}

router.push(destination);
},
onFailCallback: error => {
showToast('Unable to login', getMessagesFromError(error)[0]);
},
Expand Down