app.js 8.5 KB

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