Guest User

Untitled

a guest
Feb 6th, 2019
136
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.21 KB | None | 0 0
  1. const express = require('express');
  2. const bodyParser = require('body-parser');
  3. const bcrypt = require('bcrypt-nodejs');
  4. const cors = require('cors');
  5. const knex = require('knex');
  6.  
  7. const db = knex({
  8. client: 'mysql',
  9. connection: {
  10. host : '127.0.0.1',
  11. user : 'root',
  12. password : 'TOcvfan1979',
  13. database : 'facedetectordb'
  14. }
  15. });
  16.  
  17. db.select('*').from('users').then(data => {
  18. console.log(data);
  19. });
  20.  
  21. const app = express();
  22.  
  23. app.use(bodyParser.json());
  24. app.use(cors())
  25.  
  26. app.get('/', (req, res) => {
  27. res.send(database.users);
  28. })
  29.  
  30. app.post('/signin', (req, res) => {
  31. db.select('email', 'hash').from('login')
  32. .where('email', '=', req.body.email)
  33. .then(data => {
  34. const isValid = bcrypt.compareSync(req.body.password, data[0].hash);
  35. if (isValid) {
  36. return db.select('*').from('users')
  37. .where('email', '=', req.body.email)
  38. .then(user => {
  39. res.json(user[0])
  40. })
  41. .catch(err => res.status(400).json('unable to get user'))
  42. } else {
  43. res.status(400).json('wrong credentials')
  44. }
  45. })
  46. .catch(err => res.status(400).json('wrong credentials'))
  47. })
  48.  
  49. app.post('/register', (req, res) => {
  50. const { email, name, password } = req.body;
  51. const hash = bcrypt.hashSync(password);
  52. db.transaction(trx => {
  53. trx.insert({
  54. hash: hash,
  55. email: email
  56. })
  57. .into('login')
  58. .returning('email')
  59. .then(loginEmail => {
  60. return trx('users')
  61. .returning('*')
  62. .insert({
  63. email: email,
  64. name: name,
  65. joined: new Date()
  66. })
  67. .then(user => {
  68. res.json(user[0]);
  69. })
  70. })
  71. .then(trx.commit)
  72. .catch(trx.rollback)
  73. })
  74.  
  75. .catch(err => res.status(400).json('unable to register'))
  76. })
  77.  
  78. app.get('/profile/:id', (req, res) => {
  79. const { id } = req.params;
  80. db.select('*').from('users').where({id})
  81. .then(user => {
  82. if (user.length) {
  83. res.json(user[0])
  84. } else {
  85. res.status(400).json('Not found')
  86. }
  87. })
  88. .catch(err => res.status(400).json('error getting user'))
  89. })
  90.  
  91. app.put('/image', (req, res) => {
  92. const { id } = req.body;
  93. db('users').where('id', '=', id)
  94. .increment('entries', 1)
  95. .returning('entries')
  96. .then(entries => {
  97. res.json(entries[0]);
  98. })
  99. .catch(err => res.status(400).json('unable to get entries'))
  100. })
  101.  
  102. app.listen(3000, () => {
  103. console.log('App is running')
  104. });
Add Comment
Please, Sign In to add comment