app.js 5.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145
  1. 'use strict';
  2. // This file contains all the logic for Express
  3. const express = require('express');
  4. const bodyParser = require('body-parser');
  5. const cors = require('cors');
  6. const config = require('config');
  7. const request = require('request');
  8. const cache = require('./cache');
  9. const db = require('./db');
  10. let utils;
  11. const OAuth2 = require('oauth').OAuth2;
  12. const lib = {
  13. app: null,
  14. server: null,
  15. init: (cb) => {
  16. utils = require('./utils');
  17. let app = lib.app = express();
  18. lib.server = app.listen(80);
  19. app.use(bodyParser.json());
  20. app.use(bodyParser.urlencoded({ extended: true }));
  21. let corsOptions = Object.assign({}, config.get('cors'));
  22. app.use(cors(corsOptions));
  23. app.options('*', cors(corsOptions));
  24. let oauth2 = new OAuth2(
  25. config.get("apis.github.client"),
  26. config.get("apis.github.secret"),
  27. 'https://github.com/',
  28. 'login/oauth/authorize',
  29. 'login/oauth/access_token',
  30. null
  31. );
  32. let redirect_uri = config.get("serverDomain") + "/auth/github/authorize/callback";
  33. app.get('/auth/github/authorize', (req, res) => {
  34. let params = [
  35. `client_id=${config.get("apis.github.client")}`,
  36. `redirect_uri=http://localhost/auth/github/authorize/callback`,
  37. `scope=user:email`
  38. ].join('&');
  39. res.redirect(`https://github.com/login/oauth/authorize?${params}`);
  40. });
  41. app.get('/auth/github/authorize/callback', (req, res) => {
  42. let code = req.query.code;
  43. oauth2.getOAuthAccessToken(code, {'redirect_uri': redirect_uri}, (error, access_token, refresh_token, results) => {
  44. if (!error) {
  45. request.get({
  46. url: `https://api.github.com/user?access_token=${access_token}`,
  47. headers: {'User-Agent': 'request'}
  48. }, (error, httpResponse, body) => {
  49. if (error) return res.redirect(`http://localhost:8080/?err=${encodeURIComponent("Something went wrong while logging in1.")}`);
  50. body = JSON.parse(body);
  51. db.models.user.findOne({"services.github.id": body.id}, (err, user) => {
  52. if (err) return res.redirect(`http://localhost:8080/?err=${encodeURIComponent("Something went wrong while logging in2.")}`);
  53. if (user) {
  54. user.services.github.access_token = access_token;
  55. user.save((err) => {
  56. if (err) return res.redirect(`http://localhost:8080/?err=${encodeURIComponent("Something went wrong while logging in3.")}`);
  57. let userSessionId = utils.guid();
  58. cache.hset('userSessions', userSessionId, cache.schemas.userSession(user._id), (err) => {
  59. if (err) return res.redirect(`http://localhost:8080/?err=${encodeURIComponent("Something went wrong while logging in3.")}`);
  60. res.cookie("SID", userSessionId);
  61. res.redirect(`http://localhost:8080/`);
  62. });
  63. });
  64. } else {
  65. db.models.user.findOne({username: new RegExp(`^${body.login}$`, 'i')}, (err, user) => {
  66. if (err) return res.redirect(`http://localhost:8080/?err=${encodeURIComponent("Something went wrong while logging in4.")}`);
  67. if (user) {
  68. res.redirect(`http://localhost:8080/?err=${encodeURIComponent("Something went wrong while logging in5.")}`);
  69. } else {
  70. request.get({
  71. url: `https://api.github.com/user/emails?access_token=${access_token}`,
  72. headers: {'User-Agent': 'request'}
  73. }, (error, httpResponse, body2) => {
  74. if (error) return res.redirect(`http://localhost:8080/?err=${encodeURIComponent("Something went wrong while logging in6.")}`);
  75. body2 = JSON.parse(body2);
  76. let primaryEmail;
  77. body2.forEach((email) => {
  78. if (email.primary) {
  79. primaryEmail = email.email.toLowerCase();
  80. }
  81. });
  82. db.models.user.findOne({"email.address": primaryEmail}, (err, user) => {
  83. if (err) return res.redirect(`http://localhost:8080/?err=${encodeURIComponent("Something went wrong while logging in7.")}`);
  84. if (user) {
  85. if (err) return res.redirect(`http://localhost:8080/?err=${encodeURIComponent("Something went wrong while logging in8.")}`);
  86. } else {
  87. db.models.user.create({
  88. username: body.login,
  89. email: {
  90. address: primaryEmail,
  91. verificationToken: utils.generateRandomString(64)
  92. },
  93. services: {
  94. github: {
  95. id: body.id,
  96. access_token: access_token
  97. }
  98. }
  99. }, (err, user) => {
  100. if (err) return res.redirect(`http://localhost:8080/?err=${encodeURIComponent("Something went wrong while logging in9.")}`);
  101. //TODO Send verification email
  102. let userSessionId = utils.guid();
  103. cache.hset('userSessions', userSessionId, cache.schemas.userSession(user._id), (err) => {
  104. if (err) return res.redirect(`http://localhost:8080/?err=${encodeURIComponent("Something went wrong while logging in3.")}`);
  105. res.cookie("SID", userSessionId);
  106. res.redirect(`http://localhost:8080/`);
  107. });
  108. });
  109. }
  110. });
  111. });
  112. }
  113. });
  114. }
  115. });
  116. });
  117. } else {
  118. res.redirect(`http://localhost:8080/?err=${encodeURIComponent("Something went wrong while logging in2.")}`);
  119. }
  120. });
  121. });
  122. cb();
  123. }
  124. };
  125. module.exports = lib;