app.js 6.8 KB

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