ExpressLocals.coffee 10 KB

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