Advertisement
rhuntington

users.js

Apr 11th, 2019
132
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. const express = require('express');
  2. const userRoute = express.Router();
  3. const cors = require('cors');
  4. const bodyParser = require('body-parser');
  5. const jwt = require('jsonwebtoken');
  6. const saltRounds = 15;
  7. const bcrypt = require('bcrypt');
  8. const users = require('../models').users;
  9. userRoute.use(function timeLog (req, res, next) {
  10.     console.log('Time: ', Date.now());
  11.     next();
  12. });
  13.  
  14. userRoute.use(cors());
  15. userRoute.use(bodyParser.json());
  16. userRoute.use(bodyParser.urlencoded({ extended: true}));
  17.  
  18. userRoute.post('/register', (req, res) => {
  19.     users.findAll({
  20.         attributes: ['username'],
  21.         where: {
  22.             username: req.body.username
  23.         }
  24.     }).then((data) => {
  25.         if(data == '') {
  26.             bcrypt.hash(req.body.password, saltRounds, (err, hash) => {
  27.                 if(err != undefined) {
  28.                     console.log(err);
  29.                     res.status(400).send("There was an issue while creating the user. Please see try again or consult with a system administrator");
  30.                 } else {
  31.                     users.create({
  32.                         username: req.body.username,
  33.                         password: hash
  34.                     }).then((err, data) => {
  35.                         if(data != '') {
  36.                             res.send("User successfully created");
  37.                         } else {
  38.                             console.log(err);
  39.                             res.status(400).send("There was an issue while creating your username. Please try again.");
  40.                         }
  41.                     })
  42.                 }
  43.             });
  44.         } else {
  45.             console.log("Username already exists");
  46.             res.status(400).send("Username already exists. Please try again.");
  47.         }
  48.     });
  49. });
  50.  
  51. module.exports = userRoute;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement