Skip to content

Commit

Permalink
Add backend point for changing the password
Browse files Browse the repository at this point in the history
  • Loading branch information
mohamedsalem401 committed Jun 19, 2024
1 parent 7b2adce commit 22de37f
Show file tree
Hide file tree
Showing 4 changed files with 134 additions and 1 deletion.
9 changes: 9 additions & 0 deletions packages/api/src/@core/auth/auth.controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ import { ApiBody, ApiOperation, ApiResponse, ApiTags } from '@nestjs/swagger';
import { ApiKeyDto } from './dto/api-key.dto';
import { LoginDto } from './dto/login.dto';
import { RefreshDto } from './dto/refresh.dto';
import { ChangePasswordDto } from './dto/change-password.dto';

@ApiTags('auth')
@Controller('auth')
Expand Down Expand Up @@ -107,4 +108,12 @@ export class AuthController {
last_name,
);
}

@ApiOperation({ operationId: 'changePassword', summary: 'Change password' })
@ApiBody({ type: ChangePasswordDto })
@ApiResponse({ status: 201 })
@Post('change-password')
async changePassword(@Body() newPasswordRequest: ChangePasswordDto) {
return this.authService.changePassword(newPasswordRequest);
}
}
80 changes: 79 additions & 1 deletion packages/api/src/@core/auth/auth.service.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { Injectable } from '@nestjs/common';
import { BadRequestException, Injectable } from '@nestjs/common';
import { JwtService } from '@nestjs/jwt';
import { CreateUserDto } from './dto/create-user.dto';
import { PrismaService } from '../prisma/prisma.service';
Expand All @@ -10,6 +10,7 @@ import { AuthError, throwTypedError } from '@@core/utils/errors';
import { LoginDto } from './dto/login.dto';
import { VerifyUserDto } from './dto/verify-user.dto';
import { ProjectsService } from '@@core/projects/projects.service';
import { ChangePasswordDto } from './dto/change-password.dto';

@Injectable()
export class AuthService {
Expand Down Expand Up @@ -236,6 +237,83 @@ export class AuthService {
}
}

async changePassword(newPasswordRequest: ChangePasswordDto) {
try {
const foundUser = await this.prisma.users.findFirst({
where: {
email: newPasswordRequest.email,
},
});

if (!foundUser) {
throw new ReferenceError('User undefined!');
}

const project = await this.prisma.projects.findFirst({
where: {
id_user: foundUser.id_user,
},
});

if (!project) {
throw new ReferenceError('Project undefined!');
}

const isEq = await bcrypt.compare(
newPasswordRequest.old_password_hash,
foundUser.password_hash,
);

if (!isEq) {
throw new ReferenceError(
'Bcrypt Invalid credentials, mismatch in password.',
);
}

const hashedNewPassword = await bcrypt.hash(newPasswordRequest.new_password_hash, 10);
await this.prisma.users.update({
where: {
id_user: foundUser.id_user
},
data: {
password_hash: hashedNewPassword,
},
});

const { ...userData } = foundUser;

const payload = {
email: userData.email,
sub: userData.id_user,
first_name: userData.first_name,
last_name: userData.last_name,
id_project: project.id_project,
};

return {
user: {
id_user: foundUser.id_user,
email: foundUser.email,
first_name: foundUser.first_name,
last_name: foundUser.last_name,
},
access_token: this.jwtService.sign(payload, {
secret: process.env.JWT_SECRET,
}), // token used to generate api keys
};
} catch (error) {
throwTypedError(
new AuthError({
name: 'CHANGE_USER_PASSWORD_ERROR',
message: 'failed to updated password',
cause: error,
}),
this.logger,
);
}
}


hashApiKey(apiKey: string): string {
try {
return crypto.createHash('sha256').update(apiKey).digest('hex');
Expand Down
1 change: 1 addition & 0 deletions packages/api/src/@core/utils/errors.ts
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,7 @@ export class AuthError extends ErrorBase<
| 'GENERATE_API_KEY_ERROR'
| 'VALIDATE_API_KEY_ERROR'
| 'EMAIL_ALREADY_EXISTS_ERROR'
| 'CHANGE_USER_PASSWORD_ERROR'
> {}

export class PassthroughRequestError extends ErrorBase<'PASSTHROUGH_REMOTE_API_CALL_ERROR'> {}
Expand Down
45 changes: 45 additions & 0 deletions packages/api/swagger/swagger-spec.json
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,31 @@
]
}
},
"/auth/change-password": {
"post": {
"operationId": "changePassword",
"summary": "Change password",
"parameters": [],
"requestBody": {
"required": true,
"content": {
"application/json": {
"schema": {
"$ref": "#/components/schemas/ChangePasswordDto"
}
}
}
},
"responses": {
"201": {
"description": ""
}
},
"tags": [
"auth"
]
}
},
"/connections/oauth/callback": {
"get": {
"operationId": "handleOAuthCallback",
Expand Down Expand Up @@ -22646,6 +22671,26 @@
"projectId"
]
},
"ChangePasswordDto": {
"type": "object",
"properties": {
"email": {
"type": "string"
},
"old_password_hash": {
"type": "string"
},
"new_password_hash": {
"type": "string",
"minLength": 9
}
},
"required": [
"email",
"old_password_hash",
"new_password_hash"
]
},
"BodyDataType": {
"type": "object",
"properties": {}
Expand Down

0 comments on commit 22de37f

Please sign in to comment.