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. cdnBlocked = req.query.nocdn == 'true' or req.session.cdnBlocked
  78. user_id = AuthenticationController.getLoggedInUserId(req)
  79. if cdnBlocked and !req.session.cdnBlocked?
  80. logger.log user_id:user_id, ip:req?.ip, "cdnBlocked for user, not using it and turning it off for future requets"
  81. req.session.cdnBlocked = true
  82. isDark = req.headers?.host?.slice(0,4)?.toLowerCase() == "dark"
  83. isSmoke = req.headers?.host?.slice(0,5)?.toLowerCase() == "smoke"
  84. isLive = !isDark and !isSmoke
  85. if cdnAvailable and isLive and !cdnBlocked
  86. staticFilesBase = Settings.cdn?.web?.host
  87. else if darkCdnAvailable and isDark
  88. staticFilesBase = Settings.cdn?.web?.darkHost
  89. else
  90. staticFilesBase = ""
  91. res.locals.jsPath = jsPath
  92. res.locals.fullJsPath = Url.resolve(staticFilesBase, jsPath)
  93. res.locals.lib = PackageVersions.lib
  94. res.locals.buildJsPath = (jsFile, opts = {})->
  95. path = Path.join(jsPath, jsFile)
  96. doFingerPrint = opts.fingerprint != false
  97. if !opts.qs?
  98. opts.qs = {}
  99. if !opts.qs?.fingerprint? and doFingerPrint
  100. opts.qs.fingerprint = getFingerprint(path)
  101. if opts.cdn != false
  102. path = Url.resolve(staticFilesBase, path)
  103. qs = querystring.stringify(opts.qs)
  104. if qs? and qs.length > 0
  105. path = path + "?" + qs
  106. return path
  107. res.locals.buildCssPath = (cssFile)->
  108. path = Path.join("/stylesheets/", cssFile)
  109. return Url.resolve(staticFilesBase, path) + "?fingerprint=" + getFingerprint(path)
  110. res.locals.buildImgPath = (imgFile)->
  111. path = Path.join("/img/", imgFile)
  112. return Url.resolve(staticFilesBase, path)
  113. next()
  114. webRouter.use (req, res, next)->
  115. res.locals.settings = Settings
  116. next()
  117. webRouter.use (req, res, next)->
  118. res.locals.translate = (key, vars = {}) ->
  119. vars.appName = Settings.appName
  120. req.i18n.translate(key, vars)
  121. # Don't include the query string parameters, otherwise Google
  122. # treats ?nocdn=true as the canonical version
  123. res.locals.currentUrl = Url.parse(req.originalUrl).pathname
  124. next()
  125. webRouter.use (req, res, next)->
  126. res.locals.getSiteHost = ->
  127. Settings.siteUrl.substring(Settings.siteUrl.indexOf("//")+2)
  128. next()
  129. webRouter.use (req, res, next) ->
  130. res.locals.getUserEmail = ->
  131. user = AuthenticationController.getSessionUser(req)
  132. email = user?.email or ""
  133. return email
  134. next()
  135. webRouter.use (req, res, next)->
  136. res.locals.formatProjectPublicAccessLevel = (privilegeLevel)->
  137. formatedPrivileges = private:"Private", readOnly:"Public: Read Only", readAndWrite:"Public: Read and Write"
  138. return formatedPrivileges[privilegeLevel] || "Private"
  139. next()
  140. webRouter.use (req, res, next)->
  141. res.locals.buildReferalUrl = (referal_medium) ->
  142. url = Settings.siteUrl
  143. currentUser = AuthenticationController.getSessionUser(req)
  144. if currentUser? and currentUser?.referal_id?
  145. url+="?r=#{currentUser.referal_id}&rm=#{referal_medium}&rs=b" # Referal source = bonus
  146. return url
  147. res.locals.getReferalId = ->
  148. currentUser = AuthenticationController.getSessionUser(req)
  149. if currentUser? and currentUser?.referal_id?
  150. return currentUser.referal_id
  151. res.locals.getReferalTagLine = ->
  152. tagLines = [
  153. "Roar!"
  154. "Shout about us!"
  155. "Please recommend us"
  156. "Tell the world!"
  157. "Thanks for using ShareLaTeX"
  158. ]
  159. return tagLines[Math.floor(Math.random()*tagLines.length)]
  160. res.locals.getRedirAsQueryString = ->
  161. if req.query.redir?
  162. return "?#{querystring.stringify({redir:req.query.redir})}"
  163. return ""
  164. res.locals.getLoggedInUserId = ->
  165. return AuthenticationController.getLoggedInUserId(req)
  166. res.locals.isUserLoggedIn = ->
  167. return AuthenticationController.isUserLoggedIn(req)
  168. res.locals.getSessionUser = ->
  169. return AuthenticationController.getSessionUser(req)
  170. next()
  171. webRouter.use (req, res, next) ->
  172. res.locals.csrfToken = req?.csrfToken()
  173. next()
  174. webRouter.use (req, res, next) ->
  175. res.locals.getReqQueryParam = (field)->
  176. return req.query?[field]
  177. next()
  178. webRouter.use (req, res, next)->
  179. res.locals.fingerprint = getFingerprint
  180. next()
  181. webRouter.use (req, res, next)->
  182. res.locals.formatPrice = SubscriptionFormatters.formatPrice
  183. next()
  184. webRouter.use (req, res, next)->
  185. res.locals.externalAuthenticationSystemUsed = ->
  186. Settings.ldap? or Settings.saml?
  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()