ExpressLocals.coffee 8.9 KB

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