move chage password to user con
This commit is contained in:
parent
ff5b189b2f
commit
a6cddc6318
6 changed files with 85 additions and 57 deletions
|
|
@ -8,10 +8,9 @@ import {
|
||||||
ResetPasswordRequest,
|
ResetPasswordRequest,
|
||||||
LoginResponse,
|
LoginResponse,
|
||||||
RegisterResponse,
|
RegisterResponse,
|
||||||
RefreshTokenResponse,
|
RefreshTokenResponse
|
||||||
ChangePassword
|
|
||||||
} from '../types/auth.types';
|
} from '../types/auth.types';
|
||||||
import { loginSchema, registerSchema, refreshTokenSchema, resetRequestSchema, resetPasswordSchema, changePasswordSchema } from '../validators/auth.validator';
|
import { loginSchema, registerSchema, refreshTokenSchema, resetRequestSchema, resetPasswordSchema } from '../validators/auth.validator';
|
||||||
import { ValidationError } from '../middleware/errorHandler';
|
import { ValidationError } from '../middleware/errorHandler';
|
||||||
|
|
||||||
@Route('api/auth')
|
@Route('api/auth')
|
||||||
|
|
@ -172,26 +171,4 @@ export class AuthController {
|
||||||
}
|
}
|
||||||
return await this.authService.resetPassword(body.token, body.password);
|
return await this.authService.resetPassword(body.token, body.password);
|
||||||
}
|
}
|
||||||
|
|
||||||
/**
|
|
||||||
* Change password
|
|
||||||
* @summary Change password using old password
|
|
||||||
* @param body User ID, old password and new password
|
|
||||||
* @returns Success message
|
|
||||||
*/
|
|
||||||
@Post('change-password')
|
|
||||||
@Security('jwt')
|
|
||||||
@SuccessResponse('200', 'Password changed successfully')
|
|
||||||
@Response('401', 'Invalid or expired reset token')
|
|
||||||
public async changePassword(@Request() request: any, @Body() body: ChangePassword): Promise<{ message: string }> {
|
|
||||||
const { error } = changePasswordSchema.validate(body);
|
|
||||||
if (error) {
|
|
||||||
throw new ValidationError(error.details[0].message);
|
|
||||||
}
|
|
||||||
const token = request.headers.authorization?.replace('Bearer ', '');
|
|
||||||
if (!token) {
|
|
||||||
throw new ValidationError('No token provided');
|
|
||||||
}
|
|
||||||
return await this.authService.changePassword(token, body.oldPassword, body.newPassword);
|
|
||||||
}
|
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -8,6 +8,7 @@ import {
|
||||||
ChangePasswordRequest,
|
ChangePasswordRequest,
|
||||||
ChangePasswordResponse
|
ChangePasswordResponse
|
||||||
} from '../types/user.types';
|
} from '../types/user.types';
|
||||||
|
import { ChangePassword } from '../types/auth.types';
|
||||||
import { profileUpdateSchema, changePasswordSchema } from "../validators/user.validator";
|
import { profileUpdateSchema, changePasswordSchema } from "../validators/user.validator";
|
||||||
import { ValidationError } from '../middleware/errorHandler';
|
import { ValidationError } from '../middleware/errorHandler';
|
||||||
|
|
||||||
|
|
@ -34,4 +35,30 @@ export class UserController {
|
||||||
}
|
}
|
||||||
return await this.userService.getUserProfile(token);
|
return await this.userService.getUserProfile(token);
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Change password
|
||||||
|
* @summary Change user password using old password
|
||||||
|
* @param request Express request object with JWT token in Authorization header
|
||||||
|
* @param body Old password and new password
|
||||||
|
* @returns Success message
|
||||||
|
*/
|
||||||
|
@Post('change-password')
|
||||||
|
@Security('jwt')
|
||||||
|
@SuccessResponse('200', 'Password changed successfully')
|
||||||
|
@Response('401', 'Invalid old password or token')
|
||||||
|
@Response('400', 'Validation error')
|
||||||
|
public async changePassword(@Request() request: any, @Body() body: ChangePassword): Promise<ChangePasswordResponse> {
|
||||||
|
const { error } = changePasswordSchema.validate(body);
|
||||||
|
if (error) {
|
||||||
|
throw new ValidationError(error.details[0].message);
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = request.headers.authorization?.replace('Bearer ', '');
|
||||||
|
if (!token) {
|
||||||
|
throw new ValidationError('No token provided');
|
||||||
|
}
|
||||||
|
|
||||||
|
return await this.userService.changePassword(token, body.oldPassword, body.newPassword);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -11,7 +11,6 @@ import {
|
||||||
RegisterResponse,
|
RegisterResponse,
|
||||||
RefreshTokenResponse,
|
RefreshTokenResponse,
|
||||||
ResetPasswordResponse,
|
ResetPasswordResponse,
|
||||||
ChangePasswordResponse,
|
|
||||||
ResetRequestResponse
|
ResetRequestResponse
|
||||||
} from '../types/auth.types';
|
} from '../types/auth.types';
|
||||||
import { UserResponse } from '../types/user.types';
|
import { UserResponse } from '../types/user.types';
|
||||||
|
|
@ -260,33 +259,6 @@ export class AuthService {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
async changePassword(token: string, oldPassword: string, newPassword: string): Promise<ChangePasswordResponse> {
|
|
||||||
try {
|
|
||||||
const decoded = jwt.verify(token, config.jwt.secret) as { id: number; username: string; email: string; roleCode: string };
|
|
||||||
const user = await prisma.user.findUnique({ where: { id: decoded.id } });
|
|
||||||
if (!user) throw new UnauthorizedError('User not found');
|
|
||||||
|
|
||||||
const isPasswordValid = await bcrypt.compare(oldPassword, user.password);
|
|
||||||
if (!isPasswordValid) throw new UnauthorizedError('Invalid password');
|
|
||||||
|
|
||||||
const encryptedPassword = await bcrypt.hash(newPassword, 10);
|
|
||||||
|
|
||||||
await prisma.user.update({
|
|
||||||
where: { id: user.id },
|
|
||||||
data: { password: encryptedPassword }
|
|
||||||
});
|
|
||||||
|
|
||||||
logger.info('Password changed successfully', { userId: user.id });
|
|
||||||
return {
|
|
||||||
code: 200,
|
|
||||||
message: 'Password changed successfully'
|
|
||||||
};
|
|
||||||
} catch (error) {
|
|
||||||
logger.error('Failed to change password', { error });
|
|
||||||
throw error;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Generate access token (JWT)
|
* Generate access token (JWT)
|
||||||
*/
|
*/
|
||||||
|
|
|
||||||
|
|
@ -3,6 +3,7 @@ import { Prisma } from '@prisma/client';
|
||||||
import { config } from '../config';
|
import { config } from '../config';
|
||||||
import { logger } from '../config/logger';
|
import { logger } from '../config/logger';
|
||||||
import jwt from 'jsonwebtoken';
|
import jwt from 'jsonwebtoken';
|
||||||
|
import bcrypt from 'bcrypt';
|
||||||
import {
|
import {
|
||||||
UserResponse,
|
UserResponse,
|
||||||
ProfileResponse,
|
ProfileResponse,
|
||||||
|
|
@ -63,6 +64,50 @@ export class UserService {
|
||||||
throw error;
|
throw error;
|
||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
/**
|
||||||
|
* Change user password
|
||||||
|
*/
|
||||||
|
async changePassword(token: string, oldPassword: string, newPassword: string): Promise<ChangePasswordResponse> {
|
||||||
|
try {
|
||||||
|
// Decode JWT token to get user ID
|
||||||
|
const decoded = jwt.verify(token, config.jwt.secret) as { id: number; username: string; email: string; roleCode: string };
|
||||||
|
|
||||||
|
const user = await prisma.user.findUnique({ where: { id: decoded.id } });
|
||||||
|
if (!user) throw new UnauthorizedError('User not found');
|
||||||
|
|
||||||
|
// Verify old password
|
||||||
|
const isPasswordValid = await bcrypt.compare(oldPassword, user.password);
|
||||||
|
if (!isPasswordValid) throw new UnauthorizedError('Invalid old password');
|
||||||
|
|
||||||
|
// Hash new password
|
||||||
|
const encryptedPassword = await bcrypt.hash(newPassword, 10);
|
||||||
|
|
||||||
|
// Update password
|
||||||
|
await prisma.user.update({
|
||||||
|
where: { id: user.id },
|
||||||
|
data: { password: encryptedPassword }
|
||||||
|
});
|
||||||
|
|
||||||
|
logger.info('Password changed successfully', { userId: user.id });
|
||||||
|
return {
|
||||||
|
code: 200,
|
||||||
|
message: 'Password changed successfully'
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
if (error instanceof jwt.JsonWebTokenError) {
|
||||||
|
logger.error('Invalid JWT token:', error);
|
||||||
|
throw new UnauthorizedError('Invalid token');
|
||||||
|
}
|
||||||
|
if (error instanceof jwt.TokenExpiredError) {
|
||||||
|
logger.error('JWT token expired:', error);
|
||||||
|
throw new UnauthorizedError('Token expired');
|
||||||
|
}
|
||||||
|
logger.error('Failed to change password', { error });
|
||||||
|
throw error;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
/**
|
/**
|
||||||
* Format user response
|
* Format user response
|
||||||
*/
|
*/
|
||||||
|
|
@ -88,4 +133,3 @@ export class UserService {
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
|
|
@ -120,7 +120,7 @@ export const changePasswordSchema = Joi.object({
|
||||||
|
|
||||||
export const resetRequestSchema = Joi.object({
|
export const resetRequestSchema = Joi.object({
|
||||||
email: Joi.string()
|
email: Joi.string()
|
||||||
.email()
|
.email({ tlds: { allow: false } }) // Allow any TLD including .local
|
||||||
.required()
|
.required()
|
||||||
.messages({
|
.messages({
|
||||||
'string.email': 'Please provide a valid email address',
|
'string.email': 'Please provide a valid email address',
|
||||||
|
|
|
||||||
|
|
@ -22,14 +22,22 @@ export const profileUpdateSchema = Joi.object({
|
||||||
});
|
});
|
||||||
|
|
||||||
export const changePasswordSchema = Joi.object({
|
export const changePasswordSchema = Joi.object({
|
||||||
old_password: Joi.string()
|
oldPassword: Joi.string()
|
||||||
|
.min(6)
|
||||||
|
.max(100)
|
||||||
.required()
|
.required()
|
||||||
.messages({
|
.messages({
|
||||||
|
'string.min': 'Old password must be at least 6 characters',
|
||||||
|
'string.max': 'Old password must not exceed 100 characters',
|
||||||
'any.required': 'Old password is required'
|
'any.required': 'Old password is required'
|
||||||
}),
|
}),
|
||||||
new_password: Joi.string()
|
newPassword: Joi.string()
|
||||||
|
.min(6)
|
||||||
|
.max(100)
|
||||||
.required()
|
.required()
|
||||||
.messages({
|
.messages({
|
||||||
|
'string.min': 'New password must be at least 6 characters',
|
||||||
|
'string.max': 'New password must not exceed 100 characters',
|
||||||
'any.required': 'New password is required'
|
'any.required': 'New password is required'
|
||||||
})
|
})
|
||||||
});
|
});
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue