ExpressLocals.coffee 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  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. Modules = require "./Modules"
  19. jsPath =
  20. if Settings.useMinifiedJs
  21. "/minjs/"
  22. else
  23. "/js/"
  24. ace = PackageVersions.lib('ace')
  25. pdfjs = PackageVersions.lib('pdfjs')
  26. fineuploader = PackageVersions.lib('fineuploader')
  27. getFileContent = (filePath)->
  28. filePath = Path.join __dirname, "../../../", "public#{filePath}"
  29. exists = fs.existsSync filePath
  30. if exists
  31. content = fs.readFileSync filePath, "UTF-8"
  32. return content
  33. else
  34. logger.log filePath:filePath, "file does not exist for hashing"
  35. return ""
  36. pathList = [
  37. "#{jsPath}libs/require.js"
  38. "#{jsPath}ide.js"
  39. "#{jsPath}main.js"
  40. "#{jsPath}libraries.js"
  41. "/stylesheets/style.css"
  42. "/stylesheets/ol-style.css"
  43. ].concat(Modules.moduleAssetFiles(jsPath))
  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. res.locals.capitalize = (string) ->
  150. return "" if string.length == 0
  151. return string.charAt(0).toUpperCase() + string.slice(1)
  152. next()
  153. webRouter.use (req, res, next)->
  154. res.locals.getSiteHost = ->
  155. Settings.siteUrl.substring(Settings.siteUrl.indexOf("//")+2)
  156. next()
  157. webRouter.use (req, res, next) ->
  158. res.locals.getUserEmail = ->
  159. user = AuthenticationController.getSessionUser(req)
  160. email = user?.email or ""
  161. return email
  162. next()
  163. webRouter.use (req, res, next)->
  164. res.locals.formatProjectPublicAccessLevel = (privilegeLevel)->
  165. formatedPrivileges = private:"Private", readOnly:"Public: Read Only", readAndWrite:"Public: Read and Write"
  166. return formatedPrivileges[privilegeLevel] || "Private"
  167. next()
  168. webRouter.use (req, res, next)->
  169. res.locals.buildReferalUrl = (referal_medium) ->
  170. url = Settings.siteUrl
  171. currentUser = AuthenticationController.getSessionUser(req)
  172. if currentUser? and currentUser?.referal_id?
  173. url+="?r=#{currentUser.referal_id}&rm=#{referal_medium}&rs=b" # Referal source = bonus
  174. return url
  175. res.locals.getReferalId = ->
  176. currentUser = AuthenticationController.getSessionUser(req)
  177. if currentUser? and currentUser?.referal_id?
  178. return currentUser.referal_id
  179. res.locals.getReferalTagLine = ->
  180. tagLines = [
  181. "Roar!"
  182. "Shout about us!"
  183. "Please recommend us"
  184. "Tell the world!"
  185. "Thanks for using ShareLaTeX"
  186. ]
  187. return tagLines[Math.floor(Math.random()*tagLines.length)]
  188. res.locals.getRedirAsQueryString = ->
  189. if req.query.redir?
  190. return "?#{querystring.stringify({redir:req.query.redir})}"
  191. return ""
  192. res.locals.getLoggedInUserId = ->
  193. return AuthenticationController.getLoggedInUserId(req)
  194. res.locals.isUserLoggedIn = ->
  195. return AuthenticationController.isUserLoggedIn(req)
  196. res.locals.getSessionUser = ->
  197. return AuthenticationController.getSessionUser(req)
  198. next()
  199. webRouter.use (req, res, next) ->
  200. res.locals.csrfToken = req?.csrfToken()
  201. next()
  202. webRouter.use (req, res, next) ->
  203. res.locals.getReqQueryParam = (field)->
  204. return req.query?[field]
  205. next()
  206. webRouter.use (req, res, next)->
  207. res.locals.formatPrice = SubscriptionFormatters.formatPrice
  208. next()
  209. webRouter.use (req, res, next)->
  210. currentUser = AuthenticationController.getSessionUser(req)
  211. if currentUser?
  212. res.locals.user =
  213. email: currentUser.email
  214. first_name: currentUser.first_name
  215. last_name: currentUser.last_name
  216. if req.session.justRegistered
  217. res.locals.justRegistered = true
  218. delete req.session.justRegistered
  219. if req.session.justLoggedIn
  220. res.locals.justLoggedIn = true
  221. delete req.session.justLoggedIn
  222. res.locals.gaToken = Settings.analytics?.ga?.token
  223. res.locals.tenderUrl = Settings.tenderUrl
  224. res.locals.sentrySrc = Settings.sentry?.src
  225. res.locals.sentryPublicDSN = Settings.sentry?.publicDSN
  226. next()
  227. webRouter.use (req, res, next) ->
  228. if req.query? and req.query.scribtex_path?
  229. res.locals.lookingForScribtex = true
  230. res.locals.scribtexPath = req.query.scribtex_path
  231. next()
  232. webRouter.use (req, res, next) ->
  233. # Clone the nav settings so they can be modified for each request
  234. res.locals.nav = {}
  235. for key, value of Settings.nav
  236. res.locals.nav[key] = _.clone(Settings.nav[key])
  237. res.locals.templates = Settings.templateLinks
  238. if res.locals.nav.header
  239. console.error {}, "The `nav.header` setting is no longer supported, use `nav.header_extras` instead"
  240. next()
  241. webRouter.use (req, res, next) ->
  242. SystemMessageManager.getMessages (error, messages = []) ->
  243. res.locals.systemMessages = messages
  244. next()
  245. webRouter.use (req, res, next)->
  246. res.locals.query = req.query
  247. next()
  248. webRouter.use (req, res, next)->
  249. subdomain = _.find Settings.i18n.subdomainLang, (subdomain)->
  250. subdomain.lngCode == req.showUserOtherLng and !subdomain.hide
  251. res.locals.recomendSubdomain = subdomain
  252. res.locals.currentLngCode = req.lng
  253. next()
  254. webRouter.use (req, res, next) ->
  255. if Settings.reloadModuleViewsOnEachRequest
  256. Modules.loadViewIncludes()
  257. res.locals.moduleIncludes = Modules.moduleIncludes
  258. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  259. next()
  260. webRouter.use (req, res, next) ->
  261. isOl = (Settings.brandPrefix == 'ol-')
  262. res.locals.uiConfig =
  263. defaultResizerSizeOpen : if isOl then 7 else 24
  264. defaultResizerSizeClosed : if isOl then 7 else 24
  265. eastResizerCursor : if isOl then "ew-resize" else null
  266. westResizerCursor : if isOl then "ew-resize" else null
  267. chatResizerSizeOpen : if isOl then 7 else 12
  268. chatResizerSizeClosed : 0
  269. chatMessageBorderSaturation: if isOl then "85%" else "70%"
  270. chatMessageBorderLightness : if isOl then "40%" else "70%"
  271. chatMessageBgSaturation : if isOl then "85%" else "60%"
  272. chatMessageBgLightness : if isOl then "40%" else "97%"
  273. defaultFontFamily : if isOl then 'lucida' else 'monaco'
  274. defaultLineHeight : if isOl then 'normal' else 'compact'
  275. renderAnnouncements : !isOl
  276. next()