Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
def __check_requirements(self, conditions):
# requested_address = urllib.quote(cherrypy.request.request_line.split()[1])
if conditions is not None:
session = getattr(cherrypy, 'session')
username = session.get(SESSION_KEY, None)
if username:
cherrypy.request.login = username
for condition in conditions:
# A condition is just a callable that returns true or false
if not condition():
# TODO: log why if possible
raise cherrypy.HTTPError(403, 'No allowed')
# TODO: redirect the user to the requested url if the url matches!! -> external view of an event
# raise cherrypy.HTTPRedirect(requested_address)
else:
raise cherrypy.HTTPError(403, 'Not authenticated')
# If no clickable files were created, then return clickthrough file
else:
pagedata = open(clickthrough, 'r')
clickpage = pagedata.readlines()
pagedata.close()
return clickpage
else:
methodType = 'POST'
# If form was submitted via a GET request, build HTML form using GET, otherwise POST
# Set the form to autopost with POST/GET.
if re.search('^GET$', cherrypy.request.method):
methodType = 'GET'
postFormPhish = '<form action="'+htype+'://'+domainget+cherrypy.request.path_info+'" name="form0" method="'+methodType+'">'+formList+'</form>'
postsoup = BeautifulSoup(postFormPhish)
postFormHtml = postsoup.prettify("iso-8859-1")
return postFormHtml
else:
# Log any submitted arguments and return the original phish page
logArgs(self.args, self.kwargs)
return phishHtml.encode('utf-8').strip()
else:
# Log any submitted arguments and return the original phish page
logArgs(self.args, self.kwargs)
return phishHtml.encode('utf-8').strip()
original browser URL (assuming no internal redirections).
If relative is None or not provided, request.app.relative_urls will
be used (if available, else False). If False, the output will be an
absolute URL (including the scheme, host, vhost, and script_name).
If True, the output will instead be a URL that is relative to the
current request path, perhaps including '..' atoms. If relative is
the string 'server', the output will instead be a URL that is
relative to the server root; i.e., it will start with a slash.
"""
if isinstance(qs, (tuple, list, dict)):
qs = urllib.parse.urlencode(qs)
if qs:
qs = '?' + qs
if cherrypy.request.app:
if not path.startswith('/'):
# Append/remove trailing slash from path_info as needed
# (this is to support mistyped URL's without redirecting;
# if you want to redirect, use tools.trailing_slash).
pi = cherrypy.request.path_info
if cherrypy.request.is_index is True:
if not pi.endswith('/'):
pi = pi + '/'
elif cherrypy.request.is_index is False:
if pi.endswith('/') and pi != '/':
pi = pi[:-1]
if path == '':
path = pi
else:
path = urllib.parse.urljoin(pi, path)
"""
Load a model based on id using the current cherrypy token parameter for
authentication, caching the results. This must be called in a cherrypy
context.
:param resource: the resource class instance calling the function. Used
for access to the current user and model importer.
:param model: the model name, e.g., 'item'.
:param plugin: the plugin name when loading a plugin model.
:param id: a string id of the model to load.
:param allowCookie: true if the cookie authentication method is allowed.
:param level: access level desired.
:returns: the loaded model.
"""
key = tokenStr = None
if 'token' in cherrypy.request.params: # Token as a parameter
tokenStr = cherrypy.request.params.get('token')
elif 'Girder-Token' in cherrypy.request.headers:
tokenStr = cherrypy.request.headers['Girder-Token']
elif 'girderToken' in cherrypy.request.cookie and allowCookie:
tokenStr = cherrypy.request.cookie['girderToken'].value
key = (model, tokenStr, id)
cacheEntry = LoadModelCache.get(key)
if cacheEntry and cacheEntry['expiry'] > time.time():
entry = cacheEntry['result']
cacheEntry['hits'] += 1
else:
# we have to get the token separately from the user if we are using
# cookies.
if allowCookie:
getCurrentToken(allowCookie)
setattr(cherrypy.request, 'girderAllowCookie', True)
content_type = mimetypes.types_map.get(ext, "text/plain")
response.headers['Content-Type'] = content_type
if disposition is not None:
if name is None:
name = os.path.basename(path)
cd = '%s; filename="%s"' % (disposition, name)
response.headers["Content-Disposition"] = cd
# Set Content-Length and use an iterable (file object)
# this way CP won't load the whole file in memory
c_len = st.st_size
bodyfile = open(path, 'rb')
# HTTP/1.0 didn't have Range/Accept-Ranges headers, or the 206 code
if cherrypy.request.protocol >= (1, 1):
response.headers["Accept-Ranges"] = "bytes"
r = http.get_ranges(cherrypy.request.headers.get('Range'), c_len)
if r == []:
response.headers['Content-Range'] = "bytes */%s" % c_len
message = "Invalid Range (first-byte-pos greater than Content-Length)"
raise cherrypy.HTTPError(416, message)
if r:
if len(r) == 1:
# Return a single-part response.
start, stop = r[0]
if stop > c_len:
stop = c_len
r_len = stop - start
response.status = "206 Partial Content"
response.headers['Content-Range'] = ("bytes %s-%s/%s" %
(start, stop - 1, c_len))
def error_page(status, message, traceback, version):
gconf = cherrypy.request.app.config.get('Global')
lconf = cherrypy.request.app.config.get('Site')
_ = cherrypy.request.i18n.gettext
bug = _("Bugs may be reported via the [github project page](https://github.com/lonvia/waymarked-trails-site/issues). Please make sure to describe what you did to produce this error and include the original message below.")
return cherrypy.request.templates.get_template('error.html').render(
g=gconf, l=lconf, bugreport=bug,
message=_(http_error.get(status[0:3], http_error[None])),
srcmsg= status + ': ' + message)
def request_namespace(k, v):
"""Attach request attributes declared in config."""
setattr(cherrypy.request, k, v)
request headers and replies appropriately.
If the response is fully buffered, and the `reply` generator actually
results in an error and sets X-Error-HTTP / X-Error-Detail headers,
converts that error back into a real HTTP error response. Otherwise
responds with the fully buffered body directly, without generator
and chunking. In other words, responses smaller than `size_limit`
are always fully buffered and replied immediately without chunking.
If the response is not fully buffered, it's guaranteed to be output
at original chunk boundaries.
Note that if this function is fed the output from `stream_compress()`
as it normally would be, the `size_limit` constrains the compressed
size, and chunk boundaries correspond to compressed chunks."""
req = cherrypy.request
res = cherrypy.response
match = [str(x) for x in (req.headers.elements('If-Match') or [])]
nomatch = [str(x) for x in (req.headers.elements('If-None-Match') or [])]
# If ETag is already set, match conditions and output without buffering.
etagval = res.headers.get('ETag', None)
if etagval:
_etag_match(res.status or 200, etagval, match, nomatch)
res.headers['Trailer'] = 'X-REST-Status'
return _etag_tail([], reply, None)
# Buffer up to size_limit bytes internally. This interally builds up the
# ETag value inside 'etag'. In case of exceptions the ETag invalidates.
# If we exceed the limit, fall back to streaming without checking ETag
# against If-Match/If-None-Match. We'll still set the ETag in the trailer
# headers, so clients which understand trailers will get the value; most
@cherrypy.expose
def ws(self):
cherrypy.log("Handler created: %s" % repr(cherrypy.request.ws_handler))
def _get_src(self):
if self.helpsrc is None:
pagedesc = cherrypy.request.app.config['Site']['help']
with codecs.open(pagedesc['source'] % 'qot', 'rb', 'utf-8') as helpfd:
self.helpsrc = yaml.safe_load(helpfd)
return self.helpsrc