ExpressLocals.coffee 9.1 KB

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