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

implement reset password #389

Merged
merged 2 commits into from
Nov 16, 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
2 changes: 1 addition & 1 deletion client/src/components/Users/Auth/ForgotPassword.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -68,7 +68,7 @@ function ForgotPassword() {
evt.preventDefault();
setIsLoading(true);

const resp = await fetch(`${APP_API_BASE_URL}/auth/reset_password`, {
const resp = await fetch(`${APP_API_BASE_URL}/auth/forgot-password`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
Expand Down
26 changes: 16 additions & 10 deletions client/src/components/Users/Auth/SetNewPassword.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,10 +7,11 @@
import type { Theme } from '@mui/material/styles';

import PasswordInput from './PasswordInput';
import { UserContext } from '../../../providers';
import { APP_API_BASE_URL } from '../../../configs';

import SetNewPasswordImg from '../../../assets/set-new-password.svg';
import { useHistory } from 'react-router-dom';
import { FormHelperText } from '@mui/material';

const useStyles = makeStyles()((theme: Theme) => {
const yPadding = 6;
Expand Down Expand Up @@ -73,16 +74,22 @@
};

function SetNewPassword() {
const RESOURCE_URL = `${APP_API_BASE_URL}/auth/users`;
const RESOURCE_URL = `${APP_API_BASE_URL}/auth/reset-password`;
const { classes } = useStyles();
const sublabel = `(${PASSWORD_MIN_LENGTH} or more characters)`;

const [password, setPassword] = React.useState<string>('');
const [confirmPassword, setConfirmPassword] = React.useState<string>('');

const [globalError, setGlobalError] = React.useState('');

const [error, setError] = React.useState<string | null>(null);
const [confirmPasswordError, setConfirmPasswordError] = React.useState<string | null>(null);

const history = useHistory();
const searchParams = new URLSearchParams(history.location.search);
const token = searchParams.get('token');

const handleChange = (evt: React.ChangeEvent<HTMLInputElement>): void => {
setPassword(evt.target.value);
};
Expand Down Expand Up @@ -114,8 +121,6 @@
setConfirmPasswordError(null);
};

const { user } = React.useContext(UserContext);

const handleSubmit = async (evt: React.FormEvent): Promise<void> => {
evt.preventDefault();

Expand All @@ -129,19 +134,17 @@
return;
}

// ternary in url temporary. User should be logged in(?) id should be available once BE is built
fetch(`${RESOURCE_URL}/${user ? user.id : null}`, {
method: 'PATCH',
fetch(`${RESOURCE_URL}`, {
method: 'PUT',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ password }),
credentials: 'include',
body: JSON.stringify({ password, token }),
}).then((resp) => {
if (resp.ok) {
resp.json().then((data) => {
// send user to home page/message lets them know password was changed successfully
});
} else {
resp.json().then((errors) => setError(errors));
setGlobalError('Unable to reset password');
}
});
};
Expand All @@ -149,7 +152,7 @@
return (
<div className={classes.container}>
<div className={classes.imgContainer}>
<img src={SetNewPasswordImg} alt="FAQs Image" className={classes.setNewPasswordImg} />

Check warning on line 155 in client/src/components/Users/Auth/SetNewPassword.tsx

View workflow job for this annotation

GitHub Actions / linting

Redundant alt attribute. Screen-readers already announce `img` tags as an image. You don’t need to use the words `image`, `photo,` or `picture` (or any specified custom words) in the alt prop
</div>
<Paper elevation={0} className={classes.paper}>
<Typography variant="h2" align="center">
Expand All @@ -175,6 +178,9 @@
id="confirmPassword"
showStartAdornment
/>

{globalError && <FormHelperText error={true}>{globalError}</FormHelperText>}

<div className={classes.ctaContainer}>
<Button
onClick={handleClickReset}
Expand Down
25 changes: 21 additions & 4 deletions server/src/acccount-manager/account-manager.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,7 @@ import { UsersService } from './user.service';
import { FileInterceptor } from '@nestjs/platform-express';
import { FileSizes } from '../file-storage/domain';
import { FilesStorageService } from '../file-storage/file-storage.service';
import { VerifyEmailDto, ReturnSessionDto, ReturnUserDto } from './dto/auth.dto';
import { VerifyEmailDto, ReturnSessionDto, ReturnUserDto, ResetPasswordDto } from './dto/auth.dto';
import { UpdateUserInternal } from './dto/create-user.internal';
import { MapTo } from '../shared/serialize.interceptor';

Expand Down Expand Up @@ -153,9 +153,9 @@ export class AccountManagerController {
response.clearCookie(COOKIE_KEY).send();
}

@Post('reset_password')
@ApiOperation({ summary: 'Password reset' })
async resetPassword(
@Post('forgot-password')
@ApiOperation({ summary: 'Password reset Request' })
async resetPasswordRequest(
@Request() req,
@Response({ passthrough: true }) response: ResponseT,
): Promise<void> {
Expand Down Expand Up @@ -193,6 +193,23 @@ export class AccountManagerController {
}
}

@Put('reset-password')
async resetPassword(
@Body() resetPasswordDtO: ResetPasswordDto,
): Promise<boolean | BadRequestException> {
try {
const user = await this.jwtService.verify(resetPasswordDtO.token, {
secret: process.env.JWT_SECRET,
});
if (user) {
this.usersService.updatePasswod(user.id, { password: resetPasswordDtO.password });
}
return true;
} catch {
throw new BadRequestException('jwt verify fail');
}
}

@ApiConsumes('multipart/form-data')
@ApiOperation({ summary: 'Upload profile image' })
@ApiBody({
Expand Down
12 changes: 11 additions & 1 deletion server/src/acccount-manager/dto/auth.dto.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,21 @@ export class LoginDto {
password: string;
}

export class ResetPasswordDto {
export class ResetPasswordRequestDto {
@IsEmail()
email: string;
}

export class ResetPasswordDto {
@IsNotEmpty()
@IsString()
password: string;

@IsNotEmpty()
@IsString()
token: string;
}

export class ReturnUserDto {
@Expose()
id: number;
Expand Down
16 changes: 16 additions & 0 deletions server/src/acccount-manager/user.service.ts
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,22 @@ export class UsersService {
}
}

async updatePasswod(id: number, createUserInternal: Partial<CreateUserInternal>): Promise<User> {
try {
const hashedPw = await bcrypt.hash(createUserInternal.password, parseInt(BCRYPT_WORK_FACTOR));
await this.usersRepository.update(id, {
...createUserInternal,
password: hashedPw,
});
const user = await this.usersRepository.findOneBy({ id });
delete user.password;
return user;
} catch (err: any) {
Logger.error(`${err.message}: \n${err.stack}`, UsersService.name);
throw new Error(`Error updating user password for user ${id}`);
}
}

async findOne(id: number): Promise<Omit<User, 'password'>> {
const user = await this.usersRepository.findOneBy({ id });
if (user) {
Expand Down
Loading