Advertisement
Guest User

Untitled

a guest
Jun 4th, 2017
143
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. 'use strict';
  2. const mysql = require('mysql');
  3.  
  4. const Q = {
  5.   'GET_USER': 'SELECT username, password FROM users WHERE username = ?',
  6.   'ADD_USER': 'INSERT INTO users (username, password) VALUES (?, ?)'
  7. };
  8.  
  9. const E = {
  10.   'BAD_ADD': 'An error occured when adding your credentials to the database.',
  11.   'BAD_VALIDATION': 'An error occured when validating your credentials.',
  12.   'WRONG_CREDENTIALS': 'Your username or password was wrong.'
  13. };
  14.  
  15. const pool = mysql.createPool({
  16.   connectionLimit: 20,
  17.   host: 'localhost',
  18.   user: 'developer',
  19.   password: 'developer',
  20.   database: 'chat-app'
  21. });
  22.  
  23. function query(query, args) {
  24.   return new Promise((resolve, reject) => {
  25.     pool.query(query, args, (err, res) => {
  26.       if (err) return reject(err);
  27.       return resolve(res);
  28.     });
  29.   });
  30. }
  31.  
  32. exports.addUser = (user, cb) => {
  33.   query(Q.ADD_USER, [user.username, user.password])
  34.   .then(resultSet => cb(null, resultSet))
  35.   .catch(error => cb(E.BAD_ADD, null));
  36. }
  37.  
  38. exports.validateUser = (user, cb) => {
  39.   query(Q.GET_USER, [user.username])
  40.   .then(resultSet => {
  41.     if (user.password === resultSet[0].password) return cb(null, true);
  42.     return cb(E.WRONG_CREDENTIALS, false);
  43.   })
  44.   .catch(error => cb(E.BAD_VALIDATION, null));
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement