ExpressLocals.coffee 8.1 KB

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