ExpressLocals.coffee 11 KB

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