ExpressLocals.coffee 7.9 KB

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