Skip to content

Commit

Permalink
Merge d34bada into cc96e8b
Browse files Browse the repository at this point in the history
  • Loading branch information
nignanthomas committed Jan 14, 2020
2 parents cc96e8b + d34bada commit d404626
Show file tree
Hide file tree
Showing 16 changed files with 117 additions and 14 deletions.
5 changes: 3 additions & 2 deletions src/controllers/accommodationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -167,6 +167,7 @@ export default class AccommodationController {
const newBooking = await models.booking.create(bookingData);

await notifSender(
req,
'Accommodation Booked',
newBooking,
accommodation[0].owner,
Expand Down Expand Up @@ -280,7 +281,7 @@ export default class AccommodationController {
await bookingHelper.updateAccomodation(req, remainingSpace);
}

await notifSender(subject, booking, booking.userId, APP_URL_BACKEND, activity, 'booking', host);
await notifSender(req, subject, booking, booking.userId, APP_URL_BACKEND, activity, 'booking', host);
return responseHelper(res, responseMessage, null, 200);
}
return responseHelper(res, strings.accommodations.error.BOOKING_NOT_FOUND, null, 404);
Expand Down Expand Up @@ -343,7 +344,7 @@ export default class AccommodationController {
}

static async viewTopRated(req, res) {
const accommodations = await getAllAccommodations();
const accommodations = await getAllAccommodations({ isActivated: true });
const values = [];

accommodations.forEach(accommodation => {
Expand Down
1 change: 1 addition & 0 deletions src/controllers/chatController.js
Original file line number Diff line number Diff line change
Expand Up @@ -130,4 +130,5 @@ const viewPrivateChats = async (req, res) => {
EMPTY_HISTORY : CHAT_HISTORY, privateChats);
};


export default { chat, viewChats , viewPrivateChats};
2 changes: 1 addition & 1 deletion src/controllers/commentsController.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@ export default class CommentsController {
userNotiified,
`A comment has been made on request ${requestId}. Click here to view: ${APP_URL_BACKEND}/api/v1/requests/${requestId}.`,
);
await notifSaver(notification);
await notifSaver(req, notification);
const {
deleted, userId,
...data
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/destinationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ export default class destinationController {

const { lineManager } = user.payload;

await notifSender('Request Created', request, lineManager, APP_URL_BACKEND, 'created', 'request', host);
await notifSender(req, 'Request Created', request, lineManager, APP_URL_BACKEND, 'created', 'request', host);

return Utilities.responseHelper(
res,
Expand Down
5 changes: 2 additions & 3 deletions src/controllers/requestController.js
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,6 @@ export default class requestController {
statusId, activity, subject, responseMessage
} = req;
const { host } = req.body;

const requestToProcess = await findOneRequest({ id });
const { userId } = requestToProcess;
const user = await findUser({ id: userId });
Expand All @@ -95,7 +94,7 @@ export default class requestController {

request = request[1][0].dataValues;

await notifSender(subject, request, request.userId, APP_URL_BACKEND, activity, 'request', host);
await notifSender(req, subject, request, request.userId, APP_URL_BACKEND, activity, 'request', host);
return responseHelper(res, responseMessage, null, 200);
}
return responseHelper(res, strings.requests.NOT_FOUND, null, 404);
Expand Down Expand Up @@ -123,7 +122,7 @@ export default class requestController {

const request = await allSearch({ id });
const requestData = request[0].dataValues;
await notifSender('Request Edited', requestData, lineManager, APP_URL_BACKEND, 'edited', 'request');
await notifSender(req, 'Request Edited', requestData, lineManager, APP_URL_BACKEND, 'edited', 'request');
return responseUtil(res, 200, strings.request.success.SUCCESS_UPDATE_REQUEST, request);
} catch (error) {
return res.status(500).json({ error: 'Something wrong' });
Expand Down
2 changes: 2 additions & 0 deletions src/controllers/userController.js
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,7 @@ export default class UserController {
const user = models.users.build({
username,
email,
company: 'Andela',
password: hashPassword(password)
});
user.save().then(user => {
Expand All @@ -35,6 +36,7 @@ export default class UserController {
userId: user.id,
username: user.username,
email: user.email,
company: user.company,
});
});
}
Expand Down
6 changes: 4 additions & 2 deletions src/helpers/notifSender.js
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,9 @@ const transporter = nodemailer.createTransport({
}
});

const notifSender = async (subject, object, userId, APP_URL_BACKEND, activity, table, host) => {
const notifSender = async (
req, subject, object, userId, APP_URL_BACKEND, activity, table, host
) => {
try {
const user = await findUser({ id: userId });
let URL;
Expand All @@ -33,7 +35,7 @@ const notifSender = async (subject, object, userId, APP_URL_BACKEND, activity, t
if (user.appNotif) {
const notification = await notifBuilder(table, object.id, userId, activityMessage);
try {
await notifSaver(notification);
await notifSaver(req, notification);
} catch (error) {
return error;
}
Expand Down
11 changes: 11 additions & 0 deletions src/helpers/socketNotif.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
const socketNotif = (receiverId, data, connectedClients, io) => {
if (!receiverId) {
io.emit('notification', data);
} else if (connectedClients[receiverId.toString()]) {
connectedClients[receiverId.toString()].forEach(element => {
io.to(element).emit('notification', data);
});
}
};

export default socketNotif;
31 changes: 29 additions & 2 deletions src/index.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
/* eslint-disable no-console */
// eslint-disable-next-line no-unused-vars
import regeneratorRuntime from 'regenerator-runtime';
import dotenv from 'dotenv';
Expand All @@ -9,6 +10,7 @@ import errorhandler from 'errorhandler';
import cors from 'cors';
import allRoutes from './routes';
import chatController from './controllers/chatController';
import decodeToken from './middlewares/auth/decodeToken';

// Create global app object
dotenv.config();
Expand Down Expand Up @@ -50,6 +52,31 @@ io.on('connect', socket => {
});
});

http.listen(port, () => console.log(`Barefoot Nomad is runnig server on port ${port}...`));

const connectedClients = {};
io.use((socket, next) => {
const { token } = socket.handshake.query;
try {
const userData = decodeToken(token);
if (userData) {
const clientKey = Number.parseInt(userData.payload.id, 10);
connectedClients[clientKey] = connectedClients[clientKey] || [];
connectedClients[clientKey].push(socket.id);
}
next();
} catch (error) {
return (error);
}
});


app.use((req, res, next) => {
req.io = io;
req.connectedClients = connectedClients;
next();
});

app.use('/', allRoutes);

app.use('*', (req, res) => {
Expand All @@ -58,7 +85,7 @@ app.use('*', (req, res) => {
message: 'Sorry this route does not exist !',
});
});
// eslint-disable-next-line no-console
http.listen(port, () => console.log(`Barefoot Nomad is runnig server on port ${port}...`));

export { io };

export default app;
10 changes: 10 additions & 0 deletions src/middlewares/auth/decodeToken.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import jwt from 'jsonwebtoken';

export default token => {
try {
const verifiedUser = jwt.verify(token, process.env.JWT_SECRET);
return verifiedUser;
} catch (error) {
return error;
}
};
3 changes: 2 additions & 1 deletion src/middlewares/inputValidation.js
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,8 @@ export default class InputValidation {
static validateProfile(req, res, next) {
const schema = Joi.object({
username: Joi.string().trim().min(3).max(100),
phone: Joi.string().trim().regex(/^[0-9]{3,10}$/),
phone: Joi.string().trim().regex(/^[0-9]{3,10}$/)
.message('The phone number should be numbers of 3 to 10 digits.'),
gender: Joi.string().valid('female', 'male'),
language: Joi.string().min(2).max(15).regex(/^[a-zA-Z]/),
dob: Joi.date(),
Expand Down
6 changes: 5 additions & 1 deletion src/services/notifServices.js
Original file line number Diff line number Diff line change
@@ -1,10 +1,14 @@
/* eslint-disable require-jsdoc */
import moment from 'moment';
import models from '../database/models';
import socketNotif from '../helpers/socketNotif';

export default class notifServices {
static async notifSaver(notif) {
static async notifSaver(req, notif) {
const notification = await notif.save();
socketNotif(
notification.userNotified, notification, req.connectedClients, req.io,
);
return notification;
}

Expand Down
27 changes: 27 additions & 0 deletions src/tests/helperTests/decodeTokenTest.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import chai from 'chai';
import decodeToken from '../../middlewares/auth/decodeToken';
import generateToken from '../../utils/generateToken';
import mockData from '../mockData/mockData';


const { expect } = chai;
describe('Decode Token test', () => {
it('Should decode the token', (done) => {
try {
decodeToken(generateToken(mockData.verifiedUser1));
} catch (error) {
expect(error).to.be.null;
}
done();
});

it('Should not decode the token', (done) => {
try {
decodeToken('malformed token');
} catch (error) {
console.log('error ===>', error);
expect(error).to.be.an('object');;
}
done();
});
});
16 changes: 16 additions & 0 deletions src/tests/helperTests/socketNotifTest.spec.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import chai from 'chai';
// import { io } from '../../index';
import socketNotif from '../../helpers/socketNotif';

const { expect } = chai;
describe('Socket Notif Test', () => {
it('Should emit to one', (done) => {
socketNotif(1, {}, {'1': ['jhjhjh', 'mnjhj'], io: {to: () => {}, emit: () => {}, }});
done();
});

it('Should emit to all', (done) => {
socketNotif(undefined, {}, {'1': ['jhjhjh', 'mnjhj'], io: {to: () => {}, emit: () => {}, }});
done();
});
});
2 changes: 2 additions & 0 deletions src/tests/index.spec.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ import bookmarkTests from './bookmarkTests.spec';
import unitTests from './unitTests.spec';
import likeTests from './likeTests.spec';
import logoutTests from './logoutTests.spec';
import decocodeTokenTest from './helperTests/decodeTokenTest.spec';

describe('Default Tests', defaultTests);
describe('Edit Request Tests', editRequest);
Expand Down Expand Up @@ -50,4 +51,5 @@ describe('Accommodation Search Tests', accommodationSearchTests);
describe('Bookmarks Tests', bookmarkTests);
describe('Unit Tests', unitTests);
describe('Likes Tests', likeTests);
describe('DecodeToken Tests', decocodeTokenTest);
describe('Logout Tests', logoutTests);
2 changes: 1 addition & 1 deletion src/utils/stringsUtil.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ const strings = {
SUCCESS_VERIFIED: 'You have been verified',
SEND_EMAIL: 'please check your email to see the link for reseting password',
PASSWORD_CHANGED: 'password changed successfully',
SUCCESS_UPDATE: 'User Updated',
SUCCESS_UPDATE: 'User profile updated successfully',
SUCCESSFUL_LOGIN: 'User logged in successfully!',
SUCCESSFUL_ASSIGN: 'you have assigned the role to this user',
ROLE_ADDED: 'role added successfully',
Expand Down

0 comments on commit d404626

Please sign in to comment.