remove forgot password + reset password

This commit is contained in:
Nikita Pekin 2023-03-09 07:07:52 +02:00
parent ee86a8f9ca
commit e52f51a762
7 changed files with 2 additions and 484 deletions

View File

@ -28,11 +28,6 @@ const MESSAGES = {
userNotConfirmed: 'User is not confirmed. Please check your email for a confirmation link.',
incorrectUsernameOrPassword: 'Incorrect username or password.',
},
forgotPassword: {
userNotFound: 'User not found. Please register first.',
userNotConfirmed:
'Cannot reset password for user with unverified email. Please verify your email first.',
},
}
/** A list of known Amplify errors that we can match against prior to trying to convert to our
@ -43,11 +38,6 @@ const KNOWN_ERRORS = {
code: 'NotAuthorizedException',
message: 'User cannot be confirmed. Current status is CONFIRMED',
},
forgotPasswordUserNotConfirmed: {
code: 'InvalidParameterException',
message:
'Cannot reset password for the user as there is no registered/verified email or phone_number',
},
}
@ -80,26 +70,6 @@ const intoAmplifyErrorOrThrow = (error: unknown): AmplifyError => {
// =================
// === AuthError ===
// =================
/** Object returned by the AWS Amplify library when an auth error occurs. */
interface AuthError {
name: string
log: string
}
/** Hints to TypeScript if we can safely cast an `unknown` error to an `AuthError`. */
const isAuthError = (error: unknown): error is AuthError => {
if (error && typeof error === 'object') {
return 'name' in error && 'log' in error
}
return false
}
// ===============
// === Cognito ===
// ===============
@ -153,32 +123,6 @@ export interface Cognito {
username: string,
password: string
) => Promise<results.Result<null, SignInWithPasswordError>>
/** Sends a password reset email to the given email address.
*
* The user will be able to reset their password by following the link in the email, which takes
* them to the "reset password" page of the application. The verification code will be filled in
* automatically.
*
* @param email - Email address to send the password reset email to.
* @returns A promise that resolves to either success or known error.
* @throws An error if failed due to an unknown error. */
forgotPassword: (username: string) => Promise<results.Result<null, ForgotPasswordError>>
/** Submits a new password for the given email address.
*
* The user will have received a verification code in an email, which they will have entered on
* the "reset password" page of the application. This function will submit the new password
* along with the verification code, changing the user's password.
*
* @param email - Email address to reset the password for.
* @param code - Verification code that was sent to the user's email address.
* @param password - New password to set.
* @returns A promise that resolves to either success or known error.
* @throws An error if failed due to an unknown error. */
forgotPasswordSubmit: (
username: string,
code: string,
newPassword: string
) => Promise<results.Result<null, ForgotPasswordSubmitError>>
/** Signs out the current user.
*
* @returns A promise that resolves if successful. */
@ -233,8 +177,6 @@ export class CognitoImpl implements Cognito {
signInWithGoogle = () => signInWithGoogle(this.customState())
signInWithGitHub = signInWithGitHub
signInWithPassword = signInWithPassword
forgotPassword = forgotPassword
forgotPasswordSubmit = forgotPasswordSubmit
signOut = () => signOut(this.logger)
}
@ -486,79 +428,6 @@ const intoSignInWithPasswordErrorOrThrow = (error: AmplifyError): SignInWithPass
// ======================
// === ForgotPassword ===
// ======================
const forgotPassword = async (email: string) =>
results.Result.wrapAsync(() => amplify.Auth.forgotPassword(email))
// We don't care about the details in the success case, just that it happened.
.then(result => result.map(() => null))
.then(result => result.mapErr(intoAmplifyErrorOrThrow))
.then(result => result.mapErr(intoForgotPasswordErrorOrThrow))
type ForgotPasswordErrorKind = 'UserNotFound' | 'UserNotConfirmed'
export interface ForgotPasswordError {
kind: ForgotPasswordErrorKind
message: string
}
const intoForgotPasswordErrorOrThrow = (error: AmplifyError): ForgotPasswordError => {
if (error.code === 'UserNotFoundException') {
return {
kind: 'UserNotFound',
message: MESSAGES.forgotPassword.userNotFound,
}
} else if (error.code === KNOWN_ERRORS.forgotPasswordUserNotConfirmed.code) {
if (error.message === KNOWN_ERRORS.forgotPasswordUserNotConfirmed.message) {
return {
kind: 'UserNotConfirmed',
message: MESSAGES.forgotPassword.userNotConfirmed,
}
}
}
throw error
}
// ============================
// === ForgotPasswordSubmit ===
// ============================
const forgotPasswordSubmit = async (email: string, code: string, password: string) =>
results.Result.wrapAsync(() => amplify.Auth.forgotPasswordSubmit(email, code, password))
// We don't care about the details in the success case, just that it happened.
.then(result => result.map(() => null))
.then(result => result.mapErr(intoForgotPasswordSubmitErrorOrThrow))
type ForgotPasswordSubmitErrorKind = 'AuthError' | 'AmplifyError'
export interface ForgotPasswordSubmitError {
kind: ForgotPasswordSubmitErrorKind
message: string
}
const intoForgotPasswordSubmitErrorOrThrow = (error: unknown): ForgotPasswordSubmitError => {
if (isAuthError(error)) {
return {
kind: 'AuthError',
message: error.log,
}
} else if (isAmplifyError(error)) {
return {
kind: 'AmplifyError',
message: error.message,
}
}
throw error
}
// ===============
// === SignOut ===
// ===============

View File

@ -1,88 +0,0 @@
/** @file Container responsible for rendering and interactions in first half of forgot password
* flow. */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import * as React from "react";
import * as router from "react-router-dom";
import * as auth from "../providers/auth";
import withRouter from "../../navigation";
import * as hooks from "../../hooks";
import * as utils from "../../utils";
import * as app from "../../components/app";
import * as icons from "../../components/svg";
// ===============================
// === forgotPasswordContainer ===
// ===============================
const forgotPasswordContainer = () => {
const { forgotPassword } = auth.useAuth();
const { value: email, bind: bindEmail } = hooks.useInput("");
return (
<div className="min-h-screen flex flex-col items-center justify-center bg-gray-300">
<div className="flex flex-col bg-white shadow-md px-4 sm:px-6 md:px-8 lg:px-10 py-8 rounded-md w-full max-w-md">
<div className="font-medium self-center text-xl sm:text-2xl uppercase text-gray-800">
Forgot Your Password?
</div>
<div className="mt-10">
<form
onSubmit={utils.handleEvent(
async () => await forgotPassword(email)
)}
>
<div className="flex flex-col mb-6">
<label
htmlFor="email"
className="mb-1 text-xs sm:text-sm tracking-wide text-gray-600"
>
E-Mail Address:
</label>
<div className="relative">
<div className="inline-flex items-center justify-center absolute left-0 top-0 h-full w-10 text-gray-400">
<icons.Svg data={icons.PATHS.at} />
</div>
<input
{...bindEmail}
id="email"
type="email"
name="email"
className="text-sm sm:text-base placeholder-gray-500 pl-10 pr-4 rounded-lg border border-gray-400 w-full py-2 focus:outline-none focus:border-blue-400"
placeholder="E-Mail Address"
/>
</div>
</div>
<div className="flex w-full">
<button
type="submit"
className="flex items-center justify-center focus:outline-none text-white text-sm sm:text-base bg-blue-600 hover:bg-blue-700 rounded py-2 w-full transition duration-150 ease-in"
>
<span className="mr-2 uppercase">Send link</span>
<span>
<icons.Svg data={icons.PATHS.rightArrow} />
</span>
</button>
</div>
</form>
</div>
<div className="flex justify-center items-center mt-6">
<router.Link
to={app.LOGIN_PATH}
className="inline-flex items-center font-bold text-blue-500 hover:text-blue-700 text-xs text-center"
>
<span>
<icons.Svg data={icons.PATHS.goBack} />
</span>
<span className="ml-2">Go back to login</span>
</router.Link>
</div>
</div>
</div>
);
};
export default withRouter(forgotPasswordContainer);

View File

@ -126,17 +126,6 @@ const loginContainer = () => {
</div>
</div>
<div className="flex items-center mb-6 -mt-4">
<div className="flex ml-auto">
<router.Link
to={app.FORGOT_PASSWORD_PATH}
className="inline-flex text-xs sm:text-sm text-blue-500 hover:text-blue-700"
>
Forgot Your Password?
</router.Link>
</div>
</div>
<div className="flex w-full">
<button
type="submit"

View File

@ -1,188 +0,0 @@
/** @file Container responsible for rendering and interactions in second half of forgot password
* flow. */
// eslint-disable-next-line @typescript-eslint/no-unused-vars
import * as React from "react";
import * as router from "react-router-dom";
import toast from "react-hot-toast";
import * as auth from "../providers/auth";
import withRouter from "../../navigation";
import * as hooks from "../../hooks";
import * as utils from "../../utils";
import * as app from "../../components/app";
import * as Icons from "../../components/svg";
// =================
// === Constants ===
// =================
const RESET_PASSWORD_QUERY_PARAMS = {
email: "email",
verificationCode: "verification_code",
};
// ==============================
// === resetPasswordContainer ===
// ==============================
const resetPasswordContainer = () => {
const { resetPassword } = auth.useAuth();
const { search } = router.useLocation();
const { verificationCode: initialCode, email: initialEmail } =
parseUrlSearchParams(search);
const { value: email, bind: bindEmail } = hooks.useInput(initialEmail ?? "");
const { value: code, bind: bindCode } = hooks.useInput(initialCode ?? "");
const { value: newPassword, bind: bindNewPassword } = hooks.useInput("");
const { value: newPasswordConfirm, bind: bindNewPasswordConfirm } =
hooks.useInput("");
const handleSubmit = () => {
if (newPassword !== newPasswordConfirm) {
toast.error("Passwords do not match");
return Promise.resolve();
}
return resetPassword(email, code, newPassword);
};
return (
<div className="min-h-screen flex flex-col items-center justify-center bg-gray-300">
<div className="flex flex-col bg-white shadow-md px-4 sm:px-6 md:px-8 lg:px-10 py-8 rounded-md w-full max-w-md">
<div className="font-medium self-center text-xl sm:text-2xl uppercase text-gray-800">
Reset Your Password
</div>
<div className="mt-10">
<form onSubmit={utils.handleEvent(handleSubmit)}>
<div className="flex flex-col mb-6">
<label
htmlFor="email"
className="mb-1 text-xs sm:text-sm tracking-wide text-gray-600"
>
E-Mail Address:
</label>
<div className="relative">
<div className="inline-flex items-center justify-center absolute left-0 top-0 h-full w-10 text-gray-400">
<Icons.Svg data={Icons.PATHS.at} />
</div>
<input
{...bindEmail}
id="email"
type="email"
name="email"
className="text-sm sm:text-base placeholder-gray-500 pl-10 pr-4 rounded-lg border border-gray-400 w-full py-2 focus:outline-none focus:border-blue-400"
placeholder="E-Mail Address"
/>
</div>
</div>
<div className="flex flex-col mb-6">
<label
htmlFor="code"
className="mb-1 text-xs sm:text-sm tracking-wide text-gray-600"
>
Confirmation Code:
</label>
<div className="relative">
<div className="inline-flex items-center justify-center absolute left-0 top-0 h-full w-10 text-gray-400">
<Icons.Svg data={Icons.PATHS.lock} />
</div>
<input
{...bindCode}
id="code"
type="text"
name="code"
className="text-sm sm:text-base placeholder-gray-500 pl-10 pr-4 rounded-lg border border-gray-400 w-full py-2 focus:outline-none focus:border-blue-400"
placeholder="Confirmation Code"
/>
</div>
</div>
<div className="flex flex-col mb-6">
<label
htmlFor="new_password"
className="mb-1 text-xs sm:text-sm tracking-wide text-gray-600"
>
New Password:
</label>
<div className="relative">
<div className="inline-flex items-center justify-center absolute left-0 top-0 h-full w-10 text-gray-400">
<Icons.Svg data={Icons.PATHS.lock} />
</div>
<input
{...bindNewPassword}
id="new_password"
type="password"
name="new_password"
className="text-sm sm:text-base placeholder-gray-500 pl-10 pr-4 rounded-lg border border-gray-400 w-full py-2 focus:outline-none focus:border-blue-400"
placeholder="New Password"
/>
</div>
</div>
<div className="flex flex-col mb-6">
<label
htmlFor="new_password_confirm"
className="mb-1 text-xs sm:text-sm tracking-wide text-gray-600"
>
Confirm New Password:
</label>
<div className="relative">
<div className="inline-flex items-center justify-center absolute left-0 top-0 h-full w-10 text-gray-400">
<Icons.Svg data={Icons.PATHS.lock} />
</div>
<input
{...bindNewPasswordConfirm}
id="new_password_confirm"
type="password"
name="new_password_confirm"
className="text-sm sm:text-base placeholder-gray-500 pl-10 pr-4 rounded-lg border border-gray-400 w-full py-2 focus:outline-none focus:border-blue-400"
placeholder="Confirm New Password"
/>
</div>
</div>
<div className="flex w-full">
<button
type="submit"
className="flex items-center justify-center focus:outline-none text-white text-sm sm:text-base bg-blue-600 hover:bg-blue-700 rounded py-2 w-full transition duration-150 ease-in"
>
<span className="mr-2 uppercase">Reset</span>
<span>
<Icons.Svg data={Icons.PATHS.rightArrow} />
</span>
</button>
</div>
</form>
</div>
<div className="flex justify-center items-center mt-6">
<router.Link
to={app.LOGIN_PATH}
className="inline-flex items-center font-bold text-blue-500 hover:text-blue-700 text-xs text-center"
>
<span>
<Icons.Svg data={Icons.PATHS.goBack} />
</span>
<span className="ml-2">Go back to login</span>
</router.Link>
</div>
</div>
</div>
);
};
const parseUrlSearchParams = (search: string) => {
const query = new URLSearchParams(search);
const verificationCode = query.get(
RESET_PASSWORD_QUERY_PARAMS.verificationCode
);
const email = query.get(RESET_PASSWORD_QUERY_PARAMS.email);
return { verificationCode, email };
};
export default withRouter(resetPasswordContainer);

View File

@ -25,8 +25,6 @@ const MESSAGES = {
confirmSignUpSuccess: "Your account has been confirmed! Please log in.",
setUsernameSuccess: "Your username has been set!",
signInWithPasswordSuccess: "Successfully logged in!",
forgotPasswordSuccess: "We have sent you an email with further instructions!",
resetPasswordSuccess: "Successfully reset password!",
signOutSuccess: "Successfully logged out!",
pleaseWait: "Please wait...",
};
@ -94,12 +92,6 @@ interface AuthContextType {
signInWithGoogle: () => Promise<null>;
signInWithGitHub: () => Promise<null>;
signInWithPassword: (email: string, password: string) => Promise<void>;
forgotPassword: (email: string) => Promise<void>;
resetPassword: (
email: string,
code: string,
password: string
) => Promise<void>;
signOut: () => Promise<void>;
/** Session containing the currently authenticated user's authentication information.
*
@ -281,26 +273,6 @@ export const AuthProvider = (props: AuthProviderProps) => {
toast.error(result.val.message);
});
const forgotPassword = async (email: string) =>
cognito.forgotPassword(email).then((result) => {
if (result.ok) {
toast.success(MESSAGES.forgotPasswordSuccess);
navigate(app.RESET_PASSWORD_PATH);
} else {
toast.error(result.val.message);
}
});
const resetPassword = async (email: string, code: string, password: string) =>
cognito.forgotPasswordSubmit(email, code, password).then((result) => {
if (result.ok) {
toast.success(MESSAGES.resetPasswordSuccess);
navigate(app.LOGIN_PATH);
} else {
toast.error(result.val.message);
}
});
const signOut = () =>
cognito
.signOut()
@ -314,8 +286,6 @@ export const AuthProvider = (props: AuthProviderProps) => {
signInWithGoogle: cognito.signInWithGoogle,
signInWithGitHub: cognito.signInWithGitHub,
signInWithPassword: withLoadingToast(signInWithPassword),
forgotPassword: withLoadingToast(forgotPassword),
resetPassword: withLoadingToast(resetPassword),
signOut,
session: userSession,
};

View File

@ -25,9 +25,6 @@ const SIGN_OUT_PATHNAME = "//auth";
/** Pathname of the {@link URL} for deep links to the registration confirmation page, after a
* redirect from an account verification email. */
const CONFIRM_REGISTRATION_PATHNAME = "//auth/confirmation";
/** Pathname of the {@link URL} for deep links to the login page, after a redirect from a reset
* password email. */
const LOGIN_PATHNAME = "//auth/login";
const BASE_AMPLIFY_CONFIG: Partial<authConfig.AmplifyConfig> = {
region: authConfig.AWS_REGION,
@ -205,17 +202,10 @@ const setDeepLinkHandler = (
// Navigate to a relative URL to handle the confirmation link.
const redirectUrl = `${app.CONFIRM_REGISTRATION_PATH}${parsedUrl.search}`;
navigate(redirectUrl);
} else if (isSignOutRedirect(parsedUrl) || isLoginRedirect(parsedUrl)) {
} else if (isSignOutRedirect(parsedUrl)) {
navigate(app.LOGIN_PATH);
} else if (isSignInRedirect(parsedUrl)) {
handleAuthResponse(url);
// If the user is being redirected from a password reset email, then we need to navigate to
// the password reset page, with the verification code and email passed in the URL so they
// can be filled in automatically.
} else if (isResetPasswordRedirect(parsedUrl)) {
// Navigate to a relative URL to handle the password reset.
const redirectUrl = `${app.RESET_PASSWORD_PATH}${parsedUrl.search}`;
navigate(redirectUrl);
} else {
logger.error(`${url} is an unrecognized deep link. Ignoring.`)
}
@ -244,16 +234,6 @@ const isSignOutRedirect = (url: URL) =>
const isSignInRedirect = (url: URL) =>
url.pathname === SIGN_IN_PATHNAME && url.search !== "";
/** If the user is being redirected after clicking the reset password confirmation link in their
* email, then the URL will be for the confirm password reset path. */
const isResetPasswordRedirect = (url: URL) =>
url.pathname === app.RESET_PASSWORD_PATH;
/** If the user is being redirected after finishing the password reset flow,
* then the URL will be for the login page. */
const isLoginRedirect = (url: URL) =>
url.pathname === LOGIN_PATHNAME;
/** When the user is being redirected from a federated identity provider, then we need to pass the
* URL to the Amplify library, which will parse the URL and complete the OAuth flow. */
const handleAuthResponse = (url: string) => {

View File

@ -6,8 +6,6 @@ import * as router from "react-router-dom";
import * as authProvider from "../authentication/providers/auth";
import DashboardContainer from "../dashboard/components/dashboard";
import ForgotPasswordContainer from "../authentication/components/forgotPassword";
import ResetPasswordContainer from "../authentication/components/resetPassword";
import LoginContainer from "../authentication/components/login";
import RegistrationContainer from "../authentication/components/registration";
import ConfirmRegistrationContainer from "../authentication/components/confirmRegistration";
@ -31,10 +29,6 @@ export const LOGIN_PATH = "/login";
export const REGISTRATION_PATH = "/registration";
/** Path to the confirm registration page. */
export const CONFIRM_REGISTRATION_PATH = "/confirmation";
/** Path to the forgot password page. */
export const FORGOT_PASSWORD_PATH = "/forgot-password";
/** Path to the reset password page. */
export const RESET_PASSWORD_PATH = "/password-reset";
/** Path to the set username page. */
export const SET_USERNAME_PATH = "/set-username";
@ -84,7 +78,7 @@ const App = (props: AppProps) => {
/** Router definition for the app. */
// eslint-disable-next-line @typescript-eslint/naming-convention
const AppRouter = (props: AppProps) => {
const { logger, onAuthenticated, runningOnDesktop } = props;
const { logger, onAuthenticated } = props;
const navigate = router.useNavigate();
const authConfig = { navigate, ...props };
const memoizedAuthService = React.useMemo(
@ -140,14 +134,6 @@ const AppRouter = (props: AppProps) => {
path={CONFIRM_REGISTRATION_PATH}
element={<ConfirmRegistrationContainer />}
/>
<router.Route
path={FORGOT_PASSWORD_PATH}
element={<ForgotPasswordContainer />}
/>
<router.Route
path={RESET_PASSWORD_PATH}
element={<ResetPasswordContainer />}
/>
</React.Fragment>
</router.Routes>
</authProvider.AuthProvider>