ExpressLocals.coffee 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369
  1. logger = require 'logger-sharelatex'
  2. fs = require 'fs'
  3. crypto = require 'crypto'
  4. Settings = require('settings-sharelatex')
  5. SubscriptionFormatters = require('../Features/Subscription/SubscriptionFormatters')
  6. querystring = require('querystring')
  7. SystemMessageManager = require("../Features/SystemMessages/SystemMessageManager")
  8. AuthenticationController = require("../Features/Authentication/AuthenticationController")
  9. _ = require("underscore")
  10. async = require("async")
  11. Modules = require "./Modules"
  12. Url = require "url"
  13. PackageVersions = require "./PackageVersions"
  14. htmlEncoder = new require("node-html-encoder").Encoder("numerical")
  15. hashedFiles = {}
  16. Path = require 'path'
  17. Features = require "./Features"
  18. Modules = require "./Modules"
  19. jsPath =
  20. if Settings.useMinifiedJs
  21. "/minjs/"
  22. else
  23. "/js/"
  24. ace = PackageVersions.lib('ace')
  25. pdfjs = PackageVersions.lib('pdfjs')
  26. fineuploader = PackageVersions.lib('fineuploader')
  27. getFileContent = (filePath)->
  28. filePath = Path.join __dirname, "../../../", "public#{filePath}"
  29. exists = fs.existsSync filePath
  30. if exists
  31. content = fs.readFileSync filePath, "UTF-8"
  32. return content
  33. else
  34. logger.log filePath:filePath, "file does not exist for hashing"
  35. return ""
  36. pathList = [
  37. "#{jsPath}libs/require.js"
  38. "#{jsPath}ide.js"
  39. "#{jsPath}main.js"
  40. "#{jsPath}libraries.js"
  41. "/stylesheets/style.css"
  42. "/stylesheets/ol-style.css"
  43. "/stylesheets/ol-light-style.css"
  44. "/stylesheets/ol-ieee-style.css"
  45. ].concat(Modules.moduleAssetFiles(jsPath))
  46. if !Settings.useMinifiedJs
  47. logger.log "not using minified JS, not hashing static files"
  48. else
  49. logger.log "Generating file hashes..."
  50. for path in pathList
  51. content = getFileContent(path)
  52. hash = crypto.createHash("md5").update(content).digest("hex")
  53. splitPath = path.split("/")
  54. filenameSplit = splitPath.pop().split(".")
  55. filenameSplit.splice(filenameSplit.length-1, 0, hash)
  56. splitPath.push(filenameSplit.join("."))
  57. hashPath = splitPath.join("/")
  58. hashedFiles[path] = hashPath
  59. fsHashPath = Path.join __dirname, "../../../", "public#{hashPath}"
  60. fs.writeFileSync(fsHashPath, content)
  61. logger.log "Finished hashing static content"
  62. cdnAvailable = Settings.cdn?.web?.host?
  63. darkCdnAvailable = Settings.cdn?.web?.darkHost?
  64. module.exports = (app, webRouter, privateApiRouter, publicApiRouter)->
  65. webRouter.use (req, res, next)->
  66. res.locals.session = req.session
  67. next()
  68. addSetContentDisposition = (req, res, next) ->
  69. res.setContentDisposition = (type, opts) ->
  70. directives = for k, v of opts
  71. "#{k}=\"#{encodeURIComponent(v)}\""
  72. contentDispositionValue = "#{type}; #{directives.join('; ')}"
  73. res.setHeader(
  74. 'Content-Disposition',
  75. contentDispositionValue
  76. )
  77. next()
  78. webRouter.use addSetContentDisposition
  79. privateApiRouter.use addSetContentDisposition
  80. publicApiRouter.use addSetContentDisposition
  81. webRouter.use (req, res, next)->
  82. req.externalAuthenticationSystemUsed = Features.externalAuthenticationSystemUsed
  83. res.locals.externalAuthenticationSystemUsed = Features.externalAuthenticationSystemUsed
  84. req.hasFeature = res.locals.hasFeature = Features.hasFeature
  85. res.locals.userIsFromOLv1 = (user) ->
  86. user.overleaf?.id?
  87. res.locals.userIsFromSL = (user) ->
  88. !user.overleaf?.id?
  89. next()
  90. webRouter.use (req, res, next)->
  91. cdnBlocked = req.query.nocdn == 'true' or req.session.cdnBlocked
  92. user_id = AuthenticationController.getLoggedInUserId(req)
  93. if cdnBlocked and !req.session.cdnBlocked?
  94. logger.log user_id:user_id, ip:req?.ip, "cdnBlocked for user, not using it and turning it off for future requets"
  95. req.session.cdnBlocked = true
  96. isDark = req.headers?.host?.slice(0,7)?.toLowerCase().indexOf("dark") != -1
  97. isSmoke = req.headers?.host?.slice(0,5)?.toLowerCase() == "smoke"
  98. isLive = !isDark and !isSmoke
  99. if cdnAvailable and isLive and !cdnBlocked
  100. staticFilesBase = Settings.cdn?.web?.host
  101. else if darkCdnAvailable and isDark
  102. staticFilesBase = Settings.cdn?.web?.darkHost
  103. else
  104. staticFilesBase = ""
  105. res.locals.jsPath = jsPath
  106. res.locals.fullJsPath = Url.resolve(staticFilesBase, jsPath)
  107. res.locals.lib = PackageVersions.lib
  108. res.locals.buildJsPath = (jsFile, opts = {})->
  109. path = Path.join(jsPath, jsFile)
  110. if opts.hashedPath && hashedFiles[path]?
  111. path = hashedFiles[path]
  112. if !opts.qs?
  113. opts.qs = {}
  114. if opts.cdn != false
  115. path = Url.resolve(staticFilesBase, path)
  116. qs = querystring.stringify(opts.qs)
  117. if opts.removeExtension == true
  118. path = path.slice(0,-3)
  119. if qs? and qs.length > 0
  120. path = path + "?" + qs
  121. return path
  122. res.locals.buildWebpackPath = (jsFile, opts = {}) ->
  123. if Settings.webpack? and !Settings.useMinifiedJs
  124. path = Path.join(jsPath, jsFile)
  125. if opts.removeExtension == true
  126. path = path.slice(0,-3)
  127. return "#{Settings.webpack.url}/public#{path}"
  128. else
  129. return res.locals.buildJsPath(jsFile, opts)
  130. IEEE_BRAND_ID = 15
  131. res.locals.isIEEE = (brandVariation) ->
  132. brandVariation?.brand_id == IEEE_BRAND_ID
  133. _buildCssFileName = (themeModifier) ->
  134. return "/" + Settings.brandPrefix + (if themeModifier then themeModifier else "") + "style.css"
  135. res.locals.getCssThemeModifier = (userSettings, brandVariation) ->
  136. # Themes only exist in OL v2
  137. if Settings.overleaf?
  138. # The IEEE theme takes precedence over the user personal setting, i.e. a user with
  139. # a theme setting of "light" will still get the IEE theme in IEEE branded projects.
  140. if res.locals.isIEEE(brandVariation)
  141. themeModifier = "ieee-"
  142. else if userSettings?.overallTheme?
  143. themeModifier = userSettings.overallTheme
  144. return themeModifier
  145. res.locals.buildCssPath = (themeModifier, buildOpts) ->
  146. cssFileName = _buildCssFileName themeModifier
  147. path = Path.join("/stylesheets/", cssFileName)
  148. if buildOpts?.hashedPath && hashedFiles[path]?
  149. hashedPath = hashedFiles[path]
  150. return Url.resolve(staticFilesBase, hashedPath)
  151. return Url.resolve(staticFilesBase, path)
  152. res.locals.buildImgPath = (imgFile)->
  153. path = Path.join("/img/", imgFile)
  154. return Url.resolve(staticFilesBase, path)
  155. res.locals.mathJaxPath = res.locals.buildJsPath(
  156. 'libs/mathjax/MathJax.js',
  157. {cdn:false, qs:{config:'TeX-AMS_HTML,Safe'}}
  158. )
  159. next()
  160. webRouter.use (req, res, next)->
  161. res.locals.settings = Settings
  162. next()
  163. webRouter.use (req, res, next)->
  164. res.locals.translate = (key, vars = {}, htmlEncode = false) ->
  165. vars.appName = Settings.appName
  166. str = req.i18n.translate(key, vars)
  167. if htmlEncode then htmlEncoder.htmlEncode(str) else str
  168. # Don't include the query string parameters, otherwise Google
  169. # treats ?nocdn=true as the canonical version
  170. res.locals.currentUrl = Url.parse(req.originalUrl).pathname
  171. res.locals.capitalize = (string) ->
  172. return "" if string.length == 0
  173. return string.charAt(0).toUpperCase() + string.slice(1)
  174. next()
  175. webRouter.use (req, res, next)->
  176. res.locals.getSiteHost = ->
  177. Settings.siteUrl.substring(Settings.siteUrl.indexOf("//")+2)
  178. next()
  179. webRouter.use (req, res, next) ->
  180. res.locals.getUserEmail = ->
  181. user = AuthenticationController.getSessionUser(req)
  182. email = user?.email or ""
  183. return email
  184. next()
  185. webRouter.use (req, res, next)->
  186. res.locals.formatProjectPublicAccessLevel = (privilegeLevel)->
  187. formatedPrivileges = private:"Private", readOnly:"Public: Read Only", readAndWrite:"Public: Read and Write"
  188. return formatedPrivileges[privilegeLevel] || "Private"
  189. next()
  190. webRouter.use (req, res, next)->
  191. res.locals.buildReferalUrl = (referal_medium) ->
  192. url = Settings.siteUrl
  193. currentUser = AuthenticationController.getSessionUser(req)
  194. if currentUser? and currentUser?.referal_id?
  195. url+="?r=#{currentUser.referal_id}&rm=#{referal_medium}&rs=b" # Referal source = bonus
  196. return url
  197. res.locals.getReferalId = ->
  198. currentUser = AuthenticationController.getSessionUser(req)
  199. if currentUser? and currentUser?.referal_id?
  200. return currentUser.referal_id
  201. res.locals.getReferalTagLine = ->
  202. tagLines = [
  203. "Roar!"
  204. "Shout about us!"
  205. "Please recommend us"
  206. "Tell the world!"
  207. "Thanks for using ShareLaTeX"
  208. ]
  209. return tagLines[Math.floor(Math.random()*tagLines.length)]
  210. res.locals.getRedirAsQueryString = ->
  211. if req.query.redir?
  212. return "?#{querystring.stringify({redir:req.query.redir})}"
  213. return ""
  214. res.locals.getLoggedInUserId = ->
  215. return AuthenticationController.getLoggedInUserId(req)
  216. res.locals.isUserLoggedIn = ->
  217. return AuthenticationController.isUserLoggedIn(req)
  218. res.locals.getSessionUser = ->
  219. return AuthenticationController.getSessionUser(req)
  220. next()
  221. webRouter.use (req, res, next) ->
  222. res.locals.csrfToken = req?.csrfToken()
  223. next()
  224. webRouter.use (req, res, next) ->
  225. res.locals.getReqQueryParam = (field)->
  226. return req.query?[field]
  227. next()
  228. webRouter.use (req, res, next)->
  229. res.locals.formatPrice = SubscriptionFormatters.formatPrice
  230. next()
  231. webRouter.use (req, res, next)->
  232. currentUser = AuthenticationController.getSessionUser(req)
  233. if currentUser?
  234. res.locals.user =
  235. email: currentUser.email
  236. first_name: currentUser.first_name
  237. last_name: currentUser.last_name
  238. if req.session.justRegistered
  239. res.locals.justRegistered = true
  240. delete req.session.justRegistered
  241. if req.session.justLoggedIn
  242. res.locals.justLoggedIn = true
  243. delete req.session.justLoggedIn
  244. res.locals.gaToken = Settings.analytics?.ga?.token
  245. res.locals.tenderUrl = Settings.tenderUrl
  246. res.locals.sentrySrc = Settings.sentry?.src
  247. res.locals.sentryPublicDSN = Settings.sentry?.publicDSN
  248. next()
  249. webRouter.use (req, res, next) ->
  250. if req.query? and req.query.scribtex_path?
  251. res.locals.lookingForScribtex = true
  252. res.locals.scribtexPath = req.query.scribtex_path
  253. next()
  254. webRouter.use (req, res, next) ->
  255. # Clone the nav settings so they can be modified for each request
  256. res.locals.nav = {}
  257. for key, value of Settings.nav
  258. res.locals.nav[key] = _.clone(Settings.nav[key])
  259. res.locals.templates = Settings.templateLinks
  260. if res.locals.nav.header
  261. console.error {}, "The `nav.header` setting is no longer supported, use `nav.header_extras` instead"
  262. next()
  263. webRouter.use (req, res, next) ->
  264. SystemMessageManager.getMessages (error, messages = []) ->
  265. res.locals.systemMessages = messages
  266. next()
  267. webRouter.use (req, res, next)->
  268. res.locals.query = req.query
  269. next()
  270. webRouter.use (req, res, next)->
  271. subdomain = _.find Settings.i18n.subdomainLang, (subdomain)->
  272. subdomain.lngCode == req.showUserOtherLng and !subdomain.hide
  273. res.locals.recomendSubdomain = subdomain
  274. res.locals.currentLngCode = req.lng
  275. next()
  276. webRouter.use (req, res, next) ->
  277. if Settings.reloadModuleViewsOnEachRequest
  278. Modules.loadViewIncludes()
  279. res.locals.moduleIncludes = Modules.moduleIncludes
  280. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  281. next()
  282. webRouter.use (req, res, next) ->
  283. isOl = (Settings.brandPrefix == 'ol-')
  284. res.locals.uiConfig =
  285. defaultResizerSizeOpen : if isOl then 7 else 24
  286. defaultResizerSizeClosed : if isOl then 7 else 24
  287. eastResizerCursor : if isOl then "ew-resize" else null
  288. westResizerCursor : if isOl then "ew-resize" else null
  289. chatResizerSizeOpen : if isOl then 7 else 12
  290. chatResizerSizeClosed : 0
  291. chatMessageBorderSaturation: if isOl then "85%" else "70%"
  292. chatMessageBorderLightness : if isOl then "40%" else "70%"
  293. chatMessageBgSaturation : if isOl then "85%" else "60%"
  294. chatMessageBgLightness : if isOl then "40%" else "97%"
  295. defaultFontFamily : if isOl then 'lucida' else 'monaco'
  296. defaultLineHeight : if isOl then 'normal' else 'compact'
  297. renderAnnouncements : !isOl
  298. next()
  299. webRouter.use (req, res, next) ->
  300. #TODO
  301. if Settings.overleaf?
  302. res.locals.overallThemes = [
  303. { name: "Default", val: "", path: res.locals.buildCssPath(null, { hashedPath: true }) }
  304. { name: "Light", val: "light-", path: res.locals.buildCssPath("light-", { hashedPath: true }) }
  305. ]
  306. next()
  307. webRouter.use (req, res, next) ->
  308. res.locals.ExposedSettings =
  309. isOverleaf: Settings.overleaf?
  310. appName: Settings.appName
  311. next()