ExpressLocals.coffee 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376
  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. moment = require 'moment'
  20. jsPath =
  21. if Settings.useMinifiedJs
  22. "/minjs/"
  23. else
  24. "/js/"
  25. ace = PackageVersions.lib('ace')
  26. pdfjs = PackageVersions.lib('pdfjs')
  27. fineuploader = PackageVersions.lib('fineuploader')
  28. getFileContent = (filePath)->
  29. filePath = Path.join __dirname, "../../../", "public#{filePath}"
  30. exists = fs.existsSync filePath
  31. if exists
  32. content = fs.readFileSync filePath, "UTF-8"
  33. return content
  34. else
  35. logger.log filePath:filePath, "file does not exist for hashing"
  36. return ""
  37. pathList = [
  38. "#{jsPath}libs/require.js"
  39. "#{jsPath}ide.js"
  40. "#{jsPath}main.js"
  41. "#{jsPath}libraries.js"
  42. "/stylesheets/style.css"
  43. "/stylesheets/ol-style.css"
  44. "/stylesheets/ol-light-style.css"
  45. "/stylesheets/ol-ieee-style.css"
  46. ].concat(Modules.moduleAssetFiles(jsPath))
  47. if !Settings.useMinifiedJs
  48. logger.log "not using minified JS, not hashing static files"
  49. else
  50. logger.log "Generating file hashes..."
  51. for path in pathList
  52. content = getFileContent(path)
  53. hash = crypto.createHash("md5").update(content).digest("hex")
  54. splitPath = path.split("/")
  55. filenameSplit = splitPath.pop().split(".")
  56. filenameSplit.splice(filenameSplit.length-1, 0, hash)
  57. splitPath.push(filenameSplit.join("."))
  58. hashPath = splitPath.join("/")
  59. hashedFiles[path] = hashPath
  60. fsHashPath = Path.join __dirname, "../../../", "public#{hashPath}"
  61. fs.writeFileSync(fsHashPath, content)
  62. logger.log "Finished hashing static content"
  63. cdnAvailable = Settings.cdn?.web?.host?
  64. darkCdnAvailable = Settings.cdn?.web?.darkHost?
  65. module.exports = (app, webRouter, privateApiRouter, publicApiRouter)->
  66. webRouter.use (req, res, next)->
  67. res.locals.session = req.session
  68. next()
  69. addSetContentDisposition = (req, res, next) ->
  70. res.setContentDisposition = (type, opts) ->
  71. directives = for k, v of opts
  72. "#{k}=\"#{encodeURIComponent(v)}\""
  73. contentDispositionValue = "#{type}; #{directives.join('; ')}"
  74. res.setHeader(
  75. 'Content-Disposition',
  76. contentDispositionValue
  77. )
  78. next()
  79. webRouter.use addSetContentDisposition
  80. privateApiRouter.use addSetContentDisposition
  81. publicApiRouter.use addSetContentDisposition
  82. webRouter.use (req, res, next)->
  83. req.externalAuthenticationSystemUsed = Features.externalAuthenticationSystemUsed
  84. res.locals.externalAuthenticationSystemUsed = Features.externalAuthenticationSystemUsed
  85. req.hasFeature = res.locals.hasFeature = Features.hasFeature
  86. res.locals.userIsFromOLv1 = (user) ->
  87. user.overleaf?.id?
  88. res.locals.userIsFromSL = (user) ->
  89. !user.overleaf?.id?
  90. next()
  91. webRouter.use (req, res, next)->
  92. cdnBlocked = req.query.nocdn == 'true' or req.session.cdnBlocked
  93. user_id = AuthenticationController.getLoggedInUserId(req)
  94. if cdnBlocked and !req.session.cdnBlocked?
  95. logger.log user_id:user_id, ip:req?.ip, "cdnBlocked for user, not using it and turning it off for future requets"
  96. req.session.cdnBlocked = true
  97. isDark = req.headers?.host?.slice(0,7)?.toLowerCase().indexOf("dark") != -1
  98. isSmoke = req.headers?.host?.slice(0,5)?.toLowerCase() == "smoke"
  99. isLive = !isDark and !isSmoke
  100. if cdnAvailable and isLive and !cdnBlocked
  101. staticFilesBase = Settings.cdn?.web?.host
  102. else if darkCdnAvailable and isDark
  103. staticFilesBase = Settings.cdn?.web?.darkHost
  104. else
  105. staticFilesBase = ""
  106. res.locals.jsPath = jsPath
  107. res.locals.fullJsPath = Url.resolve(staticFilesBase, jsPath)
  108. res.locals.lib = PackageVersions.lib
  109. res.locals.moment = moment
  110. res.locals.buildJsPath = (jsFile, opts = {})->
  111. path = Path.join(jsPath, jsFile)
  112. if opts.hashedPath && hashedFiles[path]?
  113. path = hashedFiles[path]
  114. if !opts.qs?
  115. opts.qs = {}
  116. if opts.cdn != false
  117. path = Url.resolve(staticFilesBase, path)
  118. qs = querystring.stringify(opts.qs)
  119. if opts.removeExtension == true
  120. path = path.slice(0,-3)
  121. if qs? and qs.length > 0
  122. path = path + "?" + qs
  123. return path
  124. res.locals.buildWebpackPath = (jsFile, opts = {}) ->
  125. if Settings.webpack? and !Settings.useMinifiedJs
  126. path = Path.join(jsPath, jsFile)
  127. if opts.removeExtension == true
  128. path = path.slice(0,-3)
  129. return "#{Settings.webpack.url}/public#{path}"
  130. else
  131. return res.locals.buildJsPath(jsFile, opts)
  132. IEEE_BRAND_ID = 15
  133. res.locals.isIEEE = (brandVariation) ->
  134. brandVariation?.brand_id == IEEE_BRAND_ID
  135. _buildCssFileName = (themeModifier) ->
  136. return "/" + Settings.brandPrefix + (if themeModifier then themeModifier else "") + "style.css"
  137. res.locals.getCssThemeModifier = (userSettings, brandVariation) ->
  138. # Themes only exist in OL v2
  139. if Settings.overleaf?
  140. # The IEEE theme takes precedence over the user personal setting, i.e. a user with
  141. # a theme setting of "light" will still get the IEE theme in IEEE branded projects.
  142. if res.locals.isIEEE(brandVariation)
  143. themeModifier = "ieee-"
  144. else if userSettings?.overallTheme?
  145. themeModifier = userSettings.overallTheme
  146. return themeModifier
  147. res.locals.buildCssPath = (themeModifier, buildOpts) ->
  148. cssFileName = _buildCssFileName themeModifier
  149. path = Path.join("/stylesheets/", cssFileName)
  150. if buildOpts?.hashedPath && hashedFiles[path]?
  151. hashedPath = hashedFiles[path]
  152. return Url.resolve(staticFilesBase, hashedPath)
  153. return Url.resolve(staticFilesBase, path)
  154. res.locals.buildImgPath = (imgFile)->
  155. path = Path.join("/img/", imgFile)
  156. return Url.resolve(staticFilesBase, path)
  157. res.locals.mathJaxPath = res.locals.buildJsPath(
  158. 'libs/mathjax/MathJax.js',
  159. {cdn:false, qs:{config:'TeX-AMS_HTML,Safe'}}
  160. )
  161. next()
  162. webRouter.use (req, res, next)->
  163. res.locals.settings = Settings
  164. next()
  165. webRouter.use (req, res, next)->
  166. res.locals.translate = (key, vars = {}, htmlEncode = false) ->
  167. vars.appName = Settings.appName
  168. str = req.i18n.translate(key, vars)
  169. if htmlEncode then htmlEncoder.htmlEncode(str) else str
  170. # Don't include the query string parameters, otherwise Google
  171. # treats ?nocdn=true as the canonical version
  172. res.locals.currentUrl = Url.parse(req.originalUrl).pathname
  173. res.locals.capitalize = (string) ->
  174. return "" if string.length == 0
  175. return string.charAt(0).toUpperCase() + string.slice(1)
  176. next()
  177. webRouter.use (req, res, next)->
  178. res.locals.getSiteHost = ->
  179. Settings.siteUrl.substring(Settings.siteUrl.indexOf("//")+2)
  180. next()
  181. webRouter.use (req, res, next) ->
  182. res.locals.getUserEmail = ->
  183. user = AuthenticationController.getSessionUser(req)
  184. email = user?.email or ""
  185. return email
  186. next()
  187. webRouter.use (req, res, next) ->
  188. res.locals.StringHelper = require('../Features/Helpers/StringHelper')
  189. next()
  190. webRouter.use (req, res, next)->
  191. res.locals.formatProjectPublicAccessLevel = (privilegeLevel)->
  192. formatedPrivileges = private:"Private", readOnly:"Public: Read Only", readAndWrite:"Public: Read and Write"
  193. return formatedPrivileges[privilegeLevel] || "Private"
  194. next()
  195. webRouter.use (req, res, next)->
  196. res.locals.buildReferalUrl = (referal_medium) ->
  197. url = Settings.siteUrl
  198. currentUser = AuthenticationController.getSessionUser(req)
  199. if currentUser? and currentUser?.referal_id?
  200. url+="?r=#{currentUser.referal_id}&rm=#{referal_medium}&rs=b" # Referal source = bonus
  201. return url
  202. res.locals.getReferalId = ->
  203. currentUser = AuthenticationController.getSessionUser(req)
  204. if currentUser? and currentUser?.referal_id?
  205. return currentUser.referal_id
  206. res.locals.getReferalTagLine = ->
  207. tagLines = [
  208. "Roar!"
  209. "Shout about us!"
  210. "Please recommend us"
  211. "Tell the world!"
  212. "Thanks for using ShareLaTeX"
  213. ]
  214. return tagLines[Math.floor(Math.random()*tagLines.length)]
  215. res.locals.getRedirAsQueryString = ->
  216. if req.query.redir?
  217. return "?#{querystring.stringify({redir:req.query.redir})}"
  218. return ""
  219. res.locals.getLoggedInUserId = ->
  220. return AuthenticationController.getLoggedInUserId(req)
  221. res.locals.isUserLoggedIn = ->
  222. return AuthenticationController.isUserLoggedIn(req)
  223. res.locals.getSessionUser = ->
  224. return AuthenticationController.getSessionUser(req)
  225. next()
  226. webRouter.use (req, res, next) ->
  227. res.locals.csrfToken = req?.csrfToken()
  228. next()
  229. webRouter.use (req, res, next) ->
  230. res.locals.getReqQueryParam = (field)->
  231. return req.query?[field]
  232. next()
  233. webRouter.use (req, res, next)->
  234. res.locals.formatPrice = SubscriptionFormatters.formatPrice
  235. next()
  236. webRouter.use (req, res, next)->
  237. currentUser = AuthenticationController.getSessionUser(req)
  238. if currentUser?
  239. res.locals.user =
  240. email: currentUser.email
  241. first_name: currentUser.first_name
  242. last_name: currentUser.last_name
  243. if req.session.justRegistered
  244. res.locals.justRegistered = true
  245. delete req.session.justRegistered
  246. if req.session.justLoggedIn
  247. res.locals.justLoggedIn = true
  248. delete req.session.justLoggedIn
  249. res.locals.gaToken = Settings.analytics?.ga?.token
  250. res.locals.tenderUrl = Settings.tenderUrl
  251. res.locals.sentrySrc = Settings.sentry?.src
  252. res.locals.sentryPublicDSN = Settings.sentry?.publicDSN
  253. next()
  254. webRouter.use (req, res, next) ->
  255. if req.query? and req.query.scribtex_path?
  256. res.locals.lookingForScribtex = true
  257. res.locals.scribtexPath = req.query.scribtex_path
  258. next()
  259. webRouter.use (req, res, next) ->
  260. # Clone the nav settings so they can be modified for each request
  261. res.locals.nav = {}
  262. for key, value of Settings.nav
  263. res.locals.nav[key] = _.clone(Settings.nav[key])
  264. res.locals.templates = Settings.templateLinks
  265. if res.locals.nav.header
  266. console.error {}, "The `nav.header` setting is no longer supported, use `nav.header_extras` instead"
  267. next()
  268. webRouter.use (req, res, next) ->
  269. SystemMessageManager.getMessages (error, messages = []) ->
  270. res.locals.systemMessages = messages
  271. next()
  272. webRouter.use (req, res, next)->
  273. res.locals.query = req.query
  274. next()
  275. webRouter.use (req, res, next)->
  276. subdomain = _.find Settings.i18n.subdomainLang, (subdomain)->
  277. subdomain.lngCode == req.showUserOtherLng and !subdomain.hide
  278. res.locals.recomendSubdomain = subdomain
  279. res.locals.currentLngCode = req.lng
  280. next()
  281. webRouter.use (req, res, next) ->
  282. if Settings.reloadModuleViewsOnEachRequest
  283. Modules.loadViewIncludes()
  284. res.locals.moduleIncludes = Modules.moduleIncludes
  285. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  286. next()
  287. webRouter.use (req, res, next) ->
  288. isOl = (Settings.brandPrefix == 'ol-')
  289. res.locals.uiConfig =
  290. defaultResizerSizeOpen : if isOl then 7 else 24
  291. defaultResizerSizeClosed : if isOl then 7 else 24
  292. eastResizerCursor : if isOl then "ew-resize" else null
  293. westResizerCursor : if isOl then "ew-resize" else null
  294. chatResizerSizeOpen : if isOl then 7 else 12
  295. chatResizerSizeClosed : 0
  296. chatMessageBorderSaturation: if isOl then "85%" else "70%"
  297. chatMessageBorderLightness : if isOl then "40%" else "70%"
  298. chatMessageBgSaturation : if isOl then "85%" else "60%"
  299. chatMessageBgLightness : if isOl then "40%" else "97%"
  300. defaultFontFamily : if isOl then 'lucida' else 'monaco'
  301. defaultLineHeight : if isOl then 'normal' else 'compact'
  302. renderAnnouncements : !isOl
  303. next()
  304. webRouter.use (req, res, next) ->
  305. #TODO
  306. if Settings.overleaf?
  307. res.locals.overallThemes = [
  308. { name: "Default", val: "", path: res.locals.buildCssPath(null, { hashedPath: true }) }
  309. { name: "Light", val: "light-", path: res.locals.buildCssPath("light-", { hashedPath: true }) }
  310. ]
  311. next()
  312. webRouter.use (req, res, next) ->
  313. res.locals.ExposedSettings =
  314. isOverleaf: Settings.overleaf?
  315. appName: Settings.appName
  316. siteUrl: Settings.siteUrl
  317. next()