def dissallow(self): cli = self.oauth_clients[cherrypy.session.get('client_id')] redr = cli.redirect_uri + '?error=access_denied' #print redr raise cherrypy.HTTPRedirect(redr)
def resp2flask(resp): """Convert an oic.utils.http_util instance to Flask.""" if isinstance(resp, Redirect) or isinstance(resp, SeeOther): code = int(resp.status.split()[0]) raise cherrypy.HTTPRedirect(resp.message, code) return resp.message, resp.status, resp.headers
def close_session(self): cherrypy.session.pop('login', None) raise cherrypy.HTTPRedirect('/')
def index(self): """ / Path response Redirects to /tvb """ raise cherrypy.HTTPRedirect('/user')
def logout(self, to=None): # pylint: disable=R0201,C0111,C0103 raise cherrypy.HTTPRedirect(self.settings["auth"]["logout_handler"] + (f"?to={to}" if to is not None else ""))
def remove_node(self, remove_node_id): with self.lock_nodes: self.client.publish("/" + remove_node_id + "/model/node/remove", str(remove_node_id), 0, False) raise cherrypy.HTTPRedirect("/node")
def _redirect(self, ident, code=303): if ident is not None and ident != self.ident: uri_params = list(self.model_args[:-1]) uri_params += [urllib2.quote(ident.encode('utf-8'), safe="")] raise cherrypy.HTTPRedirect(self.uri_fmt % tuple(uri_params), code)
def index(self): raise cherrypy.HTTPRedirect('/static/index.html')
def default(self, *tokens, **params): """ Our default handler is here to make sure we've called setup, grabbing configuration from httpd.conf, then redirecting. It also knows whether a request should be passed off to the BUI, or whether we can just report an error.""" self.setup(cherrypy.request) def request_pub_func(path): """Return the name of the publisher to be used for a given path. This function intentionally returns None for all paths.""" return None if "_themes" in tokens: # manipulate the path to remove everything up to _themes theme_index = tokens.index("_themes") cherrypy.request.path_info = "/".join( tokens[theme_index:]) # When serving theme resources we just choose the first # repository we find, which is fine since we're serving # content that's generic to all repositories, so we repo_prefix = list(repositories.keys())[0] repo = repositories[repo_prefix] depot_bui = depot_buis[repo_prefix] # use our custom request_pub_func, since theme resources # are not publisher-specific dh = sd.DepotHTTP(repo, depot_bui.cfg, request_pub_func=request_pub_func) return dh.default(*tokens[theme_index:]) elif tokens[0] not in repositories: raise cherrypy.NotFound() # Otherwise, we'll try to serve the request from the BUI. repo_prefix = tokens[0] depot_bui = depot_buis[repo_prefix] repo = repositories[repo_prefix] # when serving reources, the publisher is not used # to locate templates, so use our custom # request_pub_func dh = sd.DepotHTTP(repo, depot_bui.cfg, request_pub_func=request_pub_func) # trim the repo_prefix cherrypy.request.path_info = re.sub("^/{0}".format(repo_prefix), "", cherrypy.request.path_info) accept_lang = self.get_accept_lang(cherrypy.request, depot_bui) path = cherrypy.request.path_info.rstrip("/").lstrip("/") toks = path.split("/") pub = None # look for a publisher in the path if toks[0] in repo.publishers: path = "/".join(toks[1:]) pub = toks[0] toks = self.__strip_pub(toks, repo) cherrypy.request.path_info = "/".join(toks) # deal with users browsing directories dirs = ["", accept_lang, repo_prefix] if path in dirs: if not pub: raise cherrypy.HTTPRedirect( "/{0}/{1}/index.shtml".format( repo_prefix, accept_lang)) else: raise cherrypy.HTTPRedirect( "/{0}/{1}/{2}/index.shtml".format( repo_prefix, pub, accept_lang)) resp = face.respond(depot_bui, cherrypy.request, cherrypy.response, pub, http_depot=repo_prefix) return resp
def logout(self): self.plex_token = None self.server_name = None self.connection = None raise cherrypy.HTTPRedirect(cherrypy.url("/"))
def validate_etags(autotags=False, debug=False): """Validate the current ETag against If-Match, If-None-Match headers. If autotags is True, an ETag response-header value will be provided from an MD5 hash of the response body (unless some other code has already provided an ETag header). If False (the default), the ETag will not be automatic. WARNING: the autotags feature is not designed for URL's which allow methods other than GET. For example, if a POST to the same URL returns no content, the automatic ETag will be incorrect, breaking a fundamental use for entity tags in a possibly destructive fashion. Likewise, if you raise 304 Not Modified, the response body will be empty, the ETag hash will be incorrect, and your application will break. See :rfc:`2616` Section 14.24. """ response = cherrypy.serving.response # Guard against being run twice. if hasattr(response, "ETag"): return status, reason, msg = _httputil.valid_status(response.status) etag = response.headers.get('ETag') # Automatic ETag generation. See warning in docstring. if etag: if debug: cherrypy.log('ETag already set: %s' % etag, 'TOOLS.ETAGS') elif not autotags: if debug: cherrypy.log('Autotags off', 'TOOLS.ETAGS') elif status != 200: if debug: cherrypy.log('Status not 200', 'TOOLS.ETAGS') else: etag = response.collapse_body() etag = '"%s"' % md5(etag).hexdigest() if debug: cherrypy.log('Setting ETag: %s' % etag, 'TOOLS.ETAGS') response.headers['ETag'] = etag response.ETag = etag # "If the request would, without the If-Match header field, result in # anything other than a 2xx or 412 status, then the If-Match header # MUST be ignored." if debug: cherrypy.log('Status: %s' % status, 'TOOLS.ETAGS') if status >= 200 and status <= 299: request = cherrypy.serving.request conditions = request.headers.elements('If-Match') or [] conditions = [str(x) for x in conditions] if debug: cherrypy.log('If-Match conditions: %s' % repr(conditions), 'TOOLS.ETAGS') if conditions and not (conditions == ["*"] or etag in conditions): raise cherrypy.HTTPError(412, "If-Match failed: ETag %r did " "not match %r" % (etag, conditions)) conditions = request.headers.elements('If-None-Match') or [] conditions = [str(x) for x in conditions] if debug: cherrypy.log('If-None-Match conditions: %s' % repr(conditions), 'TOOLS.ETAGS') if conditions == ["*"] or etag in conditions: if debug: cherrypy.log('request.method: %s' % request.method, 'TOOLS.ETAGS') if request.method in ("GET", "HEAD"): raise cherrypy.HTTPRedirect([], 304) else: raise cherrypy.HTTPError(412, "If-None-Match failed: ETag %r " "matched %r" % (etag, conditions))
def discover_pms(self, server_name=None, server_addr=None, blacklist_addr=None): try: r = self.session.get( "https://plex.tv/api/resources?includeHttps=1&includeRelay=1", headers=self.full_headers, timeout=self.plextv_timeout) r.raise_for_status() except (HTTPError, Timeout) as e: if isinstance(e, HTTPError): if e.response.status_code == 401: self.plex_token = None self.server_name = None self.connection = None print("Access denied when accessing {}, going to login". format(self.server_name)) raise cherrypy.HTTPRedirect(cherrypy.url("/token")) raise content = xmltodict.parse(r.content, attr_prefix="", force_list=("Device", "Connection")) servers = OrderedDict() # import pprint # pprint.pprint(content) use_connection = None for device in content["MediaContainer"].get("Device", []): if device["provides"] != "server" or not bool(device["presence"]): continue public_address_matches = device["publicAddressMatches"] == "1" https_required = device["httpsRequired"] == "1" for connection in device["Connection"]: connection["unavailable"] = False if not public_address_matches and connection["local"] == "1": continue elif https_required and connection["protocol"] != "https": continue if device["name"] not in servers: servers[device["name"]] = { "connections": [], "owned": device["owned"] == "1", "publicAddress": device["publicAddress"], "publicAddressMatches": public_address_matches } if blacklist_addr and connection["uri"] in blacklist_addr: print("{}: {} on blacklist, skipping".format( mask_str(device["name"]), mask_url(connection["uri"]))) connection["unavailable"] = True continue servers[device["name"]]["connections"].append(connection) if server_name and server_name == device["name"]: if server_addr and connection["uri"] == server_addr: use_connection = connection elif server_addr and server_addr == "relay" and connection.get( "relay") == "1": use_connection = connection elif not server_addr: use_connection = connection if use_connection: break if server_name and use_connection: self.server_name = server_name self.connection = use_connection server_addr = use_connection["uri"] print("Server set to: {}, {}".format(mask_str(server_name), mask_url(server_addr))) print("Verifying {}: {}".format(mask_str(server_name), mask_url(server_addr))) try: self.session.get(self.server_addr + "servers", headers=self.full_headers, **self.req_defaults) except HTTPError as e: if e.response.status_code == 401: self.plex_token = None self.server_name = None self.connection = None print("Access denied when accessing {}, going to login". format(mask_str(self.server_name))) raise cherrypy.HTTPRedirect(cherrypy.url("/token")) except Timeout as e: if not blacklist_addr: blacklist_addr = [] blacklist_addr.append(server_addr) print("{}: Blacklisting {} due to: {!r}".format( mask_str(server_name), mask_url(server_addr), type(e))) return self.discover_pms(server_name=server_name, server_addr=None, blacklist_addr=blacklist_addr) print("Verified {}: {}".format(mask_str(server_name), mask_url(server_addr))) self.plugin = None message("Successfully connected to {}".format(self.server_name), "SUCCESS") raise cherrypy.HTTPRedirect(cherrypy.url("/")) return servers
def plex_token(self): token = cherrypy.session.get("plex_token") if not token: print("No token, redirecting") raise cherrypy.HTTPRedirect(cherrypy.url("/token")) return token
def default(self, *args, **kargs): #cherrypy.session['admin'] = False #authentication is a bit tricky here, because we have 3 types. # 1) multiplexed clients that carry the user and associated authentication in an Authorization header # 2) Password base apps that login via a ('model','appname','password') tuple # 3) Web clients that might be using this to add or delete apps for a user. These can have a local session. logging.debug('args %s, kargs %s', repr(args), repr(kargs)) access_tokens = filedict.FileDict(filename=self.access_tokens_filename) logging.debug('websession: %s, auth: %s', cherrypy.session.get('webSession'), cherrypy.request.headers.has_key('Authorization')) pargs = None try: cl = cherrypy.request.headers['Content-Length'] jsonobj = cherrypy.request.body.read(int(cl)) pargs = json.loads(jsonobj) except: pargs = kargs logging.debug('pargs %s', repr(pargs)) if 'Authorization' in cherrypy.request.headers: # we're from a web client using oauth. access_token = cherrypy.request.headers['Authorization'].split()[1] #logging.debug( 'access_tokens %s', access_tokens ) logging.debug('access_token %s', repr(access_token)) if access_token not in access_tokens: raise cherrypy.HTTPError(401, 'Incorrect access token') #print 'token',self.access_tokens[access_token] now = time.time() if now > access_tokens[access_token]['expires']: logging.debug('expired %s', access_token) raise cherrypy.HTTPError(401, 'Expired access token') usr = access_tokens[access_token]['userid'] logging.debug('OAUTH: USER: %s, BEARER: %s', usr, access_token) model = usr if 'model' in pargs: model = pargs['modelname'] u = active.Access(model=model, modeldir=self.modeldir, user=usr) apps = u.listapps() if access_tokens[access_token]['client_id'] not in apps: logging.debug('client for access token not in model %s, %s', access_token, access_tokens[access_token]['client_id']) raise cherrypy.HTTPError( 401, 'client for access token not in model') elif cherrypy.session.get('webSession'): # we're a web session if not cherrypy.session.get('user'): cherrypy.session['target_url'] = args[0] raise cherrypy.HTTPRedirect('/login') usr = cherrypy.session.get('user') logging.debug('WEB: USER: %s', usr) model = usr elif pargs: # are we from an app? m = pargs.get('modelname', '-') usr = pargs.get('user', '') if m == '-': m = usr con = pargs.get('context', None) u = active.Access(model=m, modeldir=self.modeldir, user=usr) if not u.checkpermission( context=con, app=usr, permname=args[0], permval=True): raise cherrypy.HTTPError(401, 'Incorrect authentication') model = m logging.debug('APP: app: %s', usr) else: raise cherrypy.HTTPError(401, 'Incorrect authentication') try: result = False if args[0] == 'mkmodel': if not os.path.exists(os.path.join(self.modeldir, model)): mkmodel(model=model, mfile='modeldefs/empty.prod.mdef', modeldir=self.modeldir, user=usr['id'], description=pargs['description']) result = True else: um = active.Access(model=model, modeldir=self.modeldir, user=usr) if args[0] == 'access': result = True elif args[0] == 'tell': result = um.tell(context=pargs['context'], componentid=pargs['componentid'], evidence=base.Evidence(**pargs['evidence'])) elif args[0] == 'ask': reslist = um.ask(context=pargs['context'], view=pargs['view'], resolver=pargs['resolver'], \ showcontexts=pargs['showcontexts']) if pargs['showcontexts']: cobjlist, contexts, theviews, thesubs = reslist cobjlist = [c.__dict__ for c in cobjlist] for c in cobjlist: if c["evidencelist"]: c["evidencelist"] = [e for e in c["evidencelist"]] newviews = {} if theviews != None: for vname, v in theviews.items(): newviews[vname] = v.__dict__ else: newviews = None reslist = [cobjlist, contexts, newviews, thesubs] else: reslist = [c.__dict__ for c in reslist] for c in reslist: if c["evidencelist"]: c["evidencelist"] = [e for e in c["evidencelist"]] result = reslist elif args[0] == 'subscribe': result = um.subscribe(context=pargs['context'], view=pargs['view'], subscription=pargs['subscription']) elif args[0] == 'delete_sub': result = um.delete_sub(context=pargs['context'], componentid=pargs['componentid'], subname=pargs['subname']) elif args[0] == 'list_subs': result = um.list_subs(context=pargs['context'], componentid=pargs['componentid']) elif args[0] == 'export_model': result = um.export_model(context=pargs['context'], resolver=pargs['resolver']) elif args[0] == 'import_model': result = um.import_model(context=pargs['context'], partial_model=pargs['partial_model']) elif args[0] == 'set_goals': result = um.set_goals(context=pargs['context'], componentid=pargs['componentid'], goals=pargs['goals']) elif args[0] == 'registerapp': result = um.registerapp(app=pargs['app'], desc=pargs['description'], password=pargs['apppassword'], realm=pargs['realm']) elif args[0] == 'deleteapp': result = um.deleteapp(app=pargs['app']) elif args[0] == 'getpermission': result = um.getpermission(context=pargs['context'], componentid=pargs['componentid'], app=pargs['app']) elif args[0] == 'setpermission': result = um.setpermission(context=pargs['context'], componentid=pargs['componentid'], app=pargs['app'], permissions=pargs['permissions']) elif args[0] == 'listapps': result = um.listapps() elif args[0] == 'mkcomponent': comp = base.Component(**pargs["componentobj"]) result = um.mkcomponent(pargs["context"], comp) elif args[0] == 'delcomponent': result = um.delcomponent(pargs["context"], pargs["componentid"]) elif args[0] == 'delcontext': result = um.delcontext(pargs["context"]) elif args[0] == 'setresolver': result = um.setresolver(pargs["context"], pargs["componentid"], pargs["resolver"]) elif args[0] == 'getresolvers': result = um.getresolvers() elif args[0] == 'mkview': viewobj = base.View(**pargs["viewobj"]) result = um.mkview(pargs["context"], viewobj) elif args[0] == 'delview': result = um.delview(pargs["context"], pargs["viewid"]) elif args[0] == 'mkcontext': contextobj = base.Context(**pargs["contextobj"]) result = um.mkcontext(pargs["context"], contextobj) elif args[0] == 'getcontext': result = um.getcontext(pargs["context"], pargs["getsize"]) # Repackage result code with error values IF there is a version string. if 'version' in pargs: new_result = {} new_result["result"] = "ok" new_result["val"] = result result = new_result except Exception as e: logging.info("Exception: %s", e) traceback.print_exc() if 'version' in pargs: new_result = {} new_result["val"] = [ e.__class__.__name__, e.__dict__.copy(), cPickle.dumps(e) ] new_result["result"] = "error" result = new_result else: result = False return json.dumps(result)
def index(self): raise cherrypy.HTTPRedirect("show?rid=14:7015")
def download(self, file, offset=0, headers=True, endByte=None, contentDisposition=None, extraParameters=None): """ Use the appropriate assetstore adapter for whatever assetstore the file is stored in, and call downloadFile on it. If the file is a link file rather than a file in an assetstore, we redirect to it. :param file: The file to download. :param offset: The start byte within the file. :type offset: int :param headers: Whether to set headers (i.e. is this an HTTP request for a single file, or something else). :type headers: bool :param endByte: Final byte to download. If ``None``, downloads to the end of the file. :type endByte: int or None :param contentDisposition: Content-Disposition response header disposition-type value. :type contentDisposition: str or None :type extraParameters: str or None """ events.trigger('model.file.download.request', info={ 'file': file, 'startByte': offset, 'endByte': endByte }) auditLogger.info('file.download', extra={ 'details': { 'fileId': file['_id'], 'startByte': offset, 'endByte': endByte, 'extraParameters': extraParameters } }) if file.get('assetstoreId'): try: fileDownload = self.getAssetstoreAdapter(file).downloadFile( file, offset=offset, headers=headers, endByte=endByte, contentDisposition=contentDisposition, extraParameters=extraParameters) def downloadGenerator(): for data in fileDownload(): yield data if endByte is None or endByte >= file['size']: events.trigger('model.file.download.complete', info={ 'file': file, 'startByte': offset, 'endByte': endByte, 'redirect': False }) return downloadGenerator except cherrypy.HTTPRedirect: events.trigger('model.file.download.complete', info={ 'file': file, 'startByte': offset, 'endByte': endByte, 'redirect': True }) raise elif file.get('linkUrl'): if headers: events.trigger('model.file.download.complete', info={ 'file': file, 'startByte': offset, 'endByte': endByte, 'redirect': True }) raise cherrypy.HTTPRedirect(file['linkUrl']) else: endByte = endByte or len(file['linkUrl']) def stream(): yield file['linkUrl'][offset:endByte] if endByte >= len(file['linkUrl']): events.trigger('model.file.download.complete', info={ 'file': file, 'startByte': offset, 'endByte': endByte, 'redirect': False }) return stream else: raise Exception('File has no known download mechanism.')
def sendMessage( self, destination, message, markdown): # this function calls other people's receiveMessage # look up the 'destination' user in database and retrieve his corresponding ip address and port c = sqlite3.connect(DB_STRING) cur = c.cursor() cur.execute("SELECT ip, port FROM user_string WHERE username=?", [destination]) values_tuple = cur.fetchall() ip = values_tuple[0][0] port = values_tuple[0][1] if not values_tuple: # if either ip and port is empty return "3: Client Currently Unavailable" else: try: # try to send them a message with markdown argument output_dict = { "sender": cherrypy.session.get('username'), "message": message, "destination": destination, "stamp": int(time.time()), "markdown": markdown } postdata = json.dumps(output_dict) # encode to JSON req = urllib2.Request( "http://" + ip + ":" + port + "/receiveMessage", postdata, {'Content-Type': 'application/json'}) try: # just in case they give an abnormal response, do a try except response = urllib2.urlopen(req).read() if ( response.find('0') != -1 ): # successfully sent message if '0' is found in return print "Markdown arg message sent to client: " + destination with sqlite3.connect( DB_STRING ) as c: # place our sent message in our table too c.execute( "INSERT INTO msg(sender, destination, msg, stamp, markdown) VALUES (?,?,?,?,?)", [ cherrypy.session.get('username'), destination, message, int(time.time()), int(markdown) ]) else: return "4: Database Error" except: return "5: Timeout Error" except: # if it doesn't work, try to send them a message without markdown argument output_dict = { "sender": cherrypy.session.get('username'), "message": message, "destination": destination, "stamp": int(time.time()) } postdata = json.dumps(output_dict) req = urllib2.Request( "http://" + ip + ":" + port + "/receiveMessage", postdata, {'Content-Type': 'application/json'}) try: response = urllib2.urlopen(req).read() if (response.find('0') != -1): # successful print "Non-markdown arg message sent to client: " + destination with sqlite3.connect(DB_STRING) as c: c.execute( "INSERT INTO msg(sender, destination, msg, stamp) VALUES (?,?,?,?)", # no markdown arg [ cherrypy.session.get('username'), destination, message, int(time.time()) ]) else: return "4: Database Error" except: return "5: Timeout Error" raise cherrypy.HTTPRedirect("/home")
def POST(self, playerName, page, selectedTeam): try: connection = functions.Worker() playerTagObject = PlayerTag() playerTagObject.SetPlayerTag(playerName) team = connection.GetTeams(playerTagObject) selectedTeamObject = Team() selectedTeamObject.SetTeamName(selectedTeam) except: template = jinja_environment.get_template('templates/teams.html') return template.render({ 'playerTagHeader': playerTagObject.GetPlayerTag(), 'the_title': 'Team Menu', 'teams': team, 'errorMatch': ("Unexpected error:", sys.exc_info()[1]) }) #If friend request option selected if (page == 'createnewteam'): raise cherrypy.HTTPRedirect("/createnewteam/", 302) #If pending Request option selected elif (page == 'joinateam'): teamNames = connection.GetAllTeams() for item in team: if (teamNames.__contains__(item)): teamNames.remove(item) if (teamNames.__len__() > 0): raise cherrypy.HTTPRedirect("/joinateam/", 302) else: template = jinja_environment.get_template( 'templates/teams.html') return template.render({ 'the_title': 'Join A Team', 'errorMatch': 'No Teams Available!', 'teams': team, 'playerTagHeader': playerTagObject.GetPlayerTag(), }) #If Team set up is selected else: teamDB = connection.FindTeam(selectedTeamObject) if (teamDB == ""): template = jinja_environment.get_template( 'templates/teams.html') return template.render({ 'the_title': 'Manage A Team', 'errorMatch': 'No Teams Available!', 'teams': team, 'playerTagHeader': playerTagObject.GetPlayerTag(), }) else: cherrypy.session['selectedTeam'] = selectedTeam raise cherrypy.HTTPRedirect("/manageateam/", 302)
def update_app(self, stop_app_model): with self.lock_apps: raise cherrypy.HTTPRedirect("/app")
def cari(self): if cherrypy.session.get('data_user'): tmpl = env.get_template('cari_tulisan.html') return tmpl.render(data_user=cherrypy.session.get('data_user')) else: raise cherrypy.HTTPRedirect('/')
def redirect(self, url): raise cherrypy.HTTPRedirect(url)
def treat_url(): reqpath = cherrypy.request.path_info webroot = cherrypy.config.get("webroot") # Clear the thread storage. cherrypy.thread_data.target = None cherrypy.thread_data.do_auth = True # If the request path is blank, redirect to /. if reqpath == "": raise cherrypy.HTTPRedirect("/") # Compute "parallel" path component lists based on the web root and the # disk root. if reqpath == "/": reqpathcomp = [] pathcomp = [webroot] else: # Split the request path into path components, omitting the leading # slash. reqpathcomp = reqpath[1:].split("/") # Compute the disk path the URL corresponds to. # # First check to see whether the path is absolute (i.e. rooted at # webroot) or in a user home directory. if reqpathcomp[0][0] == "~" and len(reqpathcomp[0]) > 1: # Only treat this component as a home directory if there is # actually text following the tilde (rather than making the server # serve files from the home directory of whatever user account it # is using to run). pathcomp = [ os.path.expanduser(reqpathcomp[0]) + os.path.sep + "tangelo_html" ] + reqpathcomp[1:] else: pathcomp = [webroot] + reqpathcomp # Save the request path and disk path components in the thread storage, # slightly modifying the request path if it refers to an absolute path # (indicated by being one element shorter than the disk path). if len(reqpathcomp) == len(pathcomp) - 1: reqpathcomp_save = [""] + reqpathcomp elif len(reqpathcomp) == len(pathcomp): reqpathcomp_save = ["/" + reqpathcomp[0]] + reqpathcomp[1:] else: raise RuntimeError("reqpathcomp and pathcomp lengths are wonky") # If the path represents a directory and has a trailing slash, remove it # (this will make the auth update step easier). if (len(reqpathcomp_save) > 1 and reqpathcomp_save[-1] == "" or pathcomp[-1] == ""): assert reqpathcomp_save[-1] == "" and pathcomp[-1] == "" reqpathcomp_save = reqpathcomp_save[:-1] pathcomp_save = pathcomp[:-1] else: pathcomp_save = pathcomp cherrypy.thread_data.reqpathcomp = reqpathcomp_save cherrypy.thread_data.pathcomp = pathcomp_save # If pathcomp has more than one element, fuse the first two together. This # makes the search for a possible service below much simpler. if len(pathcomp) > 1: pathcomp = [pathcomp[0] + os.path.sep + pathcomp[1]] + pathcomp[2:] # Form an actual path string. path = os.path.sep.join(pathcomp) # If the path is a directory, check for a trailing slash. If missing, # perform a redirect to the path WITH the trailing slash. Otherwise, check # for an index.html file in that directory; if found, perform an internal # redirect to that file. Otherwise, leave the path alone - it now # represents a request for a directory listing. # # If instead the path isn't a directory, check to see if it's a regular # file. If it is, save the path in thread local storage - this will let # the handler very quickly serve the file. # # If it is not a regular file, then check to see if it is a python service. # # Finally, if it is none of the above, then indicate a 404 error. if os.path.isdir(path): if reqpath[-1] != "/": raise cherrypy.HTTPRedirect(reqpath + "/") elif os.path.exists(path + os.path.sep + "index.html"): raise cherrypy.InternalRedirect(reqpath + "index.html") else: cherrypy.thread_data.target = {"type": "dir", "path": path} elif os.path.exists(path): # Don't serve Python files (if someone really wants to serve the program # text, they can create a symlink with a different file extension and # that will be served just fine). if len(path) > 3 and path[-3:] == ".py": cherrypy.thread_data.target = {"type": "restricted", "path": path} else: # Also do not serve config files that match up to Python files. if (len(path) > 5 and path[-5:] == ".json" and os.path.exists(path[:-5] + ".py")): cherrypy.thread_data.target = { "type": "restricted", "path": path } else: cherrypy.thread_data.target = {"type": "file", "path": path} else: service_path = None pargs = None # for i, comp in enumerate(pathcomp): for i in range(len(pathcomp)): service_path = os.path.sep.join(pathcomp[:(i + 1)]) + ".py" if os.path.exists(service_path): pargs = pathcomp[(i + 1):] break if pargs is None: cherrypy.thread_data.target = {"type": "404", "path": path} cherrypy.thread_data.do_auth = False else: cherrypy.thread_data.target = { "type": "service", "path": service_path, "pargs": pargs }
def login(self): # pylint: disable=R0201,C0111 raise cherrypy.HTTPRedirect(self.settings["auth"]["login_handler"])
def modify(self, user=None, **params): """ modify user page """ self._check_auth(must_admin=True) is_admin = self._check_admin() if cherrypy.request.method.upper() == 'POST': params = self._parse_params(params) self._modify(params) self._add_notification("User modified") try: referer = cherrypy.request.headers['Referer'] except: referer = '/' raise cherrypy.HTTPRedirect(referer) graph = {} for r in self.roles.graph: s = list(self.roles.graph[r]['sub_roles']) p = list(self.roles.graph[r]['parent_roles']) graph[r] = {'sub_roles': s, 'parent_roles': p} graph_js = json.dumps(graph, separators=(',', ':')) display_names = {} for r in self.roles.flatten: display_names[r] = self.roles.flatten[r]['display_name'] if user is None: cherrypy.response.status = 400 return self.temp['error.tmpl'].render(is_admin=is_admin, alert='warning', message="No user requested") user_attrs = self._get_user(user) if user_attrs == {}: cherrypy.response.status = 400 return self.temp['error.tmpl'].render(is_admin=is_admin, alert='warning', message="User '" + user + "' does not exist") tmp = self._get_roles(user) user_roles = tmp['roles'] standalone_groups = tmp['unusedgroups'] roles_js = json.dumps(display_names, separators=(',', ':')) key = self.attributes.get_key() try: form = self.temp['form.tmpl'].render( attributes=self.attributes.attributes, values=self._escape(user_attrs, 'attr_list'), modify=True, keyattr=key, autofill=False) roles = self.temp['roles.tmpl'].render( roles=self.roles.flatten, graph=self.roles.graph, graph_js=graph_js, roles_js=roles_js, current_roles=user_roles, ) glued_template = self.temp['modify.tmpl'].render( form=form, roles=roles, is_admin=is_admin, standalone_groups=self._escape(standalone_groups, 'lonely_groups'), backends_display_names=self.backends_display_names, custom_js=self.custom_js, notifications=self._empty_notification(), ) except NameError: raise TemplateRenderError( exceptions.text_error_template().render()) return glued_template
adapter = ABCAdapter.build_adapter(algorithm) if self._is_compatible(algorithm, datatype_group_gid): try: pse_context = adapter.prepare_parameters( datatype_group_gid, back_page, color_metric, size_metric) pse_context.prepare_individual_jsons() return pse_context except LaunchException, ex: error_msg = urllib.quote(ex.message) else: error_msg = urllib.quote( "Discrete PSE is incompatible (most probably due to result size being too large)." ) name = urllib.quote(adapter._ui_name) raise cherrypy.HTTPRedirect(REDIRECT_MSG % (name, error_msg)) @cherrypy.expose @handle_error(redirect=True) @using_template('visualizers/pse_isocline/burst_preview') @check_user def draw_isocline_exploration(self, datatype_group_gid, width=None, height=None): if width is not None: width = int(width) if height is not None: height = int(height)
def _check_auth(self, must_admin, redir_login=True): """ check if a user is autheticated and, optionnaly an administrator if user not authentifaced -> redirection to login page (with base64 of the originaly requested page (redirection after login) if user authenticated, not admin and must_admin enabled -> 403 error @boolean must_admin: flag "user must be an administrator to access this page" @rtype str: login of the user """ if self.auth_mode == 'none': return 'anonymous' username = self._check_session() if cherrypy.request.query_string == '': qs = '' else: qs = '?' + cherrypy.request.query_string # base64 of the requested URL b64requrl = base64.b64encode(cherrypy.url() + qs) if not username: # return to login page (with base64 of the url in query string if redir_login: raise cherrypy.HTTPRedirect( "/signin?url=%(url)s" % {'url': b64requrl}, ) else: raise cherrypy.HTTPError( "403 Forbidden", "You must be logged in to access this ressource.", ) if 'connected' not in cherrypy.session \ or not cherrypy.session['connected']: if redir_login: raise cherrypy.HTTPRedirect( "/signin?url=%(url)s" % {'url': b64requrl}, ) else: raise cherrypy.HTTPError( "403 Forbidden", "You must be logged in to access this ressource.", ) if cherrypy.session['connected'] and \ not cherrypy.session['isadmin']: if must_admin: # user is not an administrator, so he gets 403 Forbidden raise cherrypy.HTTPError( "403 Forbidden", "You are not allowed to access this resource.", ) else: return username if cherrypy.session['connected'] and \ cherrypy.session['isadmin']: return username else: if redir_login: raise cherrypy.HTTPRedirect( "/signin?url=%(url)s" % {'url': b64requrl}, ) else: raise cherrypy.HTTPError( "403 Forbidden", "You must be logged in to access this ressource.", )
def new_3(self, name, trustee=None, public_key=None, private_key=None, voting_starts_at=None, voting_ends_at=None, **kw): """ Create the new election. trustees is a JSON list """ # we need a list of admins, or at least a public key if not trustee and not public_key: self.error('Need a list of trustees or a public key') election = do.Election() # hard-wire the type for now, we only have one type of election election.election_type = 'homomorphic' # basic election parameters election.name = name election.admin, election.api_client = self.user( ), do.APIClient.get_by_consumer_key(Controller.api_client()) election.voting_starts_at = utils.string_to_datetime(voting_starts_at) election.voting_ends_at = utils.string_to_datetime(voting_ends_at) # serialize the public key to JSON and store it if it was sent if public_key and public_key != "": pk = algs.EGPublicKey.from_dict(utils.from_json(public_key)) election.public_key_json = utils.to_json(pk.to_dict()) # the private key can be stored by the server if private_key and private_key != "": sk = algs.EGSecretKey.from_dict(utils.from_json(private_key)) election.private_key_json = utils.to_json(sk.to_dict()) ## FIXME: transaction! election.save() # go through the trustees if trustee: for t in trustee: if t.strip() == "": continue # create the keyshare keyshare = do.KeyShare() keyshare.parent = election keyshare.election = election keyshare.email = t keyshare.generate_password() keyshare.save() # send out the email self.email_trustees_2( election, 'You have been designated as a trustee of the Helios Election "%s".' % election.name) # user or api_client? if election.admin: raise cherrypy.HTTPRedirect("./%s/view" % str(election.election_id)) else: return str(election.election_id)
def GET(self, var=None, code='', user_id=None, date_time=None, time_from=None, time_to=None, interval=None): global client_id global client_secret ################################################################## # Endpoint for giving user consent to use their fitbit data. # ################################################################## if (var == 'fitbit-permission'): params = { 'client_id': client_id, 'response_type': 'code', 'scope': 'activity heartrate location nutrition profile settings sleep social weight', 'redirect_uri': 'https://riski.business/fitbit-callback' } url = 'https://www.fitbit.com/oauth2/authorize?' raise cherrypy.HTTPRedirect(url + urllib.parse.urlencode(params)) ################################################################## # Callback from fitbit servers after user has given consent. # ################################################################## # To do : scope checks. if (var == 'fitbit-callback'): cnx = mysql.connector.connect(user=user, database='fitbittokens', password=password) cursor = cnx.cursor(buffered=True) request_params = { 'grant_type': 'authorization_code', 'code': code, 'redirect_uri': 'https://riski.business/fitbit-callback', 'client_id': client_id, } url = 'https://api.fitbit.com/oauth2/token' try: cres = (client_id + ":" + client_secret).encode() headers = { 'Content-type': 'application/x-www-form-urlencoded', 'Authorization': 'Basic ' + base64.b64encode(cres).decode() } request = Request( url, urllib.parse.urlencode(request_params).encode(), headers=headers) response = json.loads(urlopen(request).read().decode()) response['datetime'] = datetime.now() dbresponse = dbhandler.addTokens(response, cnx, cursor) cursor.close() cnx.close() return dbresponse except urllib.error.HTTPError as e: return err.fail(str(e.code)) except urllib.error.URLError as e: return err.fail(str(e.code)) if (var == 'eyetrack' and user_id is not None and date_time is not None): cnx = mysql.connector.connect(user=user, database='fitbittokens', password=password) cursor = cnx.cursor(buffered=True) try: params = cherrypy.request.params data = { "user_id": params.get("user_id"), "datetime": params.get("date_time") } returni = dbhandler.getTrackerdata(data, cnx, cursor) return returni except Exception as e: return err.fail(str(e)) if (var == 'processed' and user_id is not None and time_from is not None and time_to is not None and interval is not None): cnx = mysql.connector.connect(user=user, database='fitbittokens', password=password) cursor = cnx.cursor(buffered=True) try: returni = dbhandler.getProcessed(user_id, time_from, time_to, interval, cnx, cursor) return returni except Exception as e: return err.fail(str(e))
def index(self, num=None): if cherrypy.session.get('login', None) == 'login': raise cherrypy.HTTPRedirect('/database/') else: userForm = Template(file=os.path.join(os.curdir, 'index.tmpl')) return str(userForm)
def logged_in(self, code): """ Step 2 of the oauth dance. At this point Google has said this is a known user. We then go and get more user info about them from google, save the info in a persistant store, create a model if none exists, and then ask them if they're happy to let the client they're using access personis on their behalf. (Accessed by the user with a web browser redirected from /authorized) """ flow = cherrypy.session.get('flow') if not flow: raise IOError() credentials = flow.step2_exchange( cherrypy.request.params #, http = httplib2.Http( # proxy_info = httplib2.ProxyInfo(proxy_type=httplib2.socks.PROXY_TYPE_HTTP_NO_TUNNEL, proxy_host='www-cache.it.usyd.edu.au', proxy_port=8000) # ) ) http = httplib2.Http() http = credentials.authorize(http) cjson = credentials.to_json() cjson = json.loads(cjson) content = http.request( 'https://www.googleapis.com/oauth2/v1/userinfo?access_token=' + cjson['access_token']) #print 'content', content try: usr = json.loads(content[1]) user = usr['email'].split('@')[0].replace('.', '').lower() cherrypy.session['user'] = user except: logging.debug('exception on usr %s', content[1]) raise IOError() logging.debug('loggedin session id %s', cherrypy.session.id) if not 'picture' in usr: if 'gender' in usr and usr['gender'].lower() == 'female': usr['picture'] = 'http://upload.wikimedia.org/wikipedia/commons/thumb/e/ec/Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg/161px-Mona_Lisa%2C_by_Leonardo_da_Vinci%2C_from_C2RMF_retouched.jpg' else: usr['picture'] = 'http://www.lacasadeviena.com/wp-content/uploads/2012/06/magritte-sonofman1-300x362.jpg' # if no model for user, create one. if not os.path.exists(os.path.join(self.modeldir, user)): mf = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'modeldefs/user.prod.mdef') mkmodel(model=user, mfile=mf, modeldir=self.modeldir, user=user) um = active.Access(model=user, modeldir=self.modeldir, user=user) ev = base.Evidence(source="Create_Model", evidence_type="explicit", value=usr['given_name']) um.tell(context=["Personal"], componentid='firstname', evidence=ev) ev = base.Evidence(source="Create_Model", evidence_type="explicit", value=usr['family_name']) um.tell(context=["Personal"], componentid='lastname', evidence=ev) if 'gender' in usr: ev = base.Evidence(source="Create_Model", evidence_type="explicit", value=usr['gender']) um.tell(context=["Personal"], componentid='gender', evidence=ev) ev = base.Evidence(source="Create_Model", evidence_type="explicit", value=usr['email']) um.tell(context=["Personal"], componentid='email', evidence=ev) ev = base.Evidence(source="Create_Model", evidence_type="explicit", value=usr['id']) um.tell(context=["Personal"], componentid='gid', evidence=ev) ev = base.Evidence(source="Create_Model", evidence_type="explicit", value=usr['picture']) um.tell(context=["Personal"], componentid='picture', evidence=ev) reslist = um.ask(context=["Personal"], view=['firstname', 'email']) util.printcomplist(reslist) um = active.Access(model=user, modeldir=self.modeldir, user=user) # if we're here from a local url, just redirect. no need to allow. if cherrypy.session.get('webSession'): cherrypy.session['um'] = um raise cherrypy.HTTPRedirect(cherrypy.session['target_url']) # if the app is already registered, it's ok. apps = um.listapps() logging.debug('apps: %s, clientid: %s', apps, cherrypy.session.get('client_id')) if cherrypy.session.get('client_id') in apps: raise cherrypy.HTTPRedirect('/allow') #otherwise, ask yes/no cli = self.oauth_clients[cherrypy.session['client_id']] base_path = os.path.dirname(os.path.abspath(__file__)) src = open(os.path.join(base_path, 'html', 'appQuery.html'), 'r').read() stream = src.format(name=usr['given_name'], app=cli['friendly_name'], icon=cli['icon'], picture=usr['picture']) return stream