ExpressLocals.js 12 KB

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