Skip to content

Commit

Permalink
feat(API): add Article CRUD features
Browse files Browse the repository at this point in the history
- change SECRET to JWT_KEY in email verification

[#159987711]
  • Loading branch information
GodswillOnuoha committed Sep 7, 2018
2 parents 8c5ed79 + 76f0028 commit 099782e
Show file tree
Hide file tree
Showing 12 changed files with 75 additions and 53 deletions.
2 changes: 1 addition & 1 deletion .env.sample
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ PROD_DB_DIALECT=postgres
USER_PASSWORD=
ADMIN_PASSWORD=

SECRET=
JWT_VAL=

FACEBOOK_APP_ID=
FACEBOOK_APP_SECRET=
Expand Down
2 changes: 1 addition & 1 deletion server/config/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
module.exports = {
secret:
process.env.NODE_ENV === 'production' ? process.env.SECRET : 'secret'
process.env.NODE_ENV === 'production' ? process.env.JWT_KEY : 'secret'
};
2 changes: 1 addition & 1 deletion server/controllers/emailVerificationController.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import emailTemplate from '../utils/services/emailTemplate';

dotenv.config();

const secret = process.env.SECRET_KEY;
const secret = process.env.JWT_KEY;
const baseURL = process.env.BASE_URL;

/**
Expand Down
2 changes: 1 addition & 1 deletion server/controllers/socialAuth.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
import jwt from 'jsonwebtoken';
import { User } from '../models';

const secretKey = process.env.SECRET;
const secretKey = process.env.JWT_KEY;


/**
Expand Down
66 changes: 38 additions & 28 deletions server/controllers/userFollows.js
Original file line number Diff line number Diff line change
Expand Up @@ -8,22 +8,22 @@ const { UserFollow, User } = db;
*/
class FollowsController {
/**
* @static
* @param {reuest} req
* @param {response} res
* @param {response} next
* @param {object} req
* @param {object} res
* @param {object} next
* @return {json} res
* @description follows a given user .
*/
static follow(req, res, next) {
const { email } = req.body;
const { username } = req.body;

User.findOne({
where: { email }
where: { username }
}).then((user) => {
// check user exists
if (!user) {
return res.status(404).json({
status: 'error',
errors: {
message: 'User you are trying to follow is missing',
}
Expand All @@ -40,15 +40,15 @@ class FollowsController {
// if created
if (created) {
return res.status(201).json({
success: {
message: `now following ${email}`
}
status: 'success',
message: `now following ${username}`
});
}
// already exists
return res.status(400).json({
status: 'error',
errors: {
message: 'you are already following user'
message: 'you are already following this user'
}
});
})
Expand All @@ -58,9 +58,9 @@ class FollowsController {
}

/**
* @static
* @param {reuest} req
* @param {response} res
* @param {object} req
* @param {object} res
* @param {object} next
* @return {json} res
* @description gets all users following current user.
*/
Expand All @@ -69,22 +69,26 @@ class FollowsController {
include: [{
model: User,
as: 'following',
attributes: ['email']
attributes: { exclude: ['email', 'emailVerified', 'role', 'hash', 'createdAt', 'updatedAt'] }
},
{
model: User,
as: 'followers',
attributes: ['email']
attributes: { exclude: ['email', 'emailVerified', 'role', 'hash', 'createdAt', 'updatedAt'] }
}],
}).then((users) => {
res.status(200).json({ followers: users.followers });
res.status(200).json({
status: 'success',
message: 'successful',
followers: users.followers
});
});
}

/**
* @static
* @param {reuest} req
* @param {response} res
* @param {object} req
* @param {object} res
* @param {object} next
* @return {json} res
* @description return users current user is following .
*/
Expand All @@ -93,15 +97,19 @@ class FollowsController {
include: [{
model: User,
as: 'following',
attributes: ['email']
attributes: { exclude: ['email', 'emailVerified', 'role', 'hash', 'createdAt', 'updatedAt'] }
},
{
model: User,
as: 'followers',
attributes: ['email']
attributes: { exclude: ['email', 'emailVerified', 'role', 'hash', 'createdAt', 'updatedAt'] }
}],
}).then((users) => {
res.status(200).json({ following: users.following });
res.status(200).json({
status: 'success',
message: 'successful',
following: users.following
});
});
}

Expand All @@ -114,16 +122,16 @@ class FollowsController {
* @description return users current user is following .
*/
static unfollow(req, res, next) {
const { email } = req.body;
const { username } = req.body;

User.findOne({
where: { email }
where: { username }
}).then((user) => {
// check user exists
if (!user) {
return res.status(404).json({
errors: {
message: 'User you are not following this user',
message: 'You are not following this user',
}
});
}
Expand All @@ -135,15 +143,17 @@ class FollowsController {
where: { followerId, userId }
}).then((userFollow) => {
if (userFollow == null) {
return res.json({
return res.status(404).json({
status: 'error',
errors: {
error: { message: `you are not following ${email}` }
message: `you are not following ${username}`,
}
});
}
userFollow.destroy()
.then(() => res.status(200).json({
message: 'article successfully deleted',
status: 'success',
message: 'unfllow successful',
}))
.catch(next);
})
Expand Down
4 changes: 2 additions & 2 deletions server/controllers/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -260,7 +260,7 @@ class UsersController {
message: 'Please provide a new password.',
});
}
jwt.verify(reset, process.env.SECRET, (error, user) => {
jwt.verify(reset, process.env.JWT_KEY, (error, user) => {
if (error) {
return res.status(400).json({
status: 'error',
Expand Down Expand Up @@ -325,7 +325,7 @@ class UsersController {
});
}

const token = jwt.sign({ email }, process.env.SECRET, { expiresIn: '2h' });
const token = jwt.sign({ email }, process.env.JWT_KEY, { expiresIn: '2h' });
const resetLink = `${reset}/${token}`;

const msg = `
Expand Down
6 changes: 3 additions & 3 deletions server/tests/controllers/emailVerification.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ describe('Verify User\'s email address after signup', () => {


it('Confirms user\'s email address', (done) => {
const token = jwt.sign({ email: user1Email }, process.env.SECRET_KEY || 'secret');
const token = jwt.sign({ email: user1Email }, process.env.JWT_KEY || 'secret');
chai.request(app)
.get(`/api/users/confirmation/${token}`)
.end((err, res) => {
Expand All @@ -62,7 +62,7 @@ describe('Verify User\'s email address after signup', () => {
});

it('Returns an error if user does not exitst in the database', (done) => {
const token = jwt.sign({ id: 10 }, process.env.SECRET_KEY || 'secret');
const token = jwt.sign({ id: 10 }, process.env.JWT_KEY || 'secret');
chai.request(app)
.get(`/api/users/confirmation/${token}`)
.end((err, res) => {
Expand All @@ -74,7 +74,7 @@ describe('Verify User\'s email address after signup', () => {
});

it('Returns an error if user has been verified', (done) => {
const token = jwt.sign({ email: user1Email }, process.env.SECRET_KEY || 'secret');
const token = jwt.sign({ email: user1Email }, process.env.JWT_KEY || 'secret');
chai.request(app)
.get(`/api/users/confirmation/${token}`)
.end((err, res) => {
Expand Down
1 change: 1 addition & 0 deletions server/tests/controllers/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,4 @@ import './users';
import './users_profile';
import './articles';
import './userFollows';
import './emailVerification.test';
35 changes: 23 additions & 12 deletions server/tests/controllers/userFollows.js
Original file line number Diff line number Diff line change
Expand Up @@ -11,17 +11,19 @@ chai.use(chaiHttp);
// user expected to have been created in seeds
const author1Login = {
email: 'author1@mail.com',
username: 'randomAuthor1',
password: process.env.AUTHOR_PASSWORD
};
const author2Login = {
email: 'su@mail.com',
username: 'randomUser',
password: process.env.USER_PASSWORD
};

let token = '';
let token2 = '';

describe('UserFollow controller', () => {
describe('Follow user controller', () => {
// get token to use for article route testing
it('', (done) => {
chai.request(server).post('/api/users/login').set('Accept', 'application/json').send(author1Login)
Expand All @@ -41,17 +43,17 @@ describe('UserFollow controller', () => {
});
});

describe('follow()', () => {
describe('followUser', () => {
it('should follow a given user', (done) => {
chai.request(server)
.post('/api/users/follow')
.set('Accept', 'application/json')
.set('Authorization', `Bearer ${token}`)
.set('Content-Type', 'application/json')
.send({ email: author2Login.email })
.send({ username: author2Login.username })
.end((err, res) => {
res.should.have.status(201);
res.body.should.have.property('success');
res.body.status.should.equal('success');
done();
});
});
Expand All @@ -62,9 +64,11 @@ describe('UserFollow controller', () => {
.set('Accept', 'application/json')
.set('Authorization', `Bearer ${token}`)
.set('Content-Type', 'application/json')
.send({ email: author2Login.email })
.send({ username: author2Login.username })
.end((err, res) => {
res.should.have.status(400);
res.body.status.should.equal('error');
res.body.errors.message.should.equal('you are already following this user');
done();
});
});
Expand All @@ -75,27 +79,31 @@ describe('UserFollow controller', () => {
.set('Accept', 'application/json')
.set('Authorization', `Bearer ${token}`)
.set('Content-Type', 'application/json')
.send({ email: 'somethin@gwrong.email' })
.send({ username: 'someWrongUsername' })
.end((err, res) => {
res.should.have.status(404);
res.body.status.should.equal('error');
res.body.errors.message.should.equal('User you are trying to follow is missing');
done();
});
});
});

describe('getFollowers()', () => {
describe('getFollowers', () => {
it('should return all users following the current user', (done) => {
chai.request(server)
.get('/api/users/follow/followers')
.set('Authorization', `Bearer ${token}`)
.end((err, res) => {
res.should.have.status(200);
res.body.status.should.equal('success');
res.body.message.should.equal('successful');
done();
});
});
});

describe('getFollowings()', () => {
describe('getFollowings', () => {
it('should return all users that the current user is following', (done) => {
chai.request(server)
.get('/api/users/follow/followings')
Expand All @@ -107,16 +115,17 @@ describe('UserFollow controller', () => {
});
});

describe('unfollow()', () => {
describe('unfollowUser', () => {
it('should remove current user from following a given user', (done) => {
chai.request(server)
.delete('/api/users/follow')
.set('Accept', 'application/json')
.set('Authorization', `Bearer ${token}`)
.set('Content-Type', 'application/json')
.send({ email: author2Login.email })
.send({ username: author2Login.username })
.end((err, res) => {
res.should.have.status(200);
res.body.message.should.equal('unfllow successful');
done();
});
});
Expand All @@ -127,9 +136,11 @@ describe('UserFollow controller', () => {
.set('Accept', 'application/json')
.set('Authorization', `Bearer ${token2}`)
.set('Content-Type', 'application/json')
.send({ email: author2Login.email })
.send({ username: author2Login.username })
.end((err, res) => {
res.should.have.status(200);
res.should.have.status(404);
res.body.status.should.equal('error');
res.body.errors.message.should.equal(`you are not following ${author2Login.username}`);
done();
});
});
Expand Down
2 changes: 1 addition & 1 deletion server/tests/controllers/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -50,7 +50,7 @@ const correctDetails = { email: 'emekag@gmail.com', password: 'emeka' };
const incorrectDetails = { email: 'emekag@gmail.com', password: 'wrongpassword' };
const emptyEmailField = { email: '', password: 'emeka' };
const emptyPasswordField = { email: 'emekag@gmail.com', password: '' };
const token = jwt.sign({ user: { email: user.email }, links: { reset: 'https://thor-ah.com' } }, process.env.SECRET, { expiresIn: '2h' });
const token = jwt.sign({ user: { email: user.email }, links: { reset: 'https://thor-ah.com' } }, process.env.JWT_KEY, { expiresIn: '2h' });
const wrongToken = 'eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJlbWFpbCI6ImlhbXVjaGVqdWRlQGdtYWlsLmNvbSIsImlhdCI6MTUzNTczMTgyNSwiZXhwIjoxNTM1NzM5MDI1fQ.BBwKljkzNFTKVuCE4VRHTv8GF4Q6uuA6_KZ8MMLdvR4';

describe('Users Controllers', () => {
Expand Down
2 changes: 1 addition & 1 deletion server/tests/utils/token.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@ describe('token utility', () => {
});

it('should take a payload and return a jwt token', () => {
const verifiedToken = jwt.verify(generatedToken, process.env.SECRET);
const verifiedToken = jwt.verify(generatedToken, process.env.JWT_KEY);
const { exp, iat, ...actual } = verifiedToken;
expect(actual).to.deep.equal(payload);
});
Expand Down
Loading

0 comments on commit 099782e

Please sign in to comment.