ExpressLocals.coffee 8.6 KB

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