Skip to content

Commit

Permalink
Merge f81eab0 into 8150687
Browse files Browse the repository at this point in the history
  • Loading branch information
rwajon authored May 6, 2019
2 parents 8150687 + f81eab0 commit 779c55a
Show file tree
Hide file tree
Showing 34 changed files with 522 additions and 64 deletions.
16 changes: 8 additions & 8 deletions .nycrc
Original file line number Diff line number Diff line change
@@ -1,10 +1,10 @@
{
"reporter": [
"lcov",
"text"
],
"exclude": [
"src/migartions",
"src/helpers"
]
"reporter": [
"lcov",
"text"
],
"exclude": [
"src/migrations",
"src/tests"
]
}
2 changes: 1 addition & 1 deletion .sequelizerc
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ require("@babel/register");
const path = require('path');

module.exports = {
"config": path.resolve('./src/config', 'db-config.js'),
"config": path.resolve('./src/config', 'dbConfig.js'),
"models-path": path.resolve('./src/models'),
"migrations-path": path.resolve('./src/migrations')
};
11 changes: 9 additions & 2 deletions .travis.yml
Original file line number Diff line number Diff line change
@@ -1,13 +1,20 @@
env:
global:
- CC_TEST_REPORTER_ID=d570e2625aaffa20e7828eaddfbec748c525e866b6d413472bc26e188cb2bc6a
- SECRET_KEY=12345
- NODE_ENV=test
- CC_TEST_REPORTER_ID=d570e2625aaffa20e7828eaddfbec748c525e866b6d413472bc26e188cb2bc6a
- DATABASE_URL_TEST=postgres://postgres@localhost:5432/authorhavens_test
language: node_js
node_js:
- "stable"
cache:
directories:
- "node_modules"
- "node_modules"
services:
- postgresql
before_script:
- psql -c 'CREATE DATABASE authorhavens_test;' -U postgres
- npm i sequelize-cli -g
- curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter
- chmod +x ./cc-test-reporter
- ./cc-test-reporter before-build
Expand Down
44 changes: 44 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 5 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
"description": "A Social platform for the creative at heart",
"main": "src/index.js",
"scripts": {
"test": "NODE_ENV=test nyc mocha --require @babel/register src/tests/index.js",
"test": "NODE_ENV=test npm run db:migrate && NODE_ENV=test nyc mocha --require @babel/register src/tests/index.js",
"cover": "npm test && nyc report --reporter=text-lcov | coveralls",
"coveralls": "cat coverage/lcov.info | coveralls",
"start": "babel-node src/index.js",
Expand All @@ -20,7 +20,10 @@
"@babel/node": "^7.2.2",
"@babel/preset-env": "^7.4.3",
"@babel/register": "^7.4.0",
"@hapi/joi": "^15.0.0",
"D": "^1.0.0",
"body-parser": "^1.18.3",
"chance": "^1.0.18",
"cheke": "^1.0.2",
"cors": "^2.8.4",
"dotenv": "^6.0.0",
Expand Down Expand Up @@ -59,6 +62,7 @@
"mocha-lcov-reporter": "^1.3.0",
"nodemon": "^1.18.11",
"nyc": "^14.0.0",
"rosie": "^2.0.1",
"sinon": "^7.3.2",
"sinon-chai": "^3.3.0"
}
Expand Down
18 changes: 9 additions & 9 deletions src/app.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,20 +9,20 @@ const app = express();

dotenv.config();

app.use(session({
secret: process.env.SECRET_KEY || 'authorshaven',
cookie: { maxAge: 60000 },
resave: true,
saveUninitialized: true,
}));
app.use(
session({
secret: process.env.SECRET_KEY || 'authorshaven',
cookie: { maxAge: 60000 },
resave: true,
saveUninitialized: true
})
);

app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cors());

// api version 1

// catch 404 and forward to error handler
app.use((req, res, next) => {
next(createError(404));
Expand All @@ -38,7 +38,7 @@ app.use((err, req, res, next) => {
res.status(err.status || 500);
res.send({
message: err.message,
error: err.status,
error: err.status
});
next();
});
Expand Down
6 changes: 3 additions & 3 deletions src/config/db-config.js → src/config/dbConfig.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,23 +9,23 @@ const config = {
password: process.env.DB_PASSWORD_DEV,
database: process.env.DB_NAME_DEV,
host: process.env.DB_HOST_DEV,
dialect: 'postgres',
dialect: 'postgres'
},
test: {
use_env_variable: 'DATABASE_URL_TEST',
username: process.env.DB_USER_TEST,
password: process.env.DB_PASSWORD_TEST,
database: process.env.DB_NAME_TEST,
host: process.env.DB_HOST_TEST,
dialect: 'postgres',
dialect: 'postgres'
},
production: {
use_env_variable: 'DATABASE_URL',
username: process.env.DB_USER,
password: process.env.DB_PASSWORD,
database: process.env.DB_NAME,
host: process.env.DB_HOST,
dialect: 'postgres',
dialect: 'postgres'
}
};

Expand Down
File renamed without changes.
11 changes: 11 additions & 0 deletions src/helpers/factory/article.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { Factory } from 'rosie';

export default Factory.define('article')
.sequence('id')
.attr('userId', 1)
.attr('title', 'Going home like a dog')
.attr('description', 'Holla and Holla')
.attr('body', 'More about this the dance of chicken')
.attr('coverUrl', 'placeholer.jpg')
.attr('slug', 'going-home-like-a-dog-2aijv735e7w');
4 changes: 4 additions & 0 deletions src/helpers/factory/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import user from './user';
import article from './article';

export { user, article };
15 changes: 15 additions & 0 deletions src/helpers/factory/user.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
// eslint-disable-next-line import/no-extraneous-dependencies
import { Factory } from 'rosie';
import Chance from 'chance';

const chance = new Chance();

export default Factory.define('user')
.sequence('id')
.attr('firstName', chance.first())
.attr('lastName', chance.last())
.attr('username', chance.word({ length: 5 }))
.attr('email', chance.email({ domain: 'example.com' }))
.attr('password', 'Baaa1234!')
.attr('role', 'admin')
.attr('permissions', ['read', 'write', 'delete', 'edit']);
32 changes: 32 additions & 0 deletions src/helpers/validation/email.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
/**
* @param {string} input
* @param {string} required
* @returns {array} an array of errors or an empty array if no error
*/
export default (input, required = '') => {
if (!input && !required) {
return [];
}

let errors = [];
const re = /[A-Z0-9]+@[A-Z0-9-]+\.[A-Z]{2,4}/gim;
const reUsername = /[\\ ,;:"!#$%&'*+/=?^`{|}~]/g;
const reDomainSLD = /[ \\,;:"!#$%&'*+/=?^`{|}~]/g;
const reDomainTLD = /[\d+ \\,;:"!#$%&'*+-/=?^_`{|}~]/g;

const emailUsername = input.substring(0, input.lastIndexOf('@'));
const emailDomainSLD = input.substring(input.lastIndexOf('@') + 1, input.lastIndexOf('.'));
const emailDomainTLD = input.substring(input.lastIndexOf('.') + 1);

const isEmailUsername = !emailUsername.match(/^[0-9]/) && !reUsername.test(emailUsername);
const isEmailDomainSLD = !emailDomainSLD.match(/^[0-9]/) && !reDomainSLD.test(emailDomainSLD);
const isEmailDomainTLD = !emailDomainTLD.match(/^[0-9]/) && !reDomainTLD.test(emailDomainTLD);

if (re.test(input) && isEmailUsername && isEmailDomainSLD && isEmailDomainTLD) {
return [];
}

errors = [...['Please provide a valid email address']];

return errors;
};
5 changes: 5 additions & 0 deletions src/helpers/validation/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
import isUser from './isUser';
import email from './email';
import password from './password';

export { isUser, email, password };
15 changes: 15 additions & 0 deletions src/helpers/validation/isUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { User } from '../../queries';

/**
* @param {object} input
* @returns {boolean} return true if the user exists or false if not
*/
export default async (input = {}) => {
const findUser = await User.findOne(input);

if (!findUser.errors && Object.keys(findUser).length > 0) {
return true;
}

return false;
};
24 changes: 24 additions & 0 deletions src/helpers/validation/password.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
/**
* @param {string} input
* @param {string} required
* @returns {array} an array of errors or an empty array if no error
*/
export default (input, required = '') => {
const errors = [];

if (!input && !required) {
return [];
}
if (
input.match(/^(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,25}$/)
&& input.match(/[ \\,;:"!#$%&'+-/=?^_`{|}~]/)
) {
return [];
}

errors.push(
'Your password should have a minimum 8 and maximum of 25 characters, it must include at least one upper case letter, one lower case letter, one numeric digit and one special character (*&^!%$@#)'
);

return errors;
};
27 changes: 27 additions & 0 deletions src/middlewares/validateNewUser.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
import * as validate from '../helpers/validation';

export default async (req, res, next) => {
if (Object.keys(req.body).length <= 0) {
return res.status(400).json({ errors: { body: ['body can not be empty'] } });
}

// check errors in email or password
const errors = {
email: [...validate.email(req.body.email, 'required')],
password: [...validate.password(req.body.password, 'required')]
};

const isUser = await validate.isUser({ email: req.body.email });

if (isUser) {
errors.email = [...['sorry, this email is already used']];
}

Object.keys(errors).forEach(error => errors[error].length > 0 || delete errors[error]);

if (Object.keys(errors).length > 0) {
return res.status(400).json({ errors });
}

next();
};
16 changes: 6 additions & 10 deletions src/models/index.js
Original file line number Diff line number Diff line change
@@ -1,24 +1,20 @@
import fs from 'fs';
import path from 'path';
import Sequelize from 'sequelize';
import dbConfig from '../config/db-config';
import dbConfig from '../config/dbConfig';

const basename = path.basename(__filename);
const env = process.env.NODE_ENV || 'development';

const db = {};
let sequelize;
const config = dbConfig[env];

if (config.use_env_variable) {
sequelize = new Sequelize(process.env[config.use_env_variable], config);
} else {
sequelize = new Sequelize(config.database, config.username, config.password, config);
}
const sequelize = config.use_env_variable
? new Sequelize(process.env[config.use_env_variable], config)
: new Sequelize(config.database, config.username, config.password, config);

fs
.readdirSync(__dirname)
.filter(file => (file.indexOf('.') !== 0) && (file !== basename) && (file.slice(-3) === '.js'))
fs.readdirSync(__dirname)
.filter(file => file.indexOf('.') !== 0 && file !== basename && file.slice(-3) === '.js')
.forEach((file) => {
const model = sequelize.import(path.join(__dirname, file));
db[model.name] = model;
Expand Down
4 changes: 4 additions & 0 deletions src/queries/index.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,4 @@
import * as User from './users';

// eslint-disable-next-line import/prefer-default-export
export { User };
Loading

0 comments on commit 779c55a

Please sign in to comment.