Skip to content

Commit

Permalink
feature(connect signin form to database):
Browse files Browse the repository at this point in the history
connect signin form to database
[Starts #165422358]
  • Loading branch information
Cavdy committed Apr 17, 2019
1 parent a6bb29a commit 9f0b5c2
Show file tree
Hide file tree
Showing 6 changed files with 168 additions and 143 deletions.
6 changes: 3 additions & 3 deletions server/v1/config/user.sql
Original file line number Diff line number Diff line change
Expand Up @@ -14,11 +14,11 @@ CREATE TABLE users (
-- select all from users table
SELECT * FROM "users" LIMIT 10

-- select email fro users
SELECT email FROM users WHERE email=$1, ['email']

-- insert into users table
INSERT into users values($1), ['value']

-- update into users
update firstname

-- delete from users table
DELETE FROM users;
26 changes: 7 additions & 19 deletions server/v1/controllers/login.js
Original file line number Diff line number Diff line change
@@ -1,31 +1,19 @@
import jwt from 'jsonwebtoken';
import debug from 'debug';
import dotenv from 'dotenv';
import LoginService from '../services/login';

dotenv.config();

const LoginController = {
loginUser(req, res) {
async loginUser(req, res) {
const userData = req.body;
const loggedUser = LoginService.loginUser(userData);

return jwt.sign({ loggedUser }, process.env.JWTSECRETKEY, (err, token) => {
if (err) { debug('jwterror')(err); }
if (loggedUser[0] === 'Invalid format' || loggedUser[0] === 'incorrect credentials') {
res.json({
status: 'error',
data: 'incorrect data',
});
} else {
res.json({
status: 'success',
data: {
loggedUser,
token,
},
}).status(201);
}
jwt.sign({ userData }, process.env.JWTSECRETKEY, async (err, token) => {
const loggedUser = await LoginService.loginUser(userData, token);
res.json({
status: 'success',
data: loggedUser,
}).status(201);
});
},
};
Expand Down
2 changes: 1 addition & 1 deletion server/v1/model/users.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,8 +4,8 @@ export default class User {
this.email = null;
this.firstName = null;
this.lastName = null;
this.password = null;
this.type = null; // client or staff
this.isAdmin = null; // must be a staff user account
this.token = null;
}
}
54 changes: 35 additions & 19 deletions server/v1/services/login.js
Original file line number Diff line number Diff line change
@@ -1,33 +1,49 @@
import usersData from '../../dummyJson/users';

const { users } = usersData;
import bcrypt from 'bcryptjs';
import dbConnection from '../config/database';
import UserModel from '../model/users';

const LoginService = {
loginUser(userData) {
async loginUser(userData, token) {
const emailRegex = /^([a-zA-Z0-9_\-\.]+)@([a-zA-Z0-9_\-\.]+)\.([a-zA-Z]{2,10})$/;
const passwordRegex = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/;
let returnValue = [];
const returnValue = [];

// Check if email and password is valid
if (emailRegex.test(userData.email) && passwordRegex.test(userData.password)) {
let checkDetails = false;

// check if account exist
// eslint-disable-next-line no-plusplus
for (let i = 0; i <= users.length - 1; i++) {
if (users[i].email === userData.email && users[i].password === userData.password) {
returnValue = users[i];
checkDetails = true;
// check if email, if it exist get the user data
const emailresponse = await dbConnection.dbConnect('SELECT * FROM users WHERE email=$1', [userData.email]);
if (emailresponse.rows.length > 0) {
// Load hash from your password DB.
const passwordUnhash = bcrypt
.compareSync(userData.password, emailresponse.rows[0].password);
if (passwordUnhash) {
// return users details
const user = new UserModel();
user.id = emailresponse.rows[0].id;
user.firstName = emailresponse.rows[0].firstname;
user.lastName = emailresponse.rows[0].lastname;
user.email = emailresponse.rows[0].email;
user.type = emailresponse.rows[0].type;
user.isAdmin = emailresponse.rows[0].isadmin;
user.token = token;
returnValue.push(user);
} else {
// else echo incorrect password
returnValue.push('incorrect password');
}
} else {
returnValue.push('email does not exist');
}
}

// gives output
if (!checkDetails) {
returnValue.push('incorrect credentials');
const checkError = (regex, data, msg) => {
if (!regex.test(data)) {
returnValue.push(msg);
}
} else {
returnValue.push('Invalid format');
}
};

checkError(emailRegex, userData.email, 'invalid email address');
checkError(passwordRegex, userData.password, 'Password should contain atleast 8 characters, 1 uppercase letter, 1 lowercase letter, 1 number and 1 symbol or character');

return returnValue;
},
Expand Down
182 changes: 98 additions & 84 deletions server/v1/test/signin.js
Original file line number Diff line number Diff line change
@@ -1,92 +1,106 @@
// /* eslint-disable no-undef */
// import chaiHttp from 'chai-http';
// import chai, { expect } from 'chai';
/* eslint-disable no-undef */
import chaiHttp from 'chai-http';
import chai, { expect } from 'chai';

// import app from '../app';
import app from '../app';

// chai.use(chaiHttp);
chai.use(chaiHttp);

// describe('Testing User Controller', () => {
// describe('Testing signin controller', () => {
// const signinUrl = '/api/auth/signin';
// it(
// 'should login when all the parameters are given',
// (done) => {
// chai.request(app)
// .post(signinUrl)
// .send({
// email: 'banka2@banka.com',
// password: 'passworD2@',
// })
describe('Testing User Controller', () => {
describe('Testing signin controller', () => {
const signinUrl = '/api/auth/signin';
it(
'should login when all the parameters are given',
async () => {
const response = await chai.request(app)
.post(signinUrl)
.send({
email: 'banka872@banka4.com',
password: 'passworD4@',
});
expect(response.body.data[0]).to.be.an('object');
expect(response.body.status).to.equal('success');
expect(response.body.data[0]).to.have.property('id');
expect(response.body.data[0]).to.have.property('email');
expect(response.body.data[0]).to.have.property('firstName');
expect(response.body.data[0]).to.have.property('lastName');
expect(response.body.data[0]).to.have.property('type');
expect(response.body.data[0]).to.have.property('isAdmin');
expect(response.body.data[0]).to.have.property('token');
},
);

// .end((error, response) => {
// expect(response.body).to.be.an('object');
// expect(response).to.have.status(200);
// expect(response.body.data).to.be.a('object');
// expect(response.body.data.loggedUser).to.have.property('id');
// expect(response.body.data.loggedUser).to.have.property('email');
// expect(response.body.data).to.have.property('token');
// done();
// });
// },
// );
it(
'should not signin a user when the email is missing',
async () => {
const response = await chai.request(app)
.post(signinUrl)
.send({
password: 'passworD4@',
});
expect(response.body).to.be.an('object');
expect(response.body.status).to.equal('success');
expect(response.body.data[0]).to.equal('invalid email address');
},
);

// it('should not signin a user when the email is missing', (done) => {
// chai.request(app)
// .post(signinUrl)
// .send({
// password: 'passworD4@',
// })
// .end((error, response) => {
// expect(response.body).to.be.an('object');
// expect(response.body.status).to.equal('error');
// expect(response.body.data).to.equal('incorrect data');
// done();
// });
// });
it(
'should not signin a user when the email does not exist',
async () => {
const response = await chai.request(app)
.post(signinUrl)
.send({
email: 'banka876@banka4.com',
password: 'passworD4@',
});
expect(response.body).to.be.an('object');
expect(response.body.status).to.equal('success');
expect(response.body.data[0]).to.equal('email does not exist');
},
);

// it('should not signin a user when the email does not exist', (done) => {
// chai.request(app)
// .post(signinUrl)
// .send({
// email: 'banka5@banka.com',
// password: 'passworD4@',
// })
// .end((error, response) => {
// expect(response.body).to.be.an('object');
// expect(response.body.status).to.equal('error');
// expect(response.body.data).to.equal('incorrect data');
// done();
// });
// });
it(
'should not login a user when the password is missing',
async () => {
const response = await chai.request(app)
.post(signinUrl)
.send({
email: 'banka872@banka4.com',
});
expect(response.body).to.be.an('object');
expect(response.body.status).to.equal('success');
expect(response.body.data[0]).to.equal('Password should contain atleast 8 characters, 1 uppercase letter, 1 lowercase letter, 1 number and 1 symbol or character');
},
);

// it('should not register a user when the password is missing', (done) => {
// chai.request(app)
// .post(signinUrl)
// .send({
// email: 'banka4@banka.com',
// })
// .end((error, response) => {
// expect(response.body).to.be.an('object');
// expect(response.body.status).to.equal('error');
// expect(response.body.data).to.equal('incorrect data');
// done();
// });
// });
it(
'should not login a user when the password is incorrect',
async () => {
const response = await chai.request(app)
.post(signinUrl)
.send({
email: 'banka872@banka4.com',
password: 'passworD4@@',
});
expect(response.body).to.be.an('object');
expect(response.body.status).to.equal('success');
expect(response.body.data[0]).to.equal('incorrect password');
},
);

// it('should not register a user when the password do not meet requirement', (done) => {
// chai.request(app)
// .post(signinUrl)
// .send({
// email: 'banka2@banka.com',
// password: 'passworD4',
// })
// .end((error, response) => {
// expect(response.body).to.be.an('object');
// expect(response.body.status).to.equal('error');
// expect(response.body.data).to.equal('incorrect data');
// done();
// });
// });
// });
// });
it(
'should not register a user when the password do not meet requirement',
async () => {
const response = await chai.request(app)
.post(signinUrl)
.send({
email: 'banka872@banka4.com',
password: 'passworD4',
});
expect(response.body).to.be.an('object');
expect(response.body.status).to.equal('success');
expect(response.body.data[0]).to.equal('Password should contain atleast 8 characters, 1 uppercase letter, 1 lowercase letter, 1 number and 1 symbol or character');
},
);
});
});
41 changes: 24 additions & 17 deletions server/v1/test/signup.js
Original file line number Diff line number Diff line change
Expand Up @@ -132,29 +132,36 @@ describe('Testing User Controller', () => {
// it(
// 'should not create staffs if not admin',
// async () => {
// await chai.request(app)
// .post(signupUrl)
// .send({
// firstName: 'cavdy',
// lastName: 'isaiah',
// email: 'bankaadmin@banka.com',
// password: 'passworadmiN4@',
// isAdmin: true,
// });
// const signinUrl = '/api/auth/signin';
// const response = await chai.request(app)
// .post(signinUrl)
// .send({
// email: 'banka872@banka4.com',
// email: 'bankaadmin@banka.com',
// password: 'passworadmiN4@',
// });
// console.log(response.body);
// const { token } = response.body.data[0];
// const res = await chai.request(app)
// .post(signupStaffUrl)
// .set('Authorization', `Bearer ${token}`)
// .send({
// firstName: 'cavdy',
// lastName: 'isaiah',
// email: 'banka4@banka.com',
// password: 'passworD4@',
// });
// console.log(response.body.data);
// // const { token } = response.body.data;
// // chai.request(app)
// // .post(signupStaffUrl)
// // .set('Authorization', `Bearer ${token}`)
// // .send({
// // firstName: 'cavdy',
// // lastName: 'isaiah',
// // email: 'banka4@banka.com',
// // password: 'passworD4@',
// // })
// // .end((err, res) => {
// // expect(res.body).to.be.an('object');
// // expect(res.body.status).to.equal('success');
// // expect(res.body.data).to.equal('You must be an admin to create staffs');
// // });
// expect(res.body).to.be.an('object');
// expect(res.body.status).to.equal('success');
// expect(res.body.data).to.equal('You must be an admin to create staffs');
// },
// );

Expand Down

0 comments on commit 9f0b5c2

Please sign in to comment.