auth-router.js 3.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  1. var express = require('express');
  2. var authControllers = require('./auth-controller');
  3. var auth = require('./index');
  4. var authRouter = express.Router();
  5. var r = require('../db');
  6. var bcrypt = require('bcryptjs');
  7. // GitHub
  8. authRouter.use('/login/callback/github', auth.authenticate('github'), function (req, res) {
  9. res.redirect('/');
  10. });
  11. authRouter.get('/login/github', auth.authenticate('github', { scope: [ 'user:email' ] }));
  12. // Local
  13. authRouter.get('/login', auth.authenticate('local', {successRedirect: '/auth/user', failureRedirect: '/login'}), function(req, res) {
  14. // If this function gets called, authentication was successful.
  15. // `req.user` contains the authenticated user.
  16. res.redirect("/auth/user");
  17. });
  18. // Local
  19. authRouter.get('/register', function(req, res) {
  20. req.checkQuery('email', 'Invalid email').isEmail();
  21. req.checkQuery('username', 'Invalid getparam').notEmpty();
  22. req.checkQuery('password', 'Invalid getparam').notEmpty();
  23. var query = req.query;
  24. var errors = req.validationErrors();
  25. if (errors) {
  26. res.send('There have been validation errors: ', 400);
  27. return;
  28. } else {
  29. //TODO Check if username/email already exists
  30. r.table("users").getAll(query.username.toLowerCase(), {index: "usernameL"}).isEmpty().run(r.conn, function(err, result) {
  31. if (err) throw err;
  32. if (result) {
  33. r.table("users").getAll(query.email.toLowerCase(), {index: "email"}).isEmpty().run(r.conn, function(err, result) {
  34. if (err) throw err;
  35. if (result) {
  36. //TODO Hash password
  37. var hash;
  38. bcrypt.genSalt(10, function (err, salt) {
  39. if (err) {
  40. //TODO Throw error
  41. } else {
  42. bcrypt.hash(query.password, salt, function (err, hash) {
  43. if (err) {
  44. //TODO Throw error
  45. } else {
  46. var email = query.email.toLowerCase();
  47. var usernameL = query.username.toLowerCase();
  48. r.table('users')
  49. .insert({
  50. username: query.username,
  51. usernameL: usernameL,
  52. email: email,
  53. type: 'local',
  54. password: hash
  55. })
  56. .run(r.conn)
  57. .then(function (response) {
  58. return r.table('users')
  59. .get(response.generated_keys[0])
  60. .run(r.conn);
  61. })
  62. .then(function (newUser) {
  63. //TODO Log in
  64. });
  65. }
  66. });
  67. }
  68. });
  69. } else {
  70. //TODO Throw error
  71. }
  72. });
  73. } else {
  74. //TODO Throw error
  75. }
  76. });
  77. }
  78. });
  79. // All
  80. authRouter.use('/user', authControllers.getUser);
  81. authRouter.use('/logout', authControllers.logout);
  82. module.exports = authRouter;