Skip to content

Commit

Permalink
correcting the test cases for auth middleware
Browse files Browse the repository at this point in the history
  • Loading branch information
udaysingh236 committed Aug 20, 2023
1 parent 17afef8 commit 1eda61f
Show file tree
Hide file tree
Showing 7 changed files with 105 additions and 53 deletions.
38 changes: 14 additions & 24 deletions src/app.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,9 @@
import express, { Request, Response, NextFunction } from 'express';
import express from 'express';
import 'dotenv/config'; //this we need for jest
import morgan from 'morgan';
import helmet from 'helmet';
import cookieSession from 'cookie-session';
import passport from './services/passport';
import passport from './services/passport.service';
import indexRouter from './routes/index';
import hotelRouter from './routes/hotels';
import roomRouter from './routes/rooms';
Expand All @@ -14,7 +15,7 @@ import availbilityRouter from './routes/availability';
import reservationRouter from './routes/reservation';
import authRouter from './routes/auth';
import swaggerDocs from './utils/swagger';
import { logger } from './utils/logger';
import * as auth from './services/auth.service';
const app = express();
const port = process.env.port || 3000;

Expand All @@ -30,29 +31,18 @@ app.use(
app.use(passport.initialize());
app.use(passport.session());

function checkUserLoggedIn(req: Request, res: Response, next: NextFunction) {
logger.debug(`Current user is ${req.user}`);
const isUserLoggedIn = req.isAuthenticated() && req.user;
if (!isUserLoggedIn) {
return res.status(401).send({
error: 'You are not logged in..!!'
});
}
next();
}

app.use(express.json());
app.use(morgan('tiny'));
app.use('/v1/auth', authRouter);
swaggerDocs(app, port, checkUserLoggedIn);
app.use('/v1/', checkUserLoggedIn, indexRouter);
app.use('/v1/hotels', checkUserLoggedIn, hotelRouter);
app.use('/v1/hotels', checkUserLoggedIn, roomRouter);
app.use('/v1/hotels', checkUserLoggedIn, employeeRouter);
app.use('/v1/hotels', checkUserLoggedIn, couponRouter);
app.use('/v1/hotels', checkUserLoggedIn, voucherRouter);
app.use('/v1/hotels', checkUserLoggedIn, rateRouter);
app.use('/v1/hotels', checkUserLoggedIn, availbilityRouter);
app.use('/v1/hotels', checkUserLoggedIn, reservationRouter);
swaggerDocs(app, port, auth.checkUserLoggedIn);
app.use('/v1/', auth.checkUserLoggedIn, indexRouter);
app.use('/v1/hotels', auth.checkUserLoggedIn, hotelRouter);
app.use('/v1/hotels', auth.checkUserLoggedIn, roomRouter);
app.use('/v1/hotels', auth.checkUserLoggedIn, employeeRouter);
app.use('/v1/hotels', auth.checkUserLoggedIn, couponRouter);
app.use('/v1/hotels', auth.checkUserLoggedIn, voucherRouter);
app.use('/v1/hotels', auth.checkUserLoggedIn, rateRouter);
app.use('/v1/hotels', auth.checkUserLoggedIn, availbilityRouter);
app.use('/v1/hotels', auth.checkUserLoggedIn, reservationRouter);

export default app;
30 changes: 21 additions & 9 deletions src/routes/employee.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import request from 'supertest';
import app from '../app';
import * as auth from '../services/auth.service';
import * as employeeController from '../controllers/employee.controller';
const mcheckUserLoggedIn = jest
.spyOn(auth, 'checkUserLoggedIn')
.mockImplementation((req, res, next) => {
req.user = 'john.doe'; //for testing bypassing the auth
if (!req.user) {
return res.status(401).send({
error: 'You are not logged in..!!'
});
}
next();
});
import app from '../app'; //This should be in the last or after the mock

describe('GET - Fetch employees details of a Hotel', () => {
afterAll(() => {
jest.resetAllMocks();
});
test('Should return all employees details', async () => {
const mgetHotelEmpDetails = jest
.spyOn(employeeController, 'getHotelEmpDetails')
Expand All @@ -16,6 +25,7 @@ describe('GET - Fetch employees details of a Hotel', () => {
);

const res = await request(app).get('/v1/hotels/10/employees');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetHotelEmpDetails).toHaveBeenCalled();
expect(res.status).toEqual(200);
});
Expand All @@ -30,13 +40,14 @@ describe('GET - Fetch employees details of a Hotel', () => {
);

const res = await request(app).get('/v1/hotels/100/employees');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetHotelEmpDetails).toHaveBeenCalled();
expect(res.status).toEqual(404);
expect(res.text).toEqual('Not able to find employee data');
mgetHotelEmpDetails.mockReset();
});

test('Should return error message when hotel ID is string', async () => {
jest.resetAllMocks();
const mgetHotelEmpDetails = jest
.spyOn(employeeController, 'getHotelEmpDetails')
.mockReturnValueOnce(
Expand All @@ -45,6 +56,7 @@ describe('GET - Fetch employees details of a Hotel', () => {
})
);
const res = await request(app).get('/v1/hotels/100AA/employees');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetHotelEmpDetails).not.toHaveBeenCalled();
expect(res.status).toEqual(400); //intentionally keeping it different since the function is not getting called
// If somehow it got called there is a double check and doube chance of failure.
Expand All @@ -53,9 +65,6 @@ describe('GET - Fetch employees details of a Hotel', () => {
});

describe('GET - Fetch employees details of a Hotel with employee name in query parameter', () => {
afterAll(() => {
jest.resetAllMocks();
});
test('Should return all employees details matching the query string', async () => {
const getHotelEmpDetailsByName = jest
.spyOn(employeeController, 'getHotelEmpDetailsByName')
Expand All @@ -66,6 +75,7 @@ describe('GET - Fetch employees details of a Hotel with employee name in query p
);

const res = await request(app).get('/v1/hotels/10/employees?empName=tt');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(getHotelEmpDetailsByName).toHaveBeenCalled();
expect(res.status).toEqual(200);
});
Expand All @@ -79,13 +89,14 @@ describe('GET - Fetch employees details of a Hotel with employee name in query p
})
);
const res = await request(app).get('/v1/hotels/100/employees?empName=tt');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetHotelEmpDetailsByName).toHaveBeenCalled();
expect(res.status).toEqual(404);
expect(res.text).toEqual('Not able to find employee data');
mgetHotelEmpDetailsByName.mockReset();
});

test('Should return error message when employee name doesnot contains only letters', async () => {
jest.resetAllMocks();
const mgetHotelEmpDetailsByName = jest
.spyOn(employeeController, 'getHotelEmpDetailsByName')
.mockReturnValueOnce(
Expand All @@ -94,6 +105,7 @@ describe('GET - Fetch employees details of a Hotel with employee name in query p
})
);
const res = await request(app).get('/v1/hotels/10/employees?empName=tt33');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetHotelEmpDetailsByName).not.toHaveBeenCalled();
//intentionally keeping it different since the function is not getting called
// If somehow it got called there is a double check and doube chance of failure.
Expand Down
28 changes: 20 additions & 8 deletions src/routes/hotels.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import request from 'supertest';
import app from '../app';
import * as auth from '../services/auth.service';
import * as hotelController from '../controllers/hotel.contoller';
const mcheckUserLoggedIn = jest
.spyOn(auth, 'checkUserLoggedIn')
.mockImplementation((req, res, next) => {
req.user = 'john.doe'; //for testing bypassing the auth
if (!req.user) {
return res.status(401).send({
error: 'You are not logged in..!!'
});
}
next();
});
import app from '../app'; //This should be in the last or after the mock

describe('GET - Fetch information of all the hotels', () => {
afterAll(() => {
jest.resetAllMocks();
});
test('Should return information of all the hotels', async () => {
const mgetAllHotelsDetails = jest
.spyOn(hotelController, 'getAllHotelsDetails')
Expand All @@ -16,15 +25,14 @@ describe('GET - Fetch information of all the hotels', () => {
);

const res = await request(app).get('/v1/hotels/');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetAllHotelsDetails).toHaveBeenCalled();
expect(res.status).toEqual(200);
mgetAllHotelsDetails.mockReset();
});
});

describe('GET - Fetch information of a hotel by hotelID', () => {
afterAll(() => {
jest.resetAllMocks();
});
test('Should return information of a hotel', async () => {
const mgetHotelDetails = jest.spyOn(hotelController, 'getHotelDetails').mockReturnValueOnce(
Promise.resolve({
Expand All @@ -33,8 +41,10 @@ describe('GET - Fetch information of a hotel by hotelID', () => {
);

const res = await request(app).get('/v1/hotels/10');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetHotelDetails).toHaveBeenCalled();
expect(res.status).toEqual(200);
mgetHotelDetails.mockReset();
});

test('Should return not able to find hotel data', async () => {
Expand All @@ -45,20 +55,22 @@ describe('GET - Fetch information of a hotel by hotelID', () => {
);

const res = await request(app).get('/v1/hotels/100');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetHotelDetails).toHaveBeenCalled();
expect(res.status).toEqual(404);
expect(res.text).toEqual('Not able to find hotel Data');
mgetHotelDetails.mockReset();
});

test('Should error out when non numeric hotel ID is passed', async () => {
jest.resetAllMocks();
const mgetHotelDetails = jest.spyOn(hotelController, 'getHotelDetails').mockReturnValueOnce(
Promise.resolve({
status: 404
})
);

const res = await request(app).get('/v1/hotels/10AA');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetHotelDetails).not.toHaveBeenCalled();
//intentionally keeping it different since the function is not getting called
// If somehow it got called there is a double check and double chance of failure.
Expand Down
15 changes: 14 additions & 1 deletion src/routes/index.test.ts
Original file line number Diff line number Diff line change
@@ -1,10 +1,23 @@
import request from 'supertest';
import app from '../app';
import * as auth from '../services/auth.service';
const mcheckUserLoggedIn = jest
.spyOn(auth, 'checkUserLoggedIn')
.mockImplementation((req, res, next) => {
req.user = 'john.doe'; //for testing bypassing the auth
if (req.user) {
next();
}
return res.status(401).send({
error: 'You are not logged in..!!'
});
});
import app from '../app'; //This should be in the last or after the mock

describe('GET - Respond when requesting for healthcheck', () => {
test('Should return success message', async () => {
const res = await request(app).get('/v1/healthcheck');
expect(res.status).toEqual(200);
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(res.text).toEqual('Hello from Kutir, I am alive..!!');
});
});
34 changes: 23 additions & 11 deletions src/routes/rooms.test.ts
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
import request from 'supertest';
import app from '../app';
import * as auth from '../services/auth.service';
import * as roomController from '../controllers/room.controller';
const mcheckUserLoggedIn = jest
.spyOn(auth, 'checkUserLoggedIn')
.mockImplementation((req, res, next) => {
req.user = 'john.doe'; //for testing bypassing the auth
if (!req.user) {
return res.status(401).send({
error: 'You are not logged in..!!'
});
}
next();
});
import app from '../app'; //This should be in the last or after the mock

describe('GET - Get information of all the rooms a hotel', () => {
afterAll(() => {
jest.resetAllMocks();
});
test('Should return information of all the rooms a hotel', async () => {
const mgetHotelRoomsDetails = jest
.spyOn(roomController, 'getHotelRoomsDetails')
Expand All @@ -16,8 +25,10 @@ describe('GET - Get information of all the rooms a hotel', () => {
);

const res = await request(app).get('/v1/hotels/10/rooms');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetHotelRoomsDetails).toHaveBeenCalled();
expect(res.status).toEqual(200);
mgetHotelRoomsDetails.mockReset();
});

test('Should return information of a room number passed in query string', async () => {
Expand All @@ -30,12 +41,13 @@ describe('GET - Get information of all the rooms a hotel', () => {
);

const res = await request(app).get('/v1/hotels/10/rooms?roomNum=102');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetRoomDetailsFromNumber).toHaveBeenCalled();
expect(res.status).toEqual(200);
mgetRoomDetailsFromNumber.mockReset();
});

test('Should error out when non numeric room number passed in query string', async () => {
jest.resetAllMocks();
const mgetRoomDetailsFromNumber = jest
.spyOn(roomController, 'getRoomDetailsFromNumber')
.mockReturnValueOnce(
Expand All @@ -45,13 +57,13 @@ describe('GET - Get information of all the rooms a hotel', () => {
);

const res = await request(app).get('/v1/hotels/10/rooms?roomNum=102AA');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetRoomDetailsFromNumber).not.toHaveBeenCalled();
expect(res.status).toEqual(400);
expect(res.text).toEqual('Hotel ID and Room Number type should be number.');
});

test('Should error out when non numeric hotel ID is passed', async () => {
jest.resetAllMocks();
const mgetHotelRoomsDetails = jest
.spyOn(roomController, 'getHotelRoomsDetails')
.mockReturnValueOnce(
Expand All @@ -62,6 +74,7 @@ describe('GET - Get information of all the rooms a hotel', () => {

const res = await request(app).get('/v1/hotels/10AA/rooms');
expect(mgetHotelRoomsDetails).not.toHaveBeenCalled();
expect(mcheckUserLoggedIn).toHaveBeenCalled();
//intentionally keeping it different since the function is not getting called
// If somehow it got called there is a double check and double chance of failure.
expect(res.status).toEqual(400);
Expand All @@ -70,9 +83,6 @@ describe('GET - Get information of all the rooms a hotel', () => {
});

describe('GET - Get information of a room by Hotel ID or Room ID', () => {
afterAll(() => {
jest.resetAllMocks();
});
test('Should return information about a room of a hotel', async () => {
const mgetRoomDetailsFromId = jest
.spyOn(roomController, 'getRoomDetailsFromId')
Expand All @@ -83,12 +93,13 @@ describe('GET - Get information of a room by Hotel ID or Room ID', () => {
);

const res = await request(app).get('/v1/hotels/1/rooms/12');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetRoomDetailsFromId).toHaveBeenCalled();
mgetRoomDetailsFromId.mockReset();
expect(res.status).toEqual(200);
});

test('Should error out when non numeric hotel ID is passed', async () => {
jest.resetAllMocks();
const mgetRoomDetailsFromId = jest
.spyOn(roomController, 'getRoomDetailsFromId')
.mockReturnValueOnce(
Expand All @@ -98,6 +109,7 @@ describe('GET - Get information of a room by Hotel ID or Room ID', () => {
);

const res = await request(app).get('/v1/hotels/10AA/rooms/12');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetRoomDetailsFromId).not.toHaveBeenCalled();
//intentionally keeping it different since the function is not getting called
// If somehow it got called there is a double check and double chance of failure.
Expand All @@ -106,7 +118,6 @@ describe('GET - Get information of a room by Hotel ID or Room ID', () => {
});

test('Should error out when non numeric room ID is passed', async () => {
jest.resetAllMocks();
const mgetRoomDetailsFromId = jest
.spyOn(roomController, 'getRoomDetailsFromId')
.mockReturnValueOnce(
Expand All @@ -116,6 +127,7 @@ describe('GET - Get information of a room by Hotel ID or Room ID', () => {
);

const res = await request(app).get('/v1/hotels/10/rooms/12AA');
expect(mcheckUserLoggedIn).toHaveBeenCalled();
expect(mgetRoomDetailsFromId).not.toHaveBeenCalled();
//intentionally keeping it different since the function is not getting called
// If somehow it got called there is a double check and double chance of failure.
Expand Down
13 changes: 13 additions & 0 deletions src/services/auth.service.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
import { Request, Response, NextFunction } from 'express';
import { logger } from '../utils/logger';

export function checkUserLoggedIn(req: Request, res: Response, next: NextFunction) {
logger.debug(`Current user is ${req.user}`);
const isUserLoggedIn = req.isAuthenticated() && req.user;
if (!isUserLoggedIn) {
return res.status(401).send({
error: 'You are not logged in..!!'
});
}
next();
}
File renamed without changes.

0 comments on commit 1eda61f

Please sign in to comment.