ExpressLocals.coffee 9.8 KB

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