ExpressLocals.coffee 9.0 KB

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