Skip to content

Commit

Permalink
bg(API): Fix issues with api
Browse files Browse the repository at this point in the history
- refactor reading stats endpoints to return like and dislike count
- replace hardcoded reset url with RESET_URL value in .env
- return timeToRead in fetch favorite articles endpoints

[Delivers #161282228]
  • Loading branch information
iamuchejude committed Oct 18, 2018
1 parent b0bd04c commit 4a13e12
Show file tree
Hide file tree
Showing 9 changed files with 46 additions and 71 deletions.
3 changes: 3 additions & 0 deletions .env.sample → .env.1.sample
Original file line number Diff line number Diff line change
Expand Up @@ -3,18 +3,21 @@ DB_PASS=
DB_DATABASE=
DB_HOST=
DB_DIALECT=postgres
DB_PORT=5433

TEST_DB_USER=
TEST_DB_PASS=
TEST_DB_DATABASE=
TEST_DB_HOST=
TEST_DB_DIALECT=postgres
TEST_DB_PORT=5433

PROD_DB_USER=
PROD_DB_PASS=
PROD_DB_DATABASE=
PROD_DB_HOST=
PROD_DB_DIALECT=postgres
PROD_DB_PORT=5433

USER_PASSWORD=
ADMIN_PASSWORD=
Expand Down
5 changes: 1 addition & 4 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,9 +1,6 @@
{
"name": "express-authorshaven",
"version": "1.0.0",
"engines": {
"node": "10.8.0"
},
"description": "A Social platform for the creative at heart",
"main": "index.js",
"scripts": {
Expand All @@ -22,7 +19,7 @@
"license": "MIT",
"dependencies": {
"@sendgrid/mail": "^6.3.1",
"bcrypt": "^3.0.0",
"bcrypt": "^3.0.2",
"body-parser": "^1.18.3",
"chai": "^4.1.2",
"chai-http": "^4.0.0",
Expand Down
4 changes: 2 additions & 2 deletions server/controllers/favoriteArticle.js
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ class FavoriteArticleController {
}))
.catch(error => res.status(500).json({
status: 'error',
error: { message: error.message ? error.message : 'An error occured during this operation' }
error: { message: error.message ? error.message : 'An error occurred during this operation' }
}));
}

Expand Down Expand Up @@ -96,7 +96,7 @@ class FavoriteArticleController {
include: [
{
model: Article,
attributes: ['title', 'description', 'body', 'slug', 'createdAt'],
attributes: ['title', 'description', 'body', 'slug', 'createdAt', 'timeToRead'],
include: [{
model: User,
as: 'author',
Expand Down
14 changes: 11 additions & 3 deletions server/controllers/readingStatsController.js
Original file line number Diff line number Diff line change
Expand Up @@ -62,14 +62,22 @@ class ReadingStatsController {
if (categoryNames.length === 0) {
mostReadCategory = 'Articles have not been added to any category';
}
const allReactions = { liked: 0, disliked: 0, };
reaction.forEach((reactions) => {
if (reactions.reaction === '1') {
allReactions.liked += 1;
} else {
allReactions.disliked += 1;
}
});
const names = categoryNames.map(category => category.name);
mostReadCategory = mode(names);
return res.status(200).json({
status: 'success',
articlesRead: articles.length === 0 ? 'No articles found' : articles,
articlesRead: articles,
numberOfArticlesRead: articleCount.length,
articleReactions: reaction.length === 0 ? 'No reactions found' : reaction,
mostReadCategory
articleReactions: allReactions,
mostReadCategory: mostReadCategory || 'None',
});
})
.catch(error => next(error));
Expand Down
20 changes: 14 additions & 6 deletions server/controllers/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -188,8 +188,9 @@ class UsersController {
* @returns {object} The body of the response message
*/
static updateUserProfile(req, res, next) {
const { userId } = req.params;
const { uid } = req.params;
const { userRole } = req;
const userId = userRole === 'admin' ? uid : req.userId;
const {
firstName, lastName, username, bio, twitter, linkedin, facebook, image
} = req.body;
Expand All @@ -205,7 +206,14 @@ class UsersController {
return next(err);
}

isValidNumber(req, res);
if (Number.isNaN(parseInt(userId, 10))) {
return res.status(400).json({
error: {
message: 'Your request ID is invalid'
},
status: 'error'
});
}

/*
* prevent user from updating another users ' profile
Expand Down Expand Up @@ -321,8 +329,8 @@ class UsersController {
* @memberof Users
*/
static resetPassword(req, res, next) {
const { reset } = req.body.tokens;
const { password } = req.body.user;
const { resetToken: reset, password } = req.body;

if (!reset || reset.trim().length < 1) {
res.status(400).json({
status: 'error',
Expand Down Expand Up @@ -392,14 +400,14 @@ class UsersController {
}

const token = jwt.sign({ email }, process.env.JWT_KEY, { expiresIn: '2h' });
const resetLink = `https://thor-ah.com/password/reset/${token}`;
const resetLink = `${process.env.RESET_URL}?token=${token}`;

const msg = `
<div style="font-size: 17px">
<p>Hello,</p>
<p>There was a recent request to change the password on your account.</p>
<p>If you requested this password change, click the reset link below to set a new password:</p>
<a href="${resetLink}">${resetLink}</a>
<a href="${resetLink}"><button style="cursor: pointer; height: 40px; width: 200px; padding: 6px 20px; color: #fff; font-size: 15px !important; border: 1px solid #C40018;background: #C40018; border-radius: 4px;">Reset password</button></a>
<p>If you don’t want to change your password, just ignore this message.</p>
<p>Kindly note that reset link expires in 2 hours.</p>
<p>
Expand Down
2 changes: 1 addition & 1 deletion server/routes/api/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ userRoutes.post('/login', UserController.userLogin);

userRoutes.get('/:username', authenticateUser, UserController.getProfileByUsername);

userRoutes.put('/:userId', authenticateUser, UserController.updateUserProfile);
userRoutes.put('/:uid?', authenticateUser, UserController.updateUserProfile);

userRoutes.post('/password/recover', UserController.recoverPassword);

Expand Down
5 changes: 3 additions & 2 deletions server/tests/controllers/readingstats.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -139,9 +139,10 @@ describe('User\'s reading stats', () => {
expect(res.body).to.have.property('articlesRead');
expect(res.body).to.have.property('numberOfArticlesRead');
expect(res.body).to.have.property('articleReactions');
expect(articlesRead).to.equal('No articles found');
expect(articlesRead).to.be.an('array');
expect(numberOfArticlesRead).to.equal(0);
expect(articleReactions).to.equal('No reactions found');
expect(articleReactions.liked).to.equal(0);
expect(articleReactions.disliked).to.equal(0);
done();
});
});
Expand Down
41 changes: 11 additions & 30 deletions server/tests/controllers/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -168,6 +168,7 @@ describe('Users Controllers', () => {
email: user.email,
})
.end((err, res) => {
console.log('========>', res.body);
res.body.should.be.an('object');
res.body.status.should.equal('success');
res.body.message.should.equal('Please follow the instructions in the email that has been sent to your address.');
Expand Down Expand Up @@ -206,12 +207,8 @@ describe('Users Controllers', () => {
chai.request(app)
.post('/api/users/password/reset')
.send({
tokens: {
reset: token
},
user: {
password: 'newPassword',
},
resetToken: token,
password: 'newPassword'
})
.end((err, res) => {
res.body.should.be.an('object');
Expand All @@ -224,12 +221,8 @@ describe('Users Controllers', () => {
chai.request(app)
.post('/api/users/password/reset')
.send({
tokens: {
reset: '',
},
user: {
password: 'newPassword',
},
resetToken: '',
password: 'newPassword'
})
.end((err, res) => {
res.body.should.be.an('object');
Expand All @@ -242,12 +235,8 @@ describe('Users Controllers', () => {
chai.request(app)
.post('/api/users/password/reset')
.send({
tokens: {
reset: wrongToken,
},
user: {
password: 'newPassword',
}
resetToken: wrongToken,
password: 'newPassword'
})
.end((err, res) => {
res.body.should.be.an('object');
Expand All @@ -260,12 +249,8 @@ describe('Users Controllers', () => {
chai.request(app)
.post('/api/users/password/reset')
.send({
tokens: {
reset: token,
},
user: {
password: '',
},
resetToken: token,
password: ''
})
.end((err, res) => {
res.body.should.be.an('object');
Expand All @@ -278,12 +263,8 @@ describe('Users Controllers', () => {
chai.request(app)
.post('/api/users/password/reset')
.send({
tokens: {
reset: token,
},
user: {
password: 'pass',
},
resetToken: token,
password: 'pass'
})
.end((err, res) => {
res.body.should.be.an('object');
Expand Down
23 changes: 0 additions & 23 deletions server/tests/controllers/users_profile.js
Original file line number Diff line number Diff line change
Expand Up @@ -125,17 +125,6 @@ describe('Users Controllers', () => {
done();
});
});
it('should prevent user from updating other users profiles', (done) => {
const unauthorizedUserToken = `Bearer ${TokenHelper.generateToken({ id: 10 })}`;
chai.request(app)
.put('/api/users/1')
.set('Authorization', unauthorizedUserToken)
.send(updateContent)
.end((error, res) => {
expect(res).to.have.status(401);
done();
});
});
it('should return error for user that does not exist', (done) => {
const unexistingUserToken = `Bearer ${TokenHelper.generateToken({ id: 10 })}`;
chai.request(app)
Expand All @@ -149,18 +138,6 @@ describe('Users Controllers', () => {
done();
});
});
it('should return error for invalid ID', (done) => {
chai.request(app)
.put('/api/users/adgb')
.set('Authorization', token)
.send(updateContent)
.end((error, res) => {
expect(res).to.have.status(400);
res.body.error.message.should.eql('Your request ID is invalid');
expect(res.body).to.be.an('object');
done();
});
});
it('should successfully update user profile with the correct input', (done) => {
chai.request(app)
.put('/api/users/1')
Expand Down

0 comments on commit 4a13e12

Please sign in to comment.