app.js 7.7 KB

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