ExpressLocals.coffee 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346
  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,7)?.toLowerCase().indexOf("dark") != -1
  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.buildCssFileName = (userSettings) ->
  135. themeModifier = ""
  136. if userSettings?.overallTheme? and Settings.overleaf?
  137. themeModifier = userSettings.overallTheme
  138. return "/" + Settings.brandPrefix + themeModifier + "style.css"
  139. res.locals.buildImgPath = (imgFile)->
  140. path = Path.join("/img/", imgFile)
  141. return Url.resolve(staticFilesBase, path)
  142. res.locals.mathJaxPath = res.locals.buildJsPath(
  143. 'libs/mathjax/MathJax.js',
  144. {cdn:false, qs:{config:'TeX-AMS_HTML'}}
  145. )
  146. next()
  147. webRouter.use (req, res, next)->
  148. res.locals.settings = Settings
  149. next()
  150. webRouter.use (req, res, next)->
  151. res.locals.translate = (key, vars = {}, htmlEncode = false) ->
  152. vars.appName = Settings.appName
  153. str = req.i18n.translate(key, vars)
  154. if htmlEncode then htmlEncoder.htmlEncode(str) else str
  155. # Don't include the query string parameters, otherwise Google
  156. # treats ?nocdn=true as the canonical version
  157. res.locals.currentUrl = Url.parse(req.originalUrl).pathname
  158. res.locals.capitalize = (string) ->
  159. return "" if string.length == 0
  160. return string.charAt(0).toUpperCase() + string.slice(1)
  161. next()
  162. webRouter.use (req, res, next)->
  163. res.locals.getSiteHost = ->
  164. Settings.siteUrl.substring(Settings.siteUrl.indexOf("//")+2)
  165. next()
  166. webRouter.use (req, res, next) ->
  167. res.locals.getUserEmail = ->
  168. user = AuthenticationController.getSessionUser(req)
  169. email = user?.email or ""
  170. return email
  171. next()
  172. webRouter.use (req, res, next)->
  173. res.locals.formatProjectPublicAccessLevel = (privilegeLevel)->
  174. formatedPrivileges = private:"Private", readOnly:"Public: Read Only", readAndWrite:"Public: Read and Write"
  175. return formatedPrivileges[privilegeLevel] || "Private"
  176. next()
  177. webRouter.use (req, res, next)->
  178. res.locals.buildReferalUrl = (referal_medium) ->
  179. url = Settings.siteUrl
  180. currentUser = AuthenticationController.getSessionUser(req)
  181. if currentUser? and currentUser?.referal_id?
  182. url+="?r=#{currentUser.referal_id}&rm=#{referal_medium}&rs=b" # Referal source = bonus
  183. return url
  184. res.locals.getReferalId = ->
  185. currentUser = AuthenticationController.getSessionUser(req)
  186. if currentUser? and currentUser?.referal_id?
  187. return currentUser.referal_id
  188. res.locals.getReferalTagLine = ->
  189. tagLines = [
  190. "Roar!"
  191. "Shout about us!"
  192. "Please recommend us"
  193. "Tell the world!"
  194. "Thanks for using ShareLaTeX"
  195. ]
  196. return tagLines[Math.floor(Math.random()*tagLines.length)]
  197. res.locals.getRedirAsQueryString = ->
  198. if req.query.redir?
  199. return "?#{querystring.stringify({redir:req.query.redir})}"
  200. return ""
  201. res.locals.getLoggedInUserId = ->
  202. return AuthenticationController.getLoggedInUserId(req)
  203. res.locals.isUserLoggedIn = ->
  204. return AuthenticationController.isUserLoggedIn(req)
  205. res.locals.getSessionUser = ->
  206. return AuthenticationController.getSessionUser(req)
  207. next()
  208. webRouter.use (req, res, next) ->
  209. res.locals.csrfToken = req?.csrfToken()
  210. next()
  211. webRouter.use (req, res, next) ->
  212. res.locals.getReqQueryParam = (field)->
  213. return req.query?[field]
  214. next()
  215. webRouter.use (req, res, next)->
  216. res.locals.formatPrice = SubscriptionFormatters.formatPrice
  217. next()
  218. webRouter.use (req, res, next)->
  219. currentUser = AuthenticationController.getSessionUser(req)
  220. if currentUser?
  221. res.locals.user =
  222. email: currentUser.email
  223. first_name: currentUser.first_name
  224. last_name: currentUser.last_name
  225. if req.session.justRegistered
  226. res.locals.justRegistered = true
  227. delete req.session.justRegistered
  228. if req.session.justLoggedIn
  229. res.locals.justLoggedIn = true
  230. delete req.session.justLoggedIn
  231. res.locals.gaToken = Settings.analytics?.ga?.token
  232. res.locals.tenderUrl = Settings.tenderUrl
  233. res.locals.sentrySrc = Settings.sentry?.src
  234. res.locals.sentryPublicDSN = Settings.sentry?.publicDSN
  235. next()
  236. webRouter.use (req, res, next) ->
  237. if req.query? and req.query.scribtex_path?
  238. res.locals.lookingForScribtex = true
  239. res.locals.scribtexPath = req.query.scribtex_path
  240. next()
  241. webRouter.use (req, res, next) ->
  242. # Clone the nav settings so they can be modified for each request
  243. res.locals.nav = {}
  244. for key, value of Settings.nav
  245. res.locals.nav[key] = _.clone(Settings.nav[key])
  246. res.locals.templates = Settings.templateLinks
  247. if res.locals.nav.header
  248. console.error {}, "The `nav.header` setting is no longer supported, use `nav.header_extras` instead"
  249. next()
  250. webRouter.use (req, res, next) ->
  251. SystemMessageManager.getMessages (error, messages = []) ->
  252. res.locals.systemMessages = messages
  253. next()
  254. webRouter.use (req, res, next)->
  255. res.locals.query = req.query
  256. next()
  257. webRouter.use (req, res, next)->
  258. subdomain = _.find Settings.i18n.subdomainLang, (subdomain)->
  259. subdomain.lngCode == req.showUserOtherLng and !subdomain.hide
  260. res.locals.recomendSubdomain = subdomain
  261. res.locals.currentLngCode = req.lng
  262. next()
  263. webRouter.use (req, res, next) ->
  264. if Settings.reloadModuleViewsOnEachRequest
  265. Modules.loadViewIncludes()
  266. res.locals.moduleIncludes = Modules.moduleIncludes
  267. res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
  268. next()
  269. webRouter.use (req, res, next) ->
  270. isOl = (Settings.brandPrefix == 'ol-')
  271. res.locals.uiConfig =
  272. defaultResizerSizeOpen : if isOl then 7 else 24
  273. defaultResizerSizeClosed : if isOl then 7 else 24
  274. eastResizerCursor : if isOl then "ew-resize" else null
  275. westResizerCursor : if isOl then "ew-resize" else null
  276. chatResizerSizeOpen : if isOl then 7 else 12
  277. chatResizerSizeClosed : 0
  278. chatMessageBorderSaturation: if isOl then "85%" else "70%"
  279. chatMessageBorderLightness : if isOl then "40%" else "70%"
  280. chatMessageBgSaturation : if isOl then "85%" else "60%"
  281. chatMessageBgLightness : if isOl then "40%" else "97%"
  282. defaultFontFamily : if isOl then 'lucida' else 'monaco'
  283. defaultLineHeight : if isOl then 'normal' else 'compact'
  284. renderAnnouncements : !isOl
  285. next()
  286. webRouter.use (req, res, next) ->
  287. res.locals.ExposedSettings =
  288. isOverleaf: Settings.overleaf?
  289. next()