authController.js 2.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
  1. const config = require('../config.js')
  2. const db = require('knex')(config.database)
  3. const bcrypt = require('bcrypt')
  4. const saltRounds = 10
  5. const randomstring = require('randomstring')
  6. let authController = {}
  7. authController.verify = function(req, res, next){
  8. let username = req.body.username
  9. let password = req.body.password
  10. if(username === undefined) return res.json({ success: false, description: 'No username provided' })
  11. if(password === undefined) return res.json({ success: false, description: 'No password provided' })
  12. db.table('users').where('username', username).then((user) => {
  13. if(user.length === 0) return res.json({ success: false, description: 'Username doesn\'t exist' })
  14. bcrypt.compare(password, user[0].password, function(err, result) {
  15. if(result === false) return res.json({ success: false, description: 'Wrong password' })
  16. return res.json({ success: true, token: user[0].token })
  17. })
  18. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  19. }
  20. authController.register = function(req, res, next){
  21. if(config.enableUserAccounts === false)
  22. return res.json({ success: false, description: 'Register is disabled at the moment' })
  23. let username = req.body.user
  24. let password = req.body.password
  25. if(username === undefined) return res.json({ success: false, description: 'No username provided' })
  26. if(password === undefined) return res.json({ success: false, description: 'No password provided' })
  27. if(username.length < 6 || username.length > 32)
  28. return res.json({ success: false, description: 'Username must have 6-32 characters' })
  29. if(password.length < 6 || password.length > 64)
  30. return res.json({ success: false, description: 'Password must have 6-64 characters' })
  31. db.table('users').where('username', username).then((user) => {
  32. if(user.length !== 0) return res.json({ success: false, description: 'Username already exists' })
  33. bcrypt.hash(password, saltRounds, function(err, hash) {
  34. if(err) return res.json({ success: false, description: 'Error generating password hash (╯°□°)╯︵ ┻━┻' })
  35. let token = randomstring.generate(64)
  36. db.table('users').insert({
  37. username: username,
  38. password: hash,
  39. token: token
  40. }).then(() => {
  41. return res.json({ success: true, token: token})
  42. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  43. })
  44. }).catch(function(error) { console.log(error); res.json({success: false, description: 'error'}) })
  45. }
  46. module.exports = authController