ExpressLocals.coffee 9.3 KB

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