app.js 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251
  1. 'use strict';
  2. const express = require('express');
  3. const bodyParser = require('body-parser');
  4. const cookieParser = require('cookie-parser');
  5. const cors = require('cors');
  6. const config = require('config');
  7. const async = require('async');
  8. const logger = require('./logger');
  9. const mail = require('./mail');
  10. const request = require('request');
  11. const OAuth2 = require('oauth').OAuth2;
  12. const api = require('./api');
  13. const cache = require('./cache');
  14. const db = require('./db');
  15. let utils;
  16. let initialized = false;
  17. let lockdown = false;
  18. const lib = {
  19. app: null,
  20. server: null,
  21. init: (cb) => {
  22. utils = require('./utils');
  23. let app = lib.app = express();
  24. lib.server = app.listen(config.get('serverPort'));
  25. app.use(cookieParser());
  26. app.use(bodyParser.json());
  27. app.use(bodyParser.urlencoded({ extended: true }));
  28. let corsOptions = Object.assign({}, config.get('cors'));
  29. app.use(cors(corsOptions));
  30. app.options('*', cors(corsOptions));
  31. let oauth2 = new OAuth2(
  32. config.get('apis.github.client'),
  33. config.get('apis.github.secret'),
  34. 'https://github.com/',
  35. 'login/oauth/authorize',
  36. 'login/oauth/access_token',
  37. null
  38. );
  39. let redirect_uri = config.get('serverDomain') + '/auth/github/authorize/callback';
  40. app.get('/auth/github/authorize', (req, res) => {
  41. if (lockdown) return res.json({status: 'failure', message: 'Lockdown'});
  42. let params = [
  43. `client_id=${config.get('apis.github.client')}`,
  44. `redirect_uri=${config.get('serverDomain')}/auth/github/authorize/callback`,
  45. `scope=user:email`
  46. ].join('&');
  47. res.redirect(`https://github.com/login/oauth/authorize?${params}`);
  48. });
  49. app.get('/auth/github/link', (req, res) => {
  50. if (lockdown) return res.json({status: 'failure', message: 'Lockdown'});
  51. let params = [
  52. `client_id=${config.get('apis.github.client')}`,
  53. `redirect_uri=${config.get('serverDomain')}/auth/github/authorize/callback`,
  54. `scope=user:email`,
  55. `state=${req.cookies.SID}`
  56. ].join('&');
  57. res.redirect(`https://github.com/login/oauth/authorize?${params}`);
  58. });
  59. function redirectOnErr (res, err){
  60. return res.redirect(`${config.get('domain')}/?err=${encodeURIComponent(err)}`);
  61. }
  62. app.get('/auth/github/authorize/callback', (req, res) => {
  63. if (lockdown) return res.json({status: 'failure', message: 'Lockdown'});
  64. let code = req.query.code;
  65. let access_token;
  66. let body;
  67. let address;
  68. const state = req.query.state;
  69. async.waterfall([
  70. (next) => {
  71. oauth2.getOAuthAccessToken(code, {redirect_uri}, next);
  72. },
  73. (_access_token, refresh_token, results, next) => {
  74. access_token = _access_token;
  75. request.get({
  76. url: `https://api.github.com/user?access_token=${access_token}`,
  77. headers: {'User-Agent': 'request'}
  78. }, next);
  79. },
  80. (httpResponse, _body, next) => {
  81. body = _body = JSON.parse(_body);
  82. if (state) {
  83. return async.waterfall([
  84. (next) => {
  85. cache.hget('sessions', state, next);
  86. },
  87. (session, next) => {
  88. if (!session) return next('Invalid session.');
  89. db.models.user.findOne({_id: session.userId}, next);
  90. },
  91. (user, next) => {
  92. if (!user) return next('User not found.');
  93. if (user.services.github && user.services.github.id) return next('Account already has GitHub linked.');
  94. db.models.user.updateOne({_id: user._id}, {$set: {"services.github": {id: body.id, access_token}}}, {runValidators: true}, (err) => {
  95. if (err) return next(err);
  96. next(null, user, body);
  97. });
  98. },
  99. (user) => {
  100. cache.pub('user.linkGitHub', user._id);
  101. res.redirect(`${config.get('domain')}/settings`);
  102. }
  103. ], next);
  104. }
  105. db.models.user.findOne({'services.github.id': body.id}, (err, user) => {
  106. next(err, user, body);
  107. });
  108. },
  109. (user, body, next) => {
  110. if (user) {
  111. user.services.github.access_token = access_token;
  112. return user.save(() => {
  113. next(true, user._id);
  114. });
  115. }
  116. db.models.user.findOne({ username: new RegExp(`^${body.login}$`, 'i' )}, (err, user) => {
  117. next(err, user);
  118. });
  119. },
  120. (user, next) => {
  121. if (user) return next('An account with that username already exists.');
  122. request.get({
  123. url: `https://api.github.com/user/emails?access_token=${access_token}`,
  124. headers: {'User-Agent': 'request'}
  125. }, next);
  126. },
  127. (httpResponse, body2, next) => {
  128. body2 = JSON.parse(body2);
  129. if (!Array.isArray(body2)) return next(body2.message);
  130. body2.forEach(email => {
  131. if (email.primary) address = email.email.toLowerCase();
  132. });
  133. db.models.user.findOne({'email.address': address}, next);
  134. },
  135. (user, next) => {
  136. const verificationToken = utils.generateRandomString(64);
  137. if (user) return next('An account with that email address already exists.');
  138. db.models.user.create({
  139. _id: utils.generateRandomString(12),//TODO Check if exists
  140. username: body.login,
  141. email: {
  142. address,
  143. verificationToken: verificationToken
  144. },
  145. services: {
  146. github: {id: body.id, access_token}
  147. }
  148. }, next);
  149. },
  150. (user, next) => {
  151. mail.schemas.verifyEmail(address, body.login, user.email.verificationToken);
  152. next(null, user._id);
  153. }
  154. ], (err, userId) => {
  155. if (err && err !== true) {
  156. err = utils.getError(err);
  157. logger.error('AUTH_GITHUB_AUTHORIZE_CALLBACK', `Failed to authorize with GitHub. "${err}"`);
  158. return redirectOnErr(res, err);
  159. }
  160. const sessionId = utils.guid();
  161. cache.hset('sessions', sessionId, cache.schemas.session(sessionId, userId), err => {
  162. if (err) return redirectOnErr(res, err.message);
  163. let date = new Date();
  164. date.setTime(new Date().getTime() + (2 * 365 * 24 * 60 * 60 * 1000));
  165. res.cookie('SID', sessionId, {
  166. expires: date,
  167. secure: config.get("cookie.secure"),
  168. path: "/",
  169. domain: config.get("cookie.domain")
  170. });
  171. logger.success('AUTH_GITHUB_AUTHORIZE_CALLBACK', `User "${userId}" successfully authorized with GitHub.`);
  172. res.redirect(`${config.get('domain')}/`);
  173. });
  174. });
  175. });
  176. app.get('/auth/verify_email', (req, res) => {
  177. let code = req.query.code;
  178. async.waterfall([
  179. (next) => {
  180. if (!code) return next('Invalid code.');
  181. next();
  182. },
  183. (next) => {
  184. db.models.user.findOne({"email.verificationToken": code}, next);
  185. },
  186. (user, next) => {
  187. if (!user) return next('User not found.');
  188. if (user.email.verified) return next('This email is already verified.');
  189. db.models.user.updateOne({"email.verificationToken": code}, {$set: {"email.verified": true}, $unset: {"email.verificationToken": ''}}, {runValidators: true}, next);
  190. }
  191. ], (err) => {
  192. if (err) {
  193. let error = 'An error occurred.';
  194. if (typeof err === "string") error = err;
  195. else if (err.message) error = err.message;
  196. logger.error("VERIFY_EMAIL", `Verifying email failed. "${error}"`);
  197. return res.json({ status: 'failure', message: error});
  198. }
  199. logger.success("VERIFY_EMAIL", `Successfully verified email.`);
  200. res.redirect(`${config.get("domain")}?msg=Thank you for verifying your email`);
  201. });
  202. });
  203. initialized = true;
  204. if (lockdown) return this._lockdown();
  205. cb();
  206. },
  207. _lockdown: () => {
  208. lib.server.close();
  209. lockdown = true;
  210. }
  211. };
  212. module.exports = lib;