ExpressLocals.coffee 9.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306
  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. hashedFiles = {}
  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, "UTF-8"
  31. return content
  32. else
  33. logger.log filePath:filePath, "file does not exist for hashing"
  34. return ""
  35. pathList = [
  36. "#{jsPath}libs/require.js"
  37. "#{jsPath}ide.js"
  38. "#{jsPath}main.js"
  39. "#{jsPath}libraries.js"
  40. "/stylesheets/style.css"
  41. "/stylesheets/ol-style.css"
  42. ]
  43. if !Settings.useMinifiedJs
  44. logger.log "not using minified JS, not hashing static files"
  45. else
  46. logger.log "Generating file hashes..."
  47. for path in pathList
  48. content = getFileContent(path)
  49. hash = crypto.createHash("md5").update(content).digest("hex")
  50. splitPath = path.split("/")
  51. filenameSplit = splitPath.pop().split(".")
  52. filenameSplit.splice(filenameSplit.length-1, 0, hash)
  53. splitPath.push(filenameSplit.join("."))
  54. hashPath = splitPath.join("/")
  55. hashedFiles[path] = hashPath
  56. fsHashPath = Path.join __dirname, "../../../", "public#{hashPath}"
  57. fs.writeFileSync(fsHashPath, content)
  58. logger.log "Finished hashing static content"
  59. cdnAvailable = Settings.cdn?.web?.host?
  60. darkCdnAvailable = Settings.cdn?.web?.darkHost?
  61. module.exports = (app, webRouter, privateApiRouter, publicApiRouter)->
  62. webRouter.use (req, res, next)->
  63. res.locals.session = req.session
  64. next()
  65. addSetContentDisposition = (req, res, next) ->
  66. res.setContentDisposition = (type, opts) ->
  67. directives = for k, v of opts
  68. "#{k}=\"#{encodeURIComponent(v)}\""
  69. contentDispositionValue = "#{type}; #{directives.join('; ')}"
  70. res.setHeader(
  71. 'Content-Disposition',
  72. contentDispositionValue
  73. )
  74. next()
  75. webRouter.use addSetContentDisposition
  76. privateApiRouter.use addSetContentDisposition
  77. publicApiRouter.use addSetContentDisposition
  78. webRouter.use (req, res, next)->
  79. req.externalAuthenticationSystemUsed = Features.externalAuthenticationSystemUsed
  80. res.locals.externalAuthenticationSystemUsed = Features.externalAuthenticationSystemUsed
  81. req.hasFeature = res.locals.hasFeature = Features.hasFeature
  82. next()
  83. webRouter.use (req, res, next)->
  84. cdnBlocked = req.query.nocdn == 'true' or req.session.cdnBlocked
  85. user_id = AuthenticationController.getLoggedInUserId(req)
  86. if cdnBlocked and !req.session.cdnBlocked?
  87. logger.log user_id:user_id, ip:req?.ip, "cdnBlocked for user, not using it and turning it off for future requets"
  88. req.session.cdnBlocked = true
  89. isDark = req.headers?.host?.slice(0,4)?.toLowerCase() == "dark"
  90. isSmoke = req.headers?.host?.slice(0,5)?.toLowerCase() == "smoke"
  91. isLive = !isDark and !isSmoke
  92. if cdnAvailable and isLive and !cdnBlocked
  93. staticFilesBase = Settings.cdn?.web?.host
  94. else if darkCdnAvailable and isDark
  95. staticFilesBase = Settings.cdn?.web?.darkHost
  96. else
  97. staticFilesBase = ""
  98. res.locals.jsPath = jsPath
  99. res.locals.fullJsPath = Url.resolve(staticFilesBase, jsPath)
  100. res.locals.lib = PackageVersions.lib
  101. res.locals.buildJsPath = (jsFile, opts = {})->
  102. path = Path.join(jsPath, jsFile)
  103. if opts.hashedPath && hashedFiles[path]?
  104. path = hashedFiles[path]
  105. if !opts.qs?
  106. opts.qs = {}
  107. if opts.cdn != false
  108. path = Url.resolve(staticFilesBase, path)
  109. qs = querystring.stringify(opts.qs)
  110. if opts.removeExtension == true
  111. path = path.slice(0,-3)
  112. if qs? and qs.length > 0
  113. path = path + "?" + qs
  114. return path
  115. res.locals.buildCssPath = (cssFile, opts)->
  116. path = Path.join("/stylesheets/", cssFile)
  117. if opts?.hashedPath && hashedFiles[path]?
  118. hashedPath = hashedFiles[path]
  119. return Url.resolve(staticFilesBase, hashedPath)
  120. return Url.resolve(staticFilesBase, 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.formatPrice = SubscriptionFormatters.formatPrice
  192. next()
  193. webRouter.use (req, res, next)->
  194. currentUser = AuthenticationController.getSessionUser(req)
  195. if currentUser?
  196. res.locals.user =
  197. email: currentUser.email
  198. first_name: currentUser.first_name
  199. last_name: currentUser.last_name
  200. if req.session.justRegistered
  201. res.locals.justRegistered = true
  202. delete req.session.justRegistered
  203. if req.session.justLoggedIn
  204. res.locals.justLoggedIn = true
  205. delete req.session.justLoggedIn
  206. res.locals.gaToken = Settings.analytics?.ga?.token
  207. res.locals.tenderUrl = Settings.tenderUrl
  208. res.locals.sentrySrc = Settings.sentry?.src
  209. res.locals.sentryPublicDSN = Settings.sentry?.publicDSN
  210. next()
  211. webRouter.use (req, res, next) ->
  212. if req.query? and req.query.scribtex_path?
  213. res.locals.lookingForScribtex = true
  214. res.locals.scribtexPath = req.query.scribtex_path
  215. next()
  216. webRouter.use (req, res, next) ->
  217. # Clone the nav settings so they can be modified for each request
  218. res.locals.nav = {}
  219. for key, value of Settings.nav
  220. res.locals.nav[key] = _.clone(Settings.nav[key])
  221. res.locals.templates = Settings.templateLinks
  222. if res.locals.nav.header
  223. console.error {}, "The `nav.header` setting is no longer supported, use `nav.header_extras` instead"
  224. next()
  225. webRouter.use (req, res, next) ->
  226. SystemMessageManager.getMessages (error, messages = []) ->
  227. res.locals.systemMessages = messages
  228. next()
  229. webRouter.use (req, res, next)->
  230. res.locals.query = req.query
  231. next()
  232. webRouter.use (req, res, next)->
  233. subdomain = _.find Settings.i18n.subdomainLang, (subdomain)->
  234. subdomain.lngCode == req.showUserOtherLng and !subdomain.hide
  235. res.locals.recomendSubdomain = subdomain
  236. res.locals.currentLngCode = req.lng
  237. next()
  238. webRouter.use (req, res, next) ->
  239. if Settings.reloadModuleViewsOnEachRequest
  240. Modules.loadViewIncludes()
  241. res.locals.moduleIncludes = Modules.moduleIncludes
  242. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  243. next()
  244. webRouter.use (req, res, next) ->
  245. isOl = (Settings.brandPrefix == 'ol-')
  246. res.locals.uiConfig =
  247. defaultResizerSizeOpen : if isOl then 2 else 24
  248. defaultResizerSizeClosed : if isOl then 2 else 24
  249. eastResizerCursor : if isOl then "ew-resize" else null
  250. westResizerCursor : if isOl then "ew-resize" else null
  251. chatResizerSizeOpen : if isOl then 2 else 12
  252. chatResizerSizeClosed : 0
  253. next()