overleaf/services/web/app/coffee/infrastructure/ExpressLocals.coffee

291 lines
8.9 KiB
CoffeeScript
Raw Normal View History

2014-02-12 10:23:40 +00:00
logger = require 'logger-sharelatex'
fs = require 'fs'
crypto = require 'crypto'
Settings = require('settings-sharelatex')
SubscriptionFormatters = require('../Features/Subscription/SubscriptionFormatters')
querystring = require('querystring')
2014-07-24 12:24:08 +00:00
SystemMessageManager = require("../Features/SystemMessages/SystemMessageManager")
2016-09-05 14:58:31 +00:00
AuthenticationController = require("../Features/Authentication/AuthenticationController")
_ = require("underscore")
async = require("async")
2014-09-08 14:40:46 +00:00
Modules = require "./Modules"
2016-07-20 15:10:33 +00:00
Url = require "url"
PackageVersions = require "./PackageVersions"
htmlEncoder = new require("node-html-encoder").Encoder("numerical")
2014-02-12 10:23:40 +00:00
fingerprints = {}
Path = require 'path'
2014-02-12 10:23:40 +00:00
jsPath =
if Settings.useMinifiedJs
"/minjs/"
else
"/js/"
ace = PackageVersions.lib('ace')
pdfjs = PackageVersions.lib('pdfjs')
2016-07-18 13:05:07 +00:00
getFileContent = (filePath)->
filePath = Path.join __dirname, "../../../", "public#{filePath}"
exists = fs.existsSync filePath
if exists
content = fs.readFileSync filePath
return content
else
logger.log filePath:filePath, "file does not exist for fingerprints"
return ""
logger.log "Generating file fingerprints..."
pathList = [
["#{jsPath}libs/require.js"]
["#{jsPath}ide.js"]
["#{jsPath}main.js"]
["#{jsPath}libs.js"]
2016-10-25 13:18:37 +00:00
["#{jsPath}#{ace}/ace.js","#{jsPath}#{ace}/mode-latex.js","#{jsPath}#{ace}/worker-latex.js","#{jsPath}#{ace}/snippets/latex.js"]
["#{jsPath}libs/#{pdfjs}/pdf.js"]
["#{jsPath}libs/#{pdfjs}/pdf.worker.js"]
["#{jsPath}libs/#{pdfjs}/compatibility.js"]
["/stylesheets/style.css"]
2017-09-05 09:54:26 +00:00
["/stylesheets/ol-style.css"]
]
for paths in pathList
contentList = _.map(paths, getFileContent)
content = contentList.join("")
hash = crypto.createHash("md5").update(content).digest("hex")
_.each paths, (filePath)->
logger.log "#{filePath}: #{hash}"
fingerprints[filePath] = hash
getFingerprint = (path) ->
if fingerprints[path]?
return fingerprints[path]
else
logger.err "No fingerprint for file: #{path}"
return ""
logger.log "Finished generating file fingerprints"
2016-07-21 14:34:23 +00:00
cdnAvailable = Settings.cdn?.web?.host?
darkCdnAvailable = Settings.cdn?.web?.darkHost?
2014-02-12 10:23:40 +00:00
2017-07-05 13:32:55 +00:00
module.exports = (app, webRouter, privateApiRouter, publicApiRouter)->
webRouter.use (req, res, next)->
2014-02-12 10:23:40 +00:00
res.locals.session = req.session
next()
addSetContentDisposition = (req, res, next) ->
res.setContentDisposition = (type, opts) ->
directives = for k, v of opts
"#{k}=\"#{encodeURIComponent(v)}\""
contentDispositionValue = "#{type}; #{directives.join('; ')}"
res.setHeader(
'Content-Disposition',
contentDispositionValue
)
next()
webRouter.use addSetContentDisposition
2017-07-05 13:32:55 +00:00
privateApiRouter.use addSetContentDisposition
publicApiRouter.use addSetContentDisposition
webRouter.use (req, res, next)->
req.externalAuthenticationSystemUsed = res.locals.externalAuthenticationSystemUsed = ->
Settings.ldap? or Settings.saml?
next()
2016-09-05 14:58:31 +00:00
webRouter.use (req, res, next)->
2016-07-21 14:34:23 +00:00
2016-08-19 10:05:35 +00:00
cdnBlocked = req.query.nocdn == 'true' or req.session.cdnBlocked
2016-09-22 14:33:50 +00:00
user_id = AuthenticationController.getLoggedInUserId(req)
2016-08-19 10:05:35 +00:00
if cdnBlocked and !req.session.cdnBlocked?
2016-09-22 14:33:50 +00:00
logger.log user_id:user_id, ip:req?.ip, "cdnBlocked for user, not using it and turning it off for future requets"
2016-08-19 10:05:35 +00:00
req.session.cdnBlocked = true
2016-07-21 14:34:23 +00:00
isDark = req.headers?.host?.slice(0,4)?.toLowerCase() == "dark"
isSmoke = req.headers?.host?.slice(0,5)?.toLowerCase() == "smoke"
isLive = !isDark and !isSmoke
2016-08-19 10:53:40 +00:00
2016-08-19 10:05:35 +00:00
if cdnAvailable and isLive and !cdnBlocked
2016-07-21 14:34:23 +00:00
staticFilesBase = Settings.cdn?.web?.host
else if darkCdnAvailable and isDark
staticFilesBase = Settings.cdn?.web?.darkHost
2016-07-21 14:34:23 +00:00
else
staticFilesBase = ""
2016-09-05 14:58:31 +00:00
2014-02-12 10:23:40 +00:00
res.locals.jsPath = jsPath
2016-07-20 15:10:33 +00:00
res.locals.fullJsPath = Url.resolve(staticFilesBase, jsPath)
res.locals.lib = PackageVersions.lib
2016-07-20 11:58:32 +00:00
2016-07-19 14:10:07 +00:00
res.locals.buildJsPath = (jsFile, opts = {})->
2016-07-20 15:10:33 +00:00
path = Path.join(jsPath, jsFile)
2016-07-20 11:58:32 +00:00
2016-07-20 13:48:58 +00:00
doFingerPrint = opts.fingerprint != false
2016-09-05 14:58:31 +00:00
2016-07-19 14:10:07 +00:00
if !opts.qs?
opts.qs = {}
2016-07-20 11:58:32 +00:00
2016-07-20 13:48:58 +00:00
if !opts.qs?.fingerprint? and doFingerPrint
opts.qs.fingerprint = getFingerprint(path)
2016-07-20 11:58:32 +00:00
if opts.cdn != false
path = Url.resolve(staticFilesBase, path)
2016-09-05 14:58:31 +00:00
2016-07-19 14:10:07 +00:00
qs = querystring.stringify(opts.qs)
2016-07-20 11:58:32 +00:00
if qs? and qs.length > 0
2016-07-20 15:10:33 +00:00
path = path + "?" + qs
return path
res.locals.buildCssPath = (cssFile)->
2016-07-21 14:34:23 +00:00
path = Path.join("/stylesheets/", cssFile)
2016-07-20 15:10:33 +00:00
return Url.resolve(staticFilesBase, path) + "?fingerprint=" + getFingerprint(path)
res.locals.buildImgPath = (imgFile)->
2016-07-21 14:34:23 +00:00
path = Path.join("/img/", imgFile)
2016-07-20 15:10:33 +00:00
return Url.resolve(staticFilesBase, path)
2014-02-12 10:23:40 +00:00
next()
2016-09-05 14:58:31 +00:00
webRouter.use (req, res, next)->
2014-02-12 10:23:40 +00:00
res.locals.settings = Settings
next()
webRouter.use (req, res, next)->
res.locals.translate = (key, vars = {}, htmlEncode = false) ->
vars.appName = Settings.appName
str = req.i18n.translate(key, vars)
if htmlEncode then htmlEncoder.htmlEncode(str) else str
# Don't include the query string parameters, otherwise Google
# treats ?nocdn=true as the canonical version
res.locals.currentUrl = Url.parse(req.originalUrl).pathname
2014-03-24 17:18:58 +00:00
next()
webRouter.use (req, res, next)->
2014-02-12 10:23:40 +00:00
res.locals.getSiteHost = ->
Settings.siteUrl.substring(Settings.siteUrl.indexOf("//")+2)
next()
2016-09-22 14:33:50 +00:00
webRouter.use (req, res, next) ->
res.locals.getUserEmail = ->
2016-09-22 14:33:50 +00:00
user = AuthenticationController.getSessionUser(req)
email = user?.email or ""
return email
next()
webRouter.use (req, res, next)->
2014-04-07 19:46:58 +00:00
res.locals.formatProjectPublicAccessLevel = (privilegeLevel)->
formatedPrivileges = private:"Private", readOnly:"Public: Read Only", readAndWrite:"Public: Read and Write"
return formatedPrivileges[privilegeLevel] || "Private"
2014-02-12 10:23:40 +00:00
next()
2016-09-05 14:58:31 +00:00
webRouter.use (req, res, next)->
2014-02-12 10:23:40 +00:00
res.locals.buildReferalUrl = (referal_medium) ->
url = Settings.siteUrl
2016-09-22 13:30:34 +00:00
currentUser = AuthenticationController.getSessionUser(req)
if currentUser? and currentUser?.referal_id?
url+="?r=#{currentUser.referal_id}&rm=#{referal_medium}&rs=b" # Referal source = bonus
2014-02-12 10:23:40 +00:00
return url
res.locals.getReferalId = ->
2016-09-22 13:30:34 +00:00
currentUser = AuthenticationController.getSessionUser(req)
if currentUser? and currentUser?.referal_id?
return currentUser.referal_id
2014-02-12 10:23:40 +00:00
res.locals.getReferalTagLine = ->
tagLines = [
"Roar!"
"Shout about us!"
"Please recommend us"
"Tell the world!"
"Thanks for using ShareLaTeX"
]
return tagLines[Math.floor(Math.random()*tagLines.length)]
res.locals.getRedirAsQueryString = ->
if req.query.redir?
return "?#{querystring.stringify({redir:req.query.redir})}"
return ""
res.locals.getLoggedInUserId = ->
2016-09-05 14:58:31 +00:00
return AuthenticationController.getLoggedInUserId(req)
2016-09-06 14:22:13 +00:00
res.locals.isUserLoggedIn = ->
return AuthenticationController.isUserLoggedIn(req)
res.locals.getSessionUser = ->
return AuthenticationController.getSessionUser(req)
2016-11-29 14:38:25 +00:00
2014-02-12 10:23:40 +00:00
next()
webRouter.use (req, res, next) ->
res.locals.csrfToken = req?.csrfToken()
2014-02-12 10:23:40 +00:00
next()
webRouter.use (req, res, next) ->
res.locals.getReqQueryParam = (field)->
return req.query?[field]
next()
2016-09-05 14:58:31 +00:00
webRouter.use (req, res, next)->
res.locals.fingerprint = getFingerprint
2014-02-12 10:23:40 +00:00
next()
2014-06-20 20:35:42 +00:00
2016-09-05 14:58:31 +00:00
webRouter.use (req, res, next)->
2014-02-12 10:23:40 +00:00
res.locals.formatPrice = SubscriptionFormatters.formatPrice
next()
webRouter.use (req, res, next)->
2016-09-22 13:30:34 +00:00
currentUser = AuthenticationController.getSessionUser(req)
if currentUser?
2014-02-12 10:23:40 +00:00
res.locals.user =
2016-09-22 13:30:34 +00:00
email: currentUser.email
first_name: currentUser.first_name
last_name: currentUser.last_name
2014-02-12 10:23:40 +00:00
if req.session.justRegistered
res.locals.justRegistered = true
delete req.session.justRegistered
if req.session.justLoggedIn
res.locals.justLoggedIn = true
delete req.session.justLoggedIn
res.locals.gaToken = Settings.analytics?.ga?.token
res.locals.tenderUrl = Settings.tenderUrl
res.locals.sentrySrc = Settings.sentry?.src
res.locals.sentryPublicDSN = Settings.sentry?.publicDSN
2014-02-12 10:23:40 +00:00
next()
webRouter.use (req, res, next) ->
2014-02-12 10:23:40 +00:00
if req.query? and req.query.scribtex_path?
res.locals.lookingForScribtex = true
res.locals.scribtexPath = req.query.scribtex_path
next()
webRouter.use (req, res, next) ->
# Clone the nav settings so they can be modified for each request
res.locals.nav = {}
for key, value of Settings.nav
res.locals.nav[key] = _.clone(Settings.nav[key])
2014-08-20 13:47:27 +00:00
res.locals.templates = Settings.templateLinks
if res.locals.nav.header
console.error {}, "The `nav.header` setting is no longer supported, use `nav.header_extras` instead"
2014-06-20 20:35:42 +00:00
next()
2016-09-05 14:58:31 +00:00
webRouter.use (req, res, next) ->
2014-07-24 12:24:08 +00:00
SystemMessageManager.getMessages (error, messages = []) ->
res.locals.systemMessages = messages
next()
2014-02-12 10:23:40 +00:00
webRouter.use (req, res, next)->
res.locals.query = req.query
next()
webRouter.use (req, res, next)->
subdomain = _.find Settings.i18n.subdomainLang, (subdomain)->
2014-08-21 16:58:25 +00:00
subdomain.lngCode == req.showUserOtherLng and !subdomain.hide
res.locals.recomendSubdomain = subdomain
res.locals.currentLngCode = req.lng
next()
webRouter.use (req, res, next) ->
if Settings.reloadModuleViewsOnEachRequest
2014-09-08 14:40:46 +00:00
Modules.loadViewIncludes()
res.locals.moduleIncludes = Modules.moduleIncludes
res.locals.moduleIncludesAvailable = Modules.moduleIncludesAvailable
2014-09-08 14:40:46 +00:00
next()