ExpressLocals.coffee 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289
  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. fingerprints = {}
  16. Path = require 'path'
  17. jsPath =
  18. if Settings.useMinifiedJs
  19. "/minjs/"
  20. else
  21. "/js/"
  22. ace = PackageVersions.lib('ace')
  23. pdfjs = PackageVersions.lib('pdfjs')
  24. getFileContent = (filePath)->
  25. filePath = Path.join __dirname, "../../../", "public#{filePath}"
  26. exists = fs.existsSync filePath
  27. if exists
  28. content = fs.readFileSync filePath
  29. return content
  30. else
  31. logger.log filePath:filePath, "file does not exist for fingerprints"
  32. return ""
  33. logger.log "Generating file fingerprints..."
  34. pathList = [
  35. ["#{jsPath}libs/require.js"]
  36. ["#{jsPath}ide.js"]
  37. ["#{jsPath}main.js"]
  38. ["#{jsPath}libs.js"]
  39. ["#{jsPath}#{ace}/ace.js","#{jsPath}#{ace}/mode-latex.js","#{jsPath}#{ace}/worker-latex.js","#{jsPath}#{ace}/snippets/latex.js"]
  40. ["#{jsPath}libs/#{pdfjs}/pdf.js"]
  41. ["#{jsPath}libs/#{pdfjs}/pdf.worker.js"]
  42. ["#{jsPath}libs/#{pdfjs}/compatibility.js"]
  43. ["/stylesheets/style.css"]
  44. ]
  45. for paths in pathList
  46. contentList = _.map(paths, getFileContent)
  47. content = contentList.join("")
  48. hash = crypto.createHash("md5").update(content).digest("hex")
  49. _.each paths, (filePath)->
  50. logger.log "#{filePath}: #{hash}"
  51. fingerprints[filePath] = hash
  52. getFingerprint = (path) ->
  53. if fingerprints[path]?
  54. return fingerprints[path]
  55. else
  56. logger.err "No fingerprint for file: #{path}"
  57. return ""
  58. logger.log "Finished generating file fingerprints"
  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 = res.locals.externalAuthenticationSystemUsed = ->
  80. Settings.ldap? or Settings.saml?
  81. next()
  82. webRouter.use (req, res, next)->
  83. cdnBlocked = req.query.nocdn == 'true' or req.session.cdnBlocked
  84. user_id = AuthenticationController.getLoggedInUserId(req)
  85. if cdnBlocked and !req.session.cdnBlocked?
  86. logger.log user_id:user_id, ip:req?.ip, "cdnBlocked for user, not using it and turning it off for future requets"
  87. req.session.cdnBlocked = true
  88. isDark = req.headers?.host?.slice(0,4)?.toLowerCase() == "dark"
  89. isSmoke = req.headers?.host?.slice(0,5)?.toLowerCase() == "smoke"
  90. isLive = !isDark and !isSmoke
  91. if cdnAvailable and isLive and !cdnBlocked
  92. staticFilesBase = Settings.cdn?.web?.host
  93. else if darkCdnAvailable and isDark
  94. staticFilesBase = Settings.cdn?.web?.darkHost
  95. else
  96. staticFilesBase = ""
  97. res.locals.jsPath = jsPath
  98. res.locals.fullJsPath = Url.resolve(staticFilesBase, jsPath)
  99. res.locals.lib = PackageVersions.lib
  100. res.locals.buildJsPath = (jsFile, opts = {})->
  101. path = Path.join(jsPath, jsFile)
  102. doFingerPrint = opts.fingerprint != false
  103. if !opts.qs?
  104. opts.qs = {}
  105. if !opts.qs?.fingerprint? and doFingerPrint
  106. opts.qs.fingerprint = getFingerprint(path)
  107. if opts.cdn != false
  108. path = Url.resolve(staticFilesBase, path)
  109. qs = querystring.stringify(opts.qs)
  110. if qs? and qs.length > 0
  111. path = path + "?" + qs
  112. return path
  113. res.locals.buildCssPath = (cssFile)->
  114. path = Path.join("/stylesheets/", cssFile)
  115. return Url.resolve(staticFilesBase, path) + "?fingerprint=" + getFingerprint(path)
  116. res.locals.buildImgPath = (imgFile)->
  117. path = Path.join("/img/", imgFile)
  118. return Url.resolve(staticFilesBase, path)
  119. next()
  120. webRouter.use (req, res, next)->
  121. res.locals.settings = Settings
  122. next()
  123. webRouter.use (req, res, next)->
  124. res.locals.translate = (key, vars = {}, htmlEncode = false) ->
  125. vars.appName = Settings.appName
  126. str = req.i18n.translate(key, vars)
  127. if htmlEncode then htmlEncoder.htmlEncode(str) else str
  128. # Don't include the query string parameters, otherwise Google
  129. # treats ?nocdn=true as the canonical version
  130. res.locals.currentUrl = Url.parse(req.originalUrl).pathname
  131. next()
  132. webRouter.use (req, res, next)->
  133. res.locals.getSiteHost = ->
  134. Settings.siteUrl.substring(Settings.siteUrl.indexOf("//")+2)
  135. next()
  136. webRouter.use (req, res, next) ->
  137. res.locals.getUserEmail = ->
  138. user = AuthenticationController.getSessionUser(req)
  139. email = user?.email or ""
  140. return email
  141. next()
  142. webRouter.use (req, res, next)->
  143. res.locals.formatProjectPublicAccessLevel = (privilegeLevel)->
  144. formatedPrivileges = private:"Private", readOnly:"Public: Read Only", readAndWrite:"Public: Read and Write"
  145. return formatedPrivileges[privilegeLevel] || "Private"
  146. next()
  147. webRouter.use (req, res, next)->
  148. res.locals.buildReferalUrl = (referal_medium) ->
  149. url = Settings.siteUrl
  150. currentUser = AuthenticationController.getSessionUser(req)
  151. if currentUser? and currentUser?.referal_id?
  152. url+="?r=#{currentUser.referal_id}&rm=#{referal_medium}&rs=b" # Referal source = bonus
  153. return url
  154. res.locals.getReferalId = ->
  155. currentUser = AuthenticationController.getSessionUser(req)
  156. if currentUser? and currentUser?.referal_id?
  157. return currentUser.referal_id
  158. res.locals.getReferalTagLine = ->
  159. tagLines = [
  160. "Roar!"
  161. "Shout about us!"
  162. "Please recommend us"
  163. "Tell the world!"
  164. "Thanks for using ShareLaTeX"
  165. ]
  166. return tagLines[Math.floor(Math.random()*tagLines.length)]
  167. res.locals.getRedirAsQueryString = ->
  168. if req.query.redir?
  169. return "?#{querystring.stringify({redir:req.query.redir})}"
  170. return ""
  171. res.locals.getLoggedInUserId = ->
  172. return AuthenticationController.getLoggedInUserId(req)
  173. res.locals.isUserLoggedIn = ->
  174. return AuthenticationController.isUserLoggedIn(req)
  175. res.locals.getSessionUser = ->
  176. return AuthenticationController.getSessionUser(req)
  177. next()
  178. webRouter.use (req, res, next) ->
  179. res.locals.csrfToken = req?.csrfToken()
  180. next()
  181. webRouter.use (req, res, next) ->
  182. res.locals.getReqQueryParam = (field)->
  183. return req.query?[field]
  184. next()
  185. webRouter.use (req, res, next)->
  186. res.locals.fingerprint = getFingerprint
  187. next()
  188. webRouter.use (req, res, next)->
  189. res.locals.formatPrice = SubscriptionFormatters.formatPrice
  190. next()
  191. webRouter.use (req, res, next)->
  192. currentUser = AuthenticationController.getSessionUser(req)
  193. if currentUser?
  194. res.locals.user =
  195. email: currentUser.email
  196. first_name: currentUser.first_name
  197. last_name: currentUser.last_name
  198. if req.session.justRegistered
  199. res.locals.justRegistered = true
  200. delete req.session.justRegistered
  201. if req.session.justLoggedIn
  202. res.locals.justLoggedIn = true
  203. delete req.session.justLoggedIn
  204. res.locals.gaToken = Settings.analytics?.ga?.token
  205. res.locals.tenderUrl = Settings.tenderUrl
  206. res.locals.sentrySrc = Settings.sentry?.src
  207. res.locals.sentryPublicDSN = Settings.sentry?.publicDSN
  208. next()
  209. webRouter.use (req, res, next) ->
  210. if req.query? and req.query.scribtex_path?
  211. res.locals.lookingForScribtex = true
  212. res.locals.scribtexPath = req.query.scribtex_path
  213. next()
  214. webRouter.use (req, res, next) ->
  215. # Clone the nav settings so they can be modified for each request
  216. res.locals.nav = {}
  217. for key, value of Settings.nav
  218. res.locals.nav[key] = _.clone(Settings.nav[key])
  219. res.locals.templates = Settings.templateLinks
  220. if res.locals.nav.header
  221. console.error {}, "The `nav.header` setting is no longer supported, use `nav.header_extras` instead"
  222. next()
  223. webRouter.use (req, res, next) ->
  224. SystemMessageManager.getMessages (error, messages = []) ->
  225. res.locals.systemMessages = messages
  226. next()
  227. webRouter.use (req, res, next)->
  228. res.locals.query = req.query
  229. next()
  230. webRouter.use (req, res, next)->
  231. subdomain = _.find Settings.i18n.subdomainLang, (subdomain)->
  232. subdomain.lngCode == req.showUserOtherLng and !subdomain.hide
  233. res.locals.recomendSubdomain = subdomain
  234. res.locals.currentLngCode = req.lng
  235. next()
  236. webRouter.use (req, res, next) ->
  237. if Settings.reloadModuleViewsOnEachRequest
  238. Modules.loadViewIncludes()
  239. res.locals.moduleIncludes = Modules.moduleIncludes
  240. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  241. next()