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

fit-add-retriving-users #122

Merged
merged 1 commit into from
Jul 12, 2024
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
8,383 changes: 3,575 additions & 4,808 deletions model.nlp

Large diffs are not rendered by default.

16 changes: 8 additions & 8 deletions src/__test__/userStatus.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -64,15 +64,15 @@ describe('POST /user/deactivate', () => {

const response = await request(app)
.post(`/user/deactivate`)
.set('Cookie', `token=${token}`)
.set('Authorization', `Bearer ${token}`)
.send({ email: `${testUser.email}` });
expect(response.status).toBe(200);
expect(response.body.message).toBe('User deactivated successfully');
}, 60000);

it('should return 404 when email is not submitted', async () => {
const token = jwt.sign(data, jwtSecretKey);
const response = await request(app).post(`/user/deactivate`).set('Cookie', `token=${token}`);
const response = await request(app).post(`/user/deactivate`).set('Authorization', `Bearer ${token}`);

expect(response.status).toBe(404);
expect(response.body.error).toBe('Email is needed');
Expand All @@ -81,7 +81,7 @@ describe('POST /user/deactivate', () => {
const token = jwt.sign(data, jwtSecretKey);
const response = await request(app)
.post(`/user/deactivate`)
.set('Cookie', `token=${token}`)
.set('Authorization', `Bearer ${token}`)
.send({ email: `${testUser.email}` });

expect(response.status).toBe(200);
Expand All @@ -92,7 +92,7 @@ describe('POST /user/deactivate', () => {
const token = jwt.sign(data, jwtSecretKey);
const response = await request(app)
.post(`/user/deactivate`)
.set('Cookie', `token=${token}`)
.set('Authorization', `Bearer ${token}`)
.send({ email: '[email protected]' });

expect(response.status).toBe(404);
Expand All @@ -106,7 +106,7 @@ describe('POST /user/activate', () => {

const response = await request(app)
.post(`/user/activate`)
.set('Cookie', `token=${token}`)
.set('Authorization', `Bearer ${token}`)
.send({ email: `${testUser.email}` });

expect(response.status).toBe(200);
Expand All @@ -115,7 +115,7 @@ describe('POST /user/activate', () => {

it('should return 404 when email is not submitted', async () => {
const token = jwt.sign(data, jwtSecretKey);
const response = await request(app).post(`/user/activate`).set('Cookie', `token=${token}`);
const response = await request(app).post(`/user/activate`).set('Authorization', `Bearer ${token}`);

expect(response.status).toBe(404);
expect(response.body.error).toBe('Email is needed');
Expand All @@ -125,7 +125,7 @@ describe('POST /user/activate', () => {
const token = jwt.sign(data, jwtSecretKey);
const response = await request(app)
.post(`/user/activate`)
.set('Cookie', `token=${token}`)
.set('Authorization', `Bearer ${token}`)
.send({ email: `${testUser.email}` });

expect(response.status).toBe(200);
Expand All @@ -142,7 +142,7 @@ describe('POST /user/activate', () => {
const token = jwt.sign(data, jwtSecretKey);
const response = await request(app)
.post('/user/activate')
.set('Cookie', `token=${token}`)
.set('Authorization', `Bearer ${token}`)
.send({ email: '[email protected]' });

expect(response.status).toBe(404);
Expand Down
14 changes: 12 additions & 2 deletions src/controllers/authController.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,8 @@ import { sendPasswordResetLinkService } from '../services/userServices/sendReset
import { activateUserService } from '../services/updateUserStatus/activateUserService';
import { deactivateUserService } from '../services/updateUserStatus/deactivateUserService';
import { userProfileUpdateServices } from '../services/userServices/userProfileUpdateServices';
import getAllUsers from '../services/userServices/getAllUsers';
import getUserById from '../services/userServices/getUserById';

export const userRegistration = async (req: Request, res: Response) => {
await userRegistrationService(req, res);
Expand Down Expand Up @@ -53,11 +55,11 @@ export const sendPasswordResetLink = async (req: Request, res: Response) => {
await sendPasswordResetLinkService(req, res);
};

export async function activateUser (req: Request, res: Response) {
export async function activateUser(req: Request, res: Response) {
await activateUserService(req, res);
}

export async function disactivateUser (req: Request, res: Response) {
export async function disactivateUser(req: Request, res: Response) {
await deactivateUserService(req, res);
}

Expand All @@ -67,3 +69,11 @@ export const logout = async (req: Request, res: Response) => {
export const userProfileUpdate = async (req: Request, res: Response) => {
await userProfileUpdateServices(req, res);
};

export const getAllUsersController = async (req: Request, res: Response) => {
await getAllUsers(req, res);
};

export const getUserByIdController = async (req: Request, res: Response) => {
await getUserById(req, res);
};
9 changes: 6 additions & 3 deletions src/routes/UserRoutes.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,11 +13,12 @@ import {
userVerification,
verifyOTP,
logout,
getAllUsersController,
getUserByIdController,
} from '../controllers';

import { activateUser, disactivateUser, userProfileUpdate } from '../controllers/index';
import { hasRole } from '../middlewares/roleCheck';
import { isTokenValide } from '../middlewares/isValid';
import passport from 'passport';
import '../utils/auth';
import { start2FAProcess } from '../services/userServices/userStartTwoFactorAuthProcess';
Expand All @@ -35,8 +36,10 @@ router.post('/enable-2fa', enable2FA);
router.post('/disable-2fa', disable2FA);
router.post('/verify-otp', verifyOTP);
router.post('/resend-otp', resendOTP);
router.post('/activate', isTokenValide, hasRole('ADMIN'), activateUser);
router.post('/deactivate', isTokenValide, hasRole('ADMIN'), disactivateUser);
router.get('/allUsers', authMiddleware as RequestHandler, hasRole('ADMIN'), getAllUsersController);
router.get('/single/:id', authMiddleware as RequestHandler, hasRole('ADMIN'), getUserByIdController);
router.post('/activate', authMiddleware as RequestHandler, hasRole('ADMIN'), activateUser);
router.post('/deactivate', authMiddleware as RequestHandler, hasRole('ADMIN'), disactivateUser);
router.post('/password/reset', userPasswordReset);
router.post('/password/reset/link', sendPasswordResetLink);
router.put('/update', authMiddleware as RequestHandler, userProfileUpdate);
Expand Down
1 change: 1 addition & 0 deletions src/services/productServices/listAllProductsService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ export const listAllProductsService = async (req: Request, res: Response) => {
email: true,
phoneNumber: true,
photoUrl: true,
status: true
},
feedbacks: {
id: true,
Expand Down
4 changes: 2 additions & 2 deletions src/services/updateUserStatus/deactivateUserService.ts
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ export const deactivateUserService = async (req: Request, res: Response) => {
return res.status(404).json({ error: 'User not found' });
}

if (user.status === 'suspended') {
if (user.status.toLowerCase() === 'suspended') {
return res.json({ message: 'User is already suspended' });
}

Expand All @@ -32,7 +32,7 @@ export const deactivateUserService = async (req: Request, res: Response) => {

await sendEmail('User_Account_diactivated', { name: user.firstName, email: user.email });

return res.json({ message: 'User deactivated successfully', user });
return res.status(200).json({ message: 'User deactivated successfully', user });
} catch (error) {
return res.status(500).json({ error: 'Internal server error' });
}
Expand Down
35 changes: 35 additions & 0 deletions src/services/userServices/getAllUsers.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
import { Request, Response } from 'express';
import { getRepository } from 'typeorm';
import { User } from '../../entities/User';

const getAllUsers = async (req: Request, res: Response) => {
try {
const userRepository = getRepository(User);

const users = await userRepository
.createQueryBuilder('user')
.select([
'user.id',
'user.firstName',
'user.lastName',
'user.email',
'user.gender',
'user.phoneNumber',
'user.photoUrl',
'user.verified',
'user.twoFactorEnabled',
'user.status',
'user.userType',
'user.role',
'user.createdAt',
'user.updatedAt',
])
.getMany();

res.status(200).json({ message: 'All users retrieved', users });
} catch (error) {
return res.status(500).json({ error: 'Internal server error' });
}
};

export default getAllUsers;
37 changes: 37 additions & 0 deletions src/services/userServices/getUserById.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,37 @@
import { Request, Response } from 'express';
import { getRepository } from 'typeorm';
import { User } from '../../entities/User';

const getUserById = async (req: Request, res: Response) => {
const userId = req.params.id;
try {
const userRepository = getRepository(User);

const user = await userRepository
.createQueryBuilder('user')
.select([
'user.id',
'user.firstName',
'user.lastName',
'user.email',
'user.gender',
'user.phoneNumber',
'user.photoUrl',
'user.verified',
'user.twoFactorEnabled',
'user.status',
'user.userType',
'user.role',
'user.createdAt',
'user.updatedAt',
])
.where('user.id = :id', { id: userId })
.getOne();

user && res.status(200).json({ message: 'User retrived', user });
} catch (error) {
return res.status(500).json({ error: 'Internal server error' });
}
};

export default getUserById;
Loading