app.js 8.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279
  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. const verificationToken = await this.utils.generateRandomString(64);
  68. async.waterfall([
  69. (next) => {
  70. if (req.query.error) return next(req.query.error_description);
  71. next();
  72. },
  73. (next) => {
  74. oauth2.getOAuthAccessToken(code, { redirect_uri }, next);
  75. },
  76. (_access_token, refresh_token, results, next) => {
  77. if (results.error) return next(results.error_description);
  78. access_token = _access_token;
  79. request.get({
  80. url: `https://api.github.com/user?access_token=${access_token}`,
  81. headers: {'User-Agent': 'request'}
  82. }, next);
  83. },
  84. (httpResponse, _body, next) => {
  85. body = _body = JSON.parse(_body);
  86. if (httpResponse.statusCode !== 200) return next(body.message);
  87. if (state) {
  88. return async.waterfall([
  89. (next) => {
  90. cache.hget('sessions', state, next);
  91. },
  92. (session, next) => {
  93. if (!session) return next('Invalid session.');
  94. db.models.user.findOne({ _id: session.userId }, next);
  95. },
  96. (user, next) => {
  97. if (!user) return next('User not found.');
  98. if (user.services.github && user.services.github.id) return next('Account already has GitHub linked.');
  99. db.models.user.updateOne({ _id: user._id }, { $set: {
  100. "services.github": { id: body.id, access_token } }
  101. }, { runValidators: true }, (err) => {
  102. if (err) return next(err);
  103. next(null, user, body);
  104. });
  105. },
  106. (user) => {
  107. cache.pub('user.linkGitHub', user._id);
  108. res.redirect(`${config.get('domain')}/settings`);
  109. }
  110. ], next);
  111. }
  112. if (!body.id) return next("Something went wrong, no id.");
  113. db.models.user.findOne({ 'services.github.id': body.id }, (err, user) => {
  114. next(err, user, body);
  115. });
  116. },
  117. (user, body, next) => {
  118. if (user) {
  119. user.services.github.access_token = access_token;
  120. return user.save(() => {
  121. next(true, user._id);
  122. });
  123. }
  124. db.models.user.findOne({ username: new RegExp(`^${body.login}$`, 'i' )}, (err, user) => {
  125. next(err, user);
  126. });
  127. },
  128. (user, next) => {
  129. if (user) return next('An account with that username already exists.');
  130. request.get({
  131. url: `https://api.github.com/user/emails?access_token=${access_token}`,
  132. headers: {'User-Agent': 'request'}
  133. }, next);
  134. },
  135. (httpResponse, body2, next) => {
  136. body2 = JSON.parse(body2);
  137. if (!Array.isArray(body2)) return next(body2.message);
  138. body2.forEach(email => {
  139. if (email.primary) address = email.email.toLowerCase();
  140. });
  141. db.models.user.findOne({ 'email.address': address }, next);
  142. },
  143. (user, next) => {
  144. this.utils.generateRandomString(12).then((_id) => {
  145. next(null, user, _id);
  146. });
  147. },
  148. (user, _id, next) => {
  149. if (user) return next('An account with that email address already exists.');
  150. next(null, {
  151. _id, //TODO Check if exists
  152. username: body.login,
  153. name: body.name,
  154. location: body.location,
  155. bio: body.bio,
  156. email: {
  157. address,
  158. verificationToken
  159. },
  160. services: {
  161. github: { id: body.id, access_token }
  162. }
  163. });
  164. },
  165. // generate the url for gravatar avatar
  166. (user, next) => {
  167. this.utils.createGravatar(user.email.address).then(url => {
  168. user.avatar = url;
  169. next(null, user);
  170. });
  171. },
  172. // save the new user to the database
  173. (user, next) => {
  174. db.models.user.create(user, next);
  175. },
  176. (user, next) => {
  177. mail.schemas.verifyEmail(address, body.login, user.email.verificationToken);
  178. next(null, user._id);
  179. }
  180. ], async (err, userId) => {
  181. if (err && err !== true) {
  182. err = await this.utils.getError(err);
  183. logger.error('AUTH_GITHUB_AUTHORIZE_CALLBACK', `Failed to authorize with GitHub. "${err}"`);
  184. return redirectOnErr(res, err);
  185. }
  186. const sessionId = await this.utils.guid();
  187. cache.hset('sessions', sessionId, cache.schemas.session(sessionId, userId), err => {
  188. if (err) return redirectOnErr(res, err.message);
  189. let date = new Date();
  190. date.setTime(new Date().getTime() + (2 * 365 * 24 * 60 * 60 * 1000));
  191. res.cookie(SIDname, sessionId, {
  192. expires: date,
  193. secure: config.get("cookie.secure"),
  194. path: "/",
  195. domain: config.get("cookie.domain")
  196. });
  197. logger.success('AUTH_GITHUB_AUTHORIZE_CALLBACK', `User "${userId}" successfully authorized with GitHub.`);
  198. res.redirect(`${config.get('domain')}/`);
  199. });
  200. });
  201. });
  202. app.get('/auth/verify_email', async (req, res) => {
  203. try { await this._validateHook(); } catch { return; }
  204. let code = req.query.code;
  205. async.waterfall([
  206. (next) => {
  207. if (!code) return next('Invalid code.');
  208. next();
  209. },
  210. (next) => {
  211. db.models.user.findOne({"email.verificationToken": code}, next);
  212. },
  213. (user, next) => {
  214. if (!user) return next('User not found.');
  215. if (user.email.verified) return next('This email is already verified.');
  216. db.models.user.updateOne({"email.verificationToken": code}, {$set: {"email.verified": true}, $unset: {"email.verificationToken": ''}}, {runValidators: true}, next);
  217. }
  218. ], (err) => {
  219. if (err) {
  220. let error = 'An error occurred.';
  221. if (typeof err === "string") error = err;
  222. else if (err.message) error = err.message;
  223. logger.error("VERIFY_EMAIL", `Verifying email failed. "${error}"`);
  224. return res.json({ status: 'failure', message: error});
  225. }
  226. logger.success("VERIFY_EMAIL", `Successfully verified email.`);
  227. res.redirect(`${config.get("domain")}?msg=Thank you for verifying your email`);
  228. });
  229. });
  230. resolve();
  231. });
  232. }
  233. }