ExpressLocals.js 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389
  1. const logger = require('logger-sharelatex')
  2. const Settings = require('settings-sharelatex')
  3. const querystring = require('querystring')
  4. const _ = require('lodash')
  5. const Url = require('url')
  6. const NodeHtmlEncoder = require('node-html-encoder').Encoder
  7. const Path = require('path')
  8. const moment = require('moment')
  9. const IS_DEV_ENV = ['development', 'test'].includes(process.env.NODE_ENV)
  10. const Features = require('./Features')
  11. const AuthenticationController = require('../Features/Authentication/AuthenticationController')
  12. const PackageVersions = require('./PackageVersions')
  13. const SystemMessageManager = require('../Features/SystemMessages/SystemMessageManager')
  14. const Modules = require('./Modules')
  15. const htmlEncoder = new NodeHtmlEncoder('numerical')
  16. let webpackManifest
  17. if (!IS_DEV_ENV) {
  18. // Only load webpack manifest file in production. In dev, the web and webpack
  19. // containers can't coordinate, so there no guarantee that the manifest file
  20. // exists when the web server boots. We therefore ignore the manifest file in
  21. // dev reload
  22. webpackManifest = require(`../../../public/manifest.json`)
  23. }
  24. module.exports = function(webRouter, privateApiRouter, publicApiRouter) {
  25. webRouter.use(function(req, res, next) {
  26. res.locals.session = req.session
  27. next()
  28. })
  29. function addSetContentDisposition(req, res, next) {
  30. res.setContentDisposition = function(type, opts) {
  31. const directives = _.map(
  32. opts,
  33. (v, k) => `${k}="${encodeURIComponent(v)}"`
  34. )
  35. const contentDispositionValue = `${type}; ${directives.join('; ')}`
  36. res.setHeader('Content-Disposition', contentDispositionValue)
  37. }
  38. next()
  39. }
  40. webRouter.use(addSetContentDisposition)
  41. privateApiRouter.use(addSetContentDisposition)
  42. publicApiRouter.use(addSetContentDisposition)
  43. webRouter.use(function(req, res, next) {
  44. req.externalAuthenticationSystemUsed =
  45. Features.externalAuthenticationSystemUsed
  46. res.locals.externalAuthenticationSystemUsed =
  47. Features.externalAuthenticationSystemUsed
  48. req.hasFeature = res.locals.hasFeature = Features.hasFeature
  49. next()
  50. })
  51. webRouter.use(function(req, res, next) {
  52. let staticFilesBase
  53. const cdnAvailable =
  54. Settings.cdn && Settings.cdn.web && !!Settings.cdn.web.host
  55. const cdnBlocked = req.query.nocdn === 'true' || req.session.cdnBlocked
  56. const userId = AuthenticationController.getLoggedInUserId(req)
  57. if (cdnBlocked && req.session.cdnBlocked == null) {
  58. logger.log(
  59. { user_id: userId, ip: req != null ? req.ip : undefined },
  60. 'cdnBlocked for user, not using it and turning it off for future requets'
  61. )
  62. req.session.cdnBlocked = true
  63. }
  64. const host = req.headers && req.headers.host
  65. const isSmoke = host.slice(0, 5).toLowerCase() === 'smoke'
  66. if (cdnAvailable && !isSmoke && !cdnBlocked) {
  67. staticFilesBase = Settings.cdn.web.host
  68. } else {
  69. staticFilesBase = ''
  70. }
  71. res.locals.buildJsPath = function(jsFile) {
  72. let path
  73. if (IS_DEV_ENV) {
  74. // In dev: resolve path within JS asset directory
  75. // We are *not* guaranteed to have a manifest file when the server
  76. // starts up
  77. path = Path.join('/js', jsFile)
  78. } else {
  79. // In production: resolve path from webpack manifest file
  80. // We are guaranteed to have a manifest file since webpack compiles in
  81. // the build
  82. path = webpackManifest[jsFile]
  83. }
  84. return Url.resolve(staticFilesBase, path)
  85. }
  86. // Temporary hack while jQuery/Angular dependencies are *not* bundled,
  87. // instead copied into output directory
  88. res.locals.buildCopiedJsAssetPath = function(jsFile, opts = {}) {
  89. let path
  90. if (IS_DEV_ENV) {
  91. // In dev: resolve path to root directory
  92. // We are *not* guaranteed to have a manifest file when the server
  93. // starts up
  94. path = Path.join('/', jsFile)
  95. } else {
  96. // In production: resolve path from webpack manifest file
  97. // We are guaranteed to have a manifest file since webpack compiles in
  98. // the build
  99. path = webpackManifest[jsFile]
  100. }
  101. if (opts.cdn !== false) {
  102. path = Url.resolve(staticFilesBase, path)
  103. }
  104. if (opts.qs) {
  105. path = path + '?' + querystring.stringify(opts.qs)
  106. }
  107. return path
  108. }
  109. res.locals.mathJaxPath = res.locals.buildCopiedJsAssetPath(
  110. 'js/libs/mathjax/MathJax.js',
  111. {
  112. cdn: false,
  113. qs: { config: 'TeX-AMS_HTML,Safe' }
  114. }
  115. )
  116. res.locals.lib = PackageVersions.lib
  117. res.locals.moment = moment
  118. const IEEE_BRAND_ID = 15
  119. res.locals.isIEEE = brandVariation =>
  120. (brandVariation != null ? brandVariation.brand_id : undefined) ===
  121. IEEE_BRAND_ID
  122. res.locals.getCssThemeModifier = function(userSettings, brandVariation) {
  123. // Themes only exist in OL v2
  124. if (Settings.overleaf != null) {
  125. // The IEEE theme takes precedence over the user personal setting, i.e. a user with
  126. // a theme setting of "light" will still get the IEE theme in IEEE branded projects.
  127. if (res.locals.isIEEE(brandVariation)) {
  128. return 'ieee-'
  129. } else if (userSettings && userSettings.overallTheme != null) {
  130. return userSettings.overallTheme
  131. }
  132. }
  133. }
  134. function _buildCssFileName(themeModifier) {
  135. return `${Settings.brandPrefix}${themeModifier || ''}style.css`
  136. }
  137. res.locals.buildCssPath = function(themeModifier) {
  138. const cssFileName = _buildCssFileName(themeModifier)
  139. let path
  140. if (IS_DEV_ENV) {
  141. // In dev: resolve path within CSS asset directory
  142. // We are *not* guaranteed to have a manifest file when the server
  143. // starts up
  144. path = Path.join('/stylesheets/', cssFileName)
  145. } else {
  146. // In production: resolve path from webpack manifest file
  147. // We are guaranteed to have a manifest file since webpack compiles in
  148. // the build
  149. path = webpackManifest[cssFileName]
  150. }
  151. return Url.resolve(staticFilesBase, path)
  152. }
  153. res.locals.buildImgPath = function(imgFile) {
  154. const path = Path.join('/img/', imgFile)
  155. return Url.resolve(staticFilesBase, path)
  156. }
  157. next()
  158. })
  159. webRouter.use(function(req, res, next) {
  160. res.locals.translate = function(key, vars, htmlEncode) {
  161. if (vars == null) {
  162. vars = {}
  163. }
  164. if (htmlEncode == null) {
  165. htmlEncode = false
  166. }
  167. vars.appName = Settings.appName
  168. const str = req.i18n.translate(key, vars)
  169. if (htmlEncode) {
  170. return htmlEncoder.htmlEncode(str)
  171. } else {
  172. return str
  173. }
  174. }
  175. // Don't include the query string parameters, otherwise Google
  176. // treats ?nocdn=true as the canonical version
  177. res.locals.currentUrl = Url.parse(req.originalUrl).pathname
  178. res.locals.capitalize = function(string) {
  179. if (string.length === 0) {
  180. return ''
  181. }
  182. return string.charAt(0).toUpperCase() + string.slice(1)
  183. }
  184. next()
  185. })
  186. webRouter.use(function(req, res, next) {
  187. const subdomain = _.find(
  188. Settings.i18n.subdomainLang,
  189. subdomain => subdomain.lngCode === req.showUserOtherLng && !subdomain.hide
  190. )
  191. res.locals.recomendSubdomain = subdomain
  192. res.locals.currentLngCode = req.lng
  193. next()
  194. })
  195. webRouter.use(function(req, res, next) {
  196. res.locals.getUserEmail = function() {
  197. const user = AuthenticationController.getSessionUser(req)
  198. const email = (user != null ? user.email : undefined) || ''
  199. return email
  200. }
  201. next()
  202. })
  203. webRouter.use(function(req, res, next) {
  204. res.locals.StringHelper = require('../Features/Helpers/StringHelper')
  205. next()
  206. })
  207. webRouter.use(function(req, res, next) {
  208. res.locals.buildReferalUrl = function(referalMedium) {
  209. let url = Settings.siteUrl
  210. const currentUser = AuthenticationController.getSessionUser(req)
  211. if (
  212. currentUser != null &&
  213. (currentUser != null ? currentUser.referal_id : undefined) != null
  214. ) {
  215. url += `?r=${currentUser.referal_id}&rm=${referalMedium}&rs=b` // Referal source = bonus
  216. }
  217. return url
  218. }
  219. res.locals.getReferalId = function() {
  220. const currentUser = AuthenticationController.getSessionUser(req)
  221. if (
  222. currentUser != null &&
  223. (currentUser != null ? currentUser.referal_id : undefined) != null
  224. ) {
  225. return currentUser.referal_id
  226. }
  227. }
  228. next()
  229. })
  230. webRouter.use(function(req, res, next) {
  231. res.locals.csrfToken = req != null ? req.csrfToken() : undefined
  232. next()
  233. })
  234. webRouter.use(function(req, res, next) {
  235. res.locals.gaToken = Settings.analytics && Settings.analytics.ga.token
  236. next()
  237. })
  238. webRouter.use(function(req, res, next) {
  239. res.locals.getReqQueryParam = field =>
  240. req.query != null ? req.query[field] : undefined
  241. next()
  242. })
  243. webRouter.use(function(req, res, next) {
  244. const currentUser = AuthenticationController.getSessionUser(req)
  245. if (currentUser != null) {
  246. res.locals.user = {
  247. email: currentUser.email,
  248. first_name: currentUser.first_name,
  249. last_name: currentUser.last_name
  250. }
  251. }
  252. next()
  253. })
  254. webRouter.use(function(req, res, next) {
  255. res.locals.getLoggedInUserId = () =>
  256. AuthenticationController.getLoggedInUserId(req)
  257. res.locals.getSessionUser = () =>
  258. AuthenticationController.getSessionUser(req)
  259. next()
  260. })
  261. webRouter.use(function(req, res, next) {
  262. // Clone the nav settings so they can be modified for each request
  263. res.locals.nav = {}
  264. for (let key in Settings.nav) {
  265. res.locals.nav[key] = _.clone(Settings.nav[key])
  266. }
  267. res.locals.templates = Settings.templateLinks
  268. next()
  269. })
  270. webRouter.use((req, res, next) =>
  271. SystemMessageManager.getMessages(function(error, messages) {
  272. if (error) {
  273. return next(error)
  274. }
  275. if (messages == null) {
  276. messages = []
  277. }
  278. res.locals.systemMessages = messages
  279. next()
  280. })
  281. )
  282. webRouter.use(function(req, res, next) {
  283. if (Settings.reloadModuleViewsOnEachRequest) {
  284. Modules.loadViewIncludes()
  285. }
  286. res.locals.moduleIncludes = Modules.moduleIncludes
  287. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  288. next()
  289. })
  290. webRouter.use(function(req, res, next) {
  291. res.locals.uiConfig = {
  292. defaultResizerSizeOpen: 7,
  293. defaultResizerSizeClosed: 7,
  294. eastResizerCursor: 'ew-resize',
  295. westResizerCursor: 'ew-resize',
  296. chatResizerSizeOpen: 7,
  297. chatResizerSizeClosed: 0,
  298. chatMessageBorderSaturation: '85%',
  299. chatMessageBorderLightness: '40%',
  300. chatMessageBgSaturation: '85%',
  301. chatMessageBgLightness: '40%',
  302. defaultFontFamily: 'lucida',
  303. defaultLineHeight: 'normal',
  304. renderAnnouncements: false
  305. }
  306. next()
  307. })
  308. webRouter.use(function(req, res, next) {
  309. // TODO
  310. if (Settings.overleaf != null) {
  311. res.locals.overallThemes = [
  312. {
  313. name: 'Default',
  314. val: '',
  315. path: res.locals.buildCssPath(null, { hashedPath: true })
  316. },
  317. {
  318. name: 'Light',
  319. val: 'light-',
  320. path: res.locals.buildCssPath('light-', { hashedPath: true })
  321. }
  322. ]
  323. }
  324. next()
  325. })
  326. webRouter.use(function(req, res, next) {
  327. res.locals.settings = Settings
  328. next()
  329. })
  330. webRouter.use(function(req, res, next) {
  331. res.locals.ExposedSettings = {
  332. isOverleaf: Settings.overleaf != null,
  333. appName: Settings.appName,
  334. hasSamlBeta: req.session.samlBeta,
  335. hasSamlFeature: Features.hasFeature('saml'),
  336. samlInitPath: _.get(Settings, ['saml', 'ukamf', 'initPath']),
  337. siteUrl: Settings.siteUrl,
  338. recaptchaSiteKeyV3:
  339. Settings.recaptcha != null ? Settings.recaptcha.siteKeyV3 : undefined,
  340. recaptchaDisabled:
  341. Settings.recaptcha != null ? Settings.recaptcha.disabled : undefined,
  342. validRootDocExtensions: Settings.validRootDocExtensions
  343. }
  344. next()
  345. })
  346. }