Skip to content

Commit

Permalink
fix(users): disallow setting date_of_birth from a future
Browse files Browse the repository at this point in the history
  • Loading branch information
serge1peshcoff committed May 11, 2020
1 parent 70a6f2a commit f6b3e9a
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 1 deletion.
10 changes: 9 additions & 1 deletion models/User.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
const bcrypt = require('bcrypt');
const moment = require('moment');

const { Sequelize, sequelize } = require('../lib/sequelize');
const config = require('../config');
Expand Down Expand Up @@ -82,7 +83,14 @@ const User = sequelize.define('user', {
},
date_of_birth: {
type: Sequelize.DATEONLY,
allowNull: true
allowNull: true,
validate: {
isPast(value) {
if (moment().isSameOrBefore(value)) {
throw new Error('Birthday should be in the past.');
}
}
}
},
gender: {
type: Sequelize.STRING,
Expand Down
18 changes: 18 additions & 0 deletions test/unit/users.test.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,5 @@
const moment = require('moment');

const { startServer, stopServer } = require('../../lib/server.js');
const generator = require('../scripts/generator');
const { User } = require('../../models');
Expand Down Expand Up @@ -95,6 +97,22 @@ describe('Users testing', () => {
}
});

test('should fail with date_of_birth in the future', async () => {
try {
const user = generator.generateUser({
date_of_birth: moment().add(1, 'year').toDate()
});
await User.create(user);

expect(1).toEqual(0);
} catch (err) {
expect(err).toHaveProperty('errors');
expect(err.errors.length).toEqual(1);
expect(err.errors[0].type).toEqual('Validation error');
expect(err.errors[0].path).toEqual('date_of_birth');
}
});

test('should normalize fields', async () => {
const data = generator.generateUser({
username: '\t\t\tSERGEY\t ',
Expand Down

0 comments on commit f6b3e9a

Please sign in to comment.