Skip to content

Commit

Permalink
Merge 7d15750 into caeb9aa
Browse files Browse the repository at this point in the history
  • Loading branch information
parkerthegeniuschild committed Sep 10, 2019
2 parents caeb9aa + 7d15750 commit 969fef8
Show file tree
Hide file tree
Showing 13 changed files with 9,246 additions and 9,581 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
### Node ###
# Logs
src/logs/app.log
src/logs/app*.log
npm-debug.log*
yarn-debug.log*
yarn-error.log*
Expand Down
18,118 changes: 9,066 additions & 9,052 deletions package-lock.json

Large diffs are not rendered by default.

16 changes: 12 additions & 4 deletions src/controllers/rating.controller.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import models from '../db/models';
import Response from '../utils/response.utils';
import RatingsCalculator from '../utils/rating.utils';

const { Rating, Facility } = models;

Expand All @@ -13,19 +14,26 @@ export default class RatingController {
* @returns {array} An array of objects containing ratings
*/
static findAll(req, res) {
Facility.findByPk(req.params.id)
const { id: facility_id } = req.params;

Facility.findByPk(facility_id)
.then((data) => {
if (!data) {
return Response.CustomError(res, 404, 'error',
`No facility found with ID: ${req.params.id}`, 'Consult the facility Admin');
}
// Rating.findAll({
// where: { facility_id: req.params.id },
// attributes: ['id', 'facility_id', 'rating', 'created_at', 'updated_at']

Rating.findAll({
where: { facility_id: req.params.id },
attributes: ['id', 'facility_id', 'rating', 'created_at', 'updated_at']
where: { facility_id },
attributes: ['facility_id', 'rating']
})
.then((data) => {
if (data.length) {
return Response.Success(res, data, 200);
const ratings = RatingsCalculator(data);
return Response.Success(res, ratings, 200);
}
return Response.CustomError(res, 404, 'error', 'No rating found for this facility',
'Please check again later');
Expand Down
43 changes: 29 additions & 14 deletions src/controllers/user.controller.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,4 @@
/* eslint-disable camelcase */
import crypto from 'crypto';

import bcrypt from 'bcrypt';
import models from '../db/models';
import sender from '../services/email.service';
Expand Down Expand Up @@ -103,7 +101,7 @@ export default class UserController {
* @param {Object} res
* @param {Function} next
* @returns {JSON} res
*/
*/
static async setUserRole(req, res, next) {
try {
const { role, email } = req.body;
Expand Down Expand Up @@ -160,11 +158,11 @@ export default class UserController {
}

/**
* get all managers
* @param {ServerRequest} req
* @param {ServerResponse} res
* @returns {ServerResponse} response
*/
* get all managers
* @param {ServerRequest} req
* @param {ServerResponse} res
* @returns {ServerResponse} response
*/
static async getManagers(req, res) {
try {
const result = await User.findAll({ attributes: ['id', 'first_name', 'last_name', 'email', 'preferred_language', 'location'], where: { role: 'manager' } });
Expand All @@ -175,12 +173,12 @@ export default class UserController {
}

/**
* @static
* @param {object} req
* @param {object} res
* @returns {json} - json
* @memberof UserController
*/
* @static
* @param {object} req
* @param {object} res
* @returns {json} - json
* @memberof UserController
*/
static async resetpasswordEmail(req, res) {
let userToken;
let payload;
Expand Down Expand Up @@ -222,4 +220,21 @@ export default class UserController {
});
});
}

/**
* Handles auto retrieval of user's profile needed for travel
* @param {*} req
* @param {*} res
* @returns {*} response
*/
static retrieveProfile(req, res) {
const { id: user_id } = req.body.user;

return User.findByPk(user_id, {
attributes: ['first_name', 'last_name', 'email',
'manager_id', 'gender', 'birth_date', 'location']
})
.then((data) => Response.Success(res, data))
.catch((err) => Response.InternalServerError(res, err));
}
}
14 changes: 14 additions & 0 deletions src/db/seeders/20190828065822-ratings-seeder.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,20 @@ module.exports = {
created_at: new Date(),
updated_at: new Date()
},
{
rating: 5,
user_id: 3,
facility_id: 1,
created_at: new Date(),
updated_at: new Date()
},
{
rating: 2,
user_id: 2,
facility_id: 1,
created_at: new Date(),
updated_at: new Date()
},
{
rating: 3,
user_id: 2,
Expand Down
505 changes: 0 additions & 505 deletions src/logs/app1.log

This file was deleted.

2 changes: 1 addition & 1 deletion src/logs/winston.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,7 +8,7 @@ const options = {
filename: `${appRoot}/src/logs/app.log`,
handleExceptions: true,
json: true,
maxsize: 5242880, // %MB
maxsize: 20971520, // 20MB
maxFiles: 5,
colorize: false,
},
Expand Down
3 changes: 1 addition & 2 deletions src/middlewares/jwtAuth.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,8 +17,7 @@ const verifyToken = (req, res, next) => {
}
if (token.startsWith('Bearer')) token = token.slice(7);
try {
const decoded = jwt.verify(token, secret);
req.body.user = decoded;
req.body.user = jwt.verify(token, secret);
return next();
} catch (err) {
return res.status(401).json({
Expand Down
8 changes: 6 additions & 2 deletions src/routes/api/user.router.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,14 +5,18 @@ import UserMiddleware from '../../middlewares/user.middleware';
import roleValidation from '../../validation/user/role.validation';
import profileValidation from '../../validation/profile.validation';
import getValuesToUpdate from '../../middlewares/profile.middleware';
import Validator from '../../validation/index';

const { isSuperAdmin } = UserMiddleware;
const { setUserRole, updateProfile, getManagers } = UserController;
const {
setUserRole, updateProfile, getManagers, retrieveProfile
} = UserController;

const router = express.Router();

router.patch('/role', verifyToken, isSuperAdmin, roleValidation, setUserRole);
router.get('/managers', verifyToken, getManagers);

router.get('/user/profile', verifyToken, Validator.rememberMe, retrieveProfile);
router.patch('/profile', verifyToken, profileValidation, getValuesToUpdate, updateProfile);

export default router;
77 changes: 77 additions & 0 deletions src/test/retrieve-profile.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,77 @@
import chai from 'chai';
import chaiHttp from 'chai-http';
import sinon from 'sinon';
import Sinonchai from 'sinon-chai';
import app from '../index';
import JWTService from '../services/jwt.service';
import UserController from '../controllers/user.controller';

chai.use(Sinonchai);
chai.use(chaiHttp);
chai.should();

const profileEndpoint = '/api/v1/user/profile';
let userToken = `Bearer ${JWTService.generateToken({ id: 1, role: 'requester'})}`;

describe('/RETRIEVE PROFILE', () => {

it('should allow only logged in users', (done) => {
chai.request(app)
.get(`${profileEndpoint}?rememberMe=yes`)
.set('Authorization', '')
.end((err, res) => {
res.should.have.status(401);
res.body.should.have.property('status').eql('error');
done();
})
});

it('should return 200 if profile is retrieved successfully', (done) => {
chai.request(app)
.get(`${profileEndpoint}?rememberMe=yes`)
.set('Authorization', userToken)
.end((err, res) => {
res.should.have.status(200);
res.body.should.have.property('status').eql('success');
done();
})
});

it('should return 500 if something goes wrong', (done) => {
const req = {
query: {
rememberMe: 'yes'
},
headers: {
authorization: userToken
},
body: {
user: {
id: 3
}
}
};

const res = {
status() {},
send() {}
};

sinon.stub(res, 'status').returnsThis();

UserController.retrieveProfile(req, res);
(res.status).should.have.callCount(0);
done();
});

it('should return 400 when rememberMe is set to NO', (done) => {
chai.request(app)
.get(`${profileEndpoint}?rememberMe=no`)
.set('Authorization', userToken)
.end((err, res) => {
res.should.have.status(400);
res.body.should.have.property('status').eql('error');
done();
})
});
});
20 changes: 20 additions & 0 deletions src/utils/rating.utils.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
const ratingCalculator = (data) => {
const { facility_id } = data[0];
const ratingTable = {
facility_id,
ratings: {
'5-stars': 0,
'4-stars': 0,
'3-stars': 0,
'2-stars': 0,
'1-star': 0,
}
};

for (let i = 0; i < data.length; i += 1) {
ratingTable.ratings[`${data[i].rating}-stars`] += 1;
}
return ratingTable;
};

export default ratingCalculator;
2 changes: 1 addition & 1 deletion src/utils/response.utils.js
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ export default class {
* @param {string} information
* @returns {Object} response
*/
static CustomError(res, code, status, message, information = 0) {
static CustomError(res, code, status, message, information) {
return res.status(code).json({
status,
error: {
Expand Down
18 changes: 18 additions & 0 deletions src/validation/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -63,4 +63,22 @@ export default {

return next();
},

rememberMe: (req, res, next) => {
const errors = [];
const { rememberMe } = req.query;

if (rememberMe.toLowerCase() !== 'yes') {
errors.push('user profile will not be auto retrieved next time. Choose "YES" to do so.');
}

if (errors.length) {
return res.status(400).json({
status: 'error',
error: errors,
});
}

return next();
},
};

0 comments on commit 969fef8

Please sign in to comment.