def PUT(self, id, setting): if setting not in self.Settings: web.notfound() return None try: configData = json.loads(web.data()) id = int(id) vm = model.getVM(web.ctx.veerezoDB, id) if vm['user'] != web.ctx.username: web.forbidden() return None except (ValueError, KeyError): web.notfound() return None fn = '_put' + self.Settings[setting] f = getattr(self, fn) try: f(id, vm, configData) except ValueError as e: web.badrequest() return {'error': 'ValueError: {0}'.format(e.message)} web.nocontent() return None
def authenticate(self, username, password): if not config.SECURITY: return True if users.users[username] == password: return True else: web.forbidden() return False
def POST(self, channel_id, channel): """ Handles channel creation, editing, deletion, configuration and user permissions. """ form = web.input() current_user = User.get(self.session['user']['id']) try: if form.action == 'reset-config': if form.all == "true": for param_id, param_attrs in channel.plugin.channels_params.items( ): read, write = channel.get_access_rights_for( param_id, current_user) if read and write: channel.plugin_config.pop(param_id, None) # Force SQLObject update channel.plugin_config = channel.plugin_config else: param_id = form["reset-param-id"] if param_id not in channel.plugin.channels_params.keys(): raise ImmediateFeedback(form.action, "invalid_param_id") read, write = channel.get_access_rights_for( param_id, current_user) if read and write: channel.plugin_config.pop(param_id, None) else: raise web.forbidden() # Force SQLObject update channel.plugin_config = channel.plugin_config channel.syncUpdate() logger.info('params of channel ' + channel.name + ' reset by ' + current_user.log_name) elif form.action == 'reset-cache-config': if not current_user.super_admin: raise web.forbidden() form.name = channel.name channel.cache_activated = None channel.cache_validity = None add_feedback('general', 'channel_cache_reset') logger.info( 'the cache configuration of channel %s has been reset by user %s', channel.name, current_user.log_name) elif form.action == 'reset-filtering-config': if not current_user.super_admin: raise web.forbidden() form.name = channel.name channel.keep_noncomplying_capsules = None add_feedback('general', 'channel_filtering_reset') logger.info( 'the capsule filtering configuration of channel %s has been reset by user %s', channel.name, current_user.log_name) add_feedback('general', 'channel_edited') add_feedback(form.action, 'ok') form.name = channel.name except ImmediateFeedback: if channel is not None and channel.enabled: form.enabled = 'on' store_form(form) raise web.seeother('/channels/%d' % channel.id)
def _parse_lti_data(self, courseid, taskid): """ Verify and parse the data for the LTI basic launch """ post_input = web.webapi.rawinput("POST") self.logger.debug('_parse_lti_data:' + str(post_input)) try: course = self.course_factory.get_course(courseid) except exceptions.CourseNotFoundException as ex: raise web.notfound(str(ex)) try: test = LTIWebPyToolProvider.from_webpy_request() validator = LTIValidator(self.database.nonce, course.lti_keys()) verified = test.is_valid_request(validator) except Exception: self.logger.exception("...") self.logger.info("Error while validating LTI request for %s", str(post_input)) raise web.forbidden(_("Error while validating LTI request")) if verified: self.logger.debug('parse_lit_data for %s', str(post_input)) user_id = post_input["user_id"] username = post_input.get("ext_user_username", "") if username == "": username = post_input.get("lis_person_sourcedid", "") roles = post_input.get("roles", "Student").split(",") realname = self._find_realname(post_input) email = post_input.get("lis_person_contact_email_primary", "") lis_outcome_service_url = post_input.get("lis_outcome_service_url", None) outcome_result_id = post_input.get("lis_result_sourcedid", None) consumer_key = post_input["oauth_consumer_key"] if course.lti_send_back_grade(): if lis_outcome_service_url is None or outcome_result_id is None: self.logger.info('Error: lis_outcome_service_url is None but lti_send_back_grade is True') raise web.forbidden(_("In order to send grade back to the TC, UNCode needs the parameters lis_outcome_service_url and " "lis_outcome_result_id in the LTI basic-launch-request. Please contact your administrator.")) else: lis_outcome_service_url = None outcome_result_id = None tool_name = post_input.get('tool_consumer_instance_name', 'N/A') tool_desc = post_input.get('tool_consumer_instance_description', 'N/A') tool_url = post_input.get('tool_consumer_instance_url', 'N/A') context_title = post_input.get('context_title', 'N/A') context_label = post_input.get('context_label', 'N/A') session_id = self.user_manager.create_lti_session(user_id, roles, username, realname, email, courseid, taskid, consumer_key, lis_outcome_service_url, outcome_result_id, tool_name, tool_desc, tool_url, context_title, context_label) loggedin = self.user_manager.attempt_lti_login() return session_id, loggedin else: self.logger.info("Couldn't validate LTI request") raise web.forbidden(_("Couldn't validate LTI request"))
def __call__(self, method): if not self.config.hooks.pre(): forbidden() # TODO: customize else: return { 'GET': self._GET, 'PUT': self._PUT, 'POST': self._POST, 'DELETE': self._DELETE }.get(method, internalerror)()
def protect(what, *a, **kw): try: return what(*a, **kw) or "" except (IOError, OSError) as e: if e.errno in [EACCES, ENOTDIR]: forbidden() else: internalerror() return str(e) except CalledProcessError as e: internalerror() return str(e)
def GET(self, id): try: id = int(id) sshkey = model.getSSHKey(web.ctx.veerezoDB, id) if sshkey['user'] != web.ctx.username: web.forbidden() return None return sshkey except (KeyError, ValueError): web.notfound() return None
def GET(self, id): try: id = int(id) network = model.getNetwork(web.ctx.veerezoDB, id) if network['user'] != web.ctx.username: web.forbidden() return None return network except (ValueError, KeyError): web.notfound() return None
def new(*args): uri = web.ctx.env.get('REQUEST_URI') key = web.ctx.env.get('HTTP_X_API_KEY') log = lambda status: db.insert('access_log', description=uri, date=datetime.now(), key=key, status=status) if not is_valid_key(key): log('invalid key') web.badrequest() elif exist_key(key): log('access') return fn(*args) else: log('key not found') web.forbidden()
def POST(self): try: args = web.input(track_id="", token=None) logging.debug("Vote request: %s" % args) sender = auth.get_id_by_token(args.token) if sender is None: raise web.forbidden("Bad token.") if args.track_id.isdigit(): track_id = int(args.track_id) else: track_id = tracks.get_last_track_id() weight = tracks.add_vote(track_id, sender, self.vote_value) if weight is None: return {"status": "error", "message": "No such track."} database.commit() message = 'OK, current weight of track #%u is %.04f.' % (track_id, weight) return { "status": "ok", "message": message, "id": track_id, "weight": weight, } except web.Forbidden: raise except Exception, e: log.log_exception(str(e), e) return {"status": "error", "message": str(e)}
def POST(self): args = web.input(token=None) try: sender = auth.get_id_by_token(args.token) if sender is None: raise web.forbidden("Bad token.") if sender not in get_admins(): raise web.forbidden("admin access required to skip tracks") skip_current_track() return {"success": True} except Exception, e: return {"success": False, "error": str(e)}
def GET(self): path = web.ctx.path if path == "/": if session.get('loggedin', False): raise web.seeother("/dashboard.html") else: raise web.seeother("/login.html") protectedExtensions = [".html", ".htm", ".py"] for extention in protectedExtensions: if path.endswith(extention): help.check_access() web.header("X-LIGHTTPD-send-file", doc_root + path) return "Access granted" resourcesExtensions = [ ".css", ".js", ".jpg", ".png", ".ico", ".woff", ".woff2", ".ttf", ".r", ".py", ".txt" ] for extention in resourcesExtensions: if path.endswith(extention): web.header("X-LIGHTTPD-send-file", doc_root + path) return "Access granted" raise web.forbidden()
def __init__(self): if (self.disallow_api or self.moderator_only or self.admin_only) and weasyl.api.is_api_user(): raise web.forbidden() self.user_id = define.get_userid() self.status = define.common_status_check(self.user_id) # Status check if self.status: self.replace_methods(self.status_check_fail) return # Guest check if self.guest_required and self.user_id != 0: self.replace_methods(self.login_guest_fail) return # Login check if self.login_required and self.user_id == 0: self.replace_methods(self.login_check_fail) return # Permission check if self.moderator_only and self.user_id not in staff.MODS: self.replace_methods(self.permission_check_fail) return if self.admin_only and self.user_id not in staff.ADMINS: self.replace_methods(self.permission_check_fail) return
def PUT(self, cluster_id): """:returns: JSONized Cluster attributes. :http: * 200 (OK) * 400 (wrong attributes data specified) * 404 (cluster not found in db) * 500 (cluster has no attributes) """ cluster = self.get_object_or_404(Cluster, cluster_id) if not cluster.attributes: raise web.internalerror("No attributes found!") data = self.checked_data() if cluster.is_locked: error = web.forbidden() error.data = "Environment attributes can't be changed " \ "after, or in deploy." raise error for key, value in data.iteritems(): setattr(cluster.attributes, key, value) cluster.add_pending_changes("attributes") db().commit() return {"editable": cluster.attributes.editable}
def DELETE(self, id): try: id = int(id) sshkey = model.getSSHKey(web.ctx.veerezoDB, id) if sshkey['user'] != web.ctx.username: web.forbidden() return None model.deleteSSHKey(web.ctx.veerezoDB, id) except: web.notfound() return None web.nocontent() return None
def POST(self): fb_data = fb.parse_signed_request(web.input()['signed_request']) if not fb_data: raise web.forbidden() gettext.translation('messages', localedir, languages=[fb_data['user']['locale'], 'en_US']).install(True) if not fb_data.get('user_id'): return "<script> top.location.href='" + fb.oauth_login_url( ) + "'</script>" res = fb.call('fql', args={ 'q': "SELECT pic_cover FROM user WHERE uid='{}'".format( fb_data['user_id']), 'access_token': fb_data['oauth_token'] }) cover = fb.get_biggest_image(res['data'][0]['pic_cover']['cover_id']) flipped_cover = flip_url(cover) tracking_id = os.environ.get('TRACKING_ID', '') return render.index(fb_data, cover, flipped_cover, web.ctx.host, tracking_id, _, DEBUG)
def POST(self): try: args = web.input(track_id="", token=None) logging.debug("Vote request: %s" % args) sender = auth.get_id_by_token(args.token) if sender is None: raise web.forbidden("Bad token.") if args.track_id.isdigit(): track_id = int(args.track_id) else: track_id = tracks.get_last_track_id() weight = tracks.add_vote(track_id, sender, self.vote_value) if weight is None: return {"status": "error", "message": "No such track."} database.commit() message = 'OK, current weight of track #%u is %.04f.' % (track_id, weight) return { "status": "ok", "message": message, "id": track_id, "weight": weight, } except web.Forbidden: raise except Exception, e: log.log_error(str(e), e) return {"status": "error", "message": str(e)}
def POST(self): data = web.input() token = data.get('token') if token == setting.entry_token: # 新用户 session['granted'] = True raise web.seeother('/new') else: db = getDB() r = list( db.select('webuser', {'usertoken': token}, where='usertoken=$usertoken')) if len(r) == 0: raise web.forbidden() else: # 老用户登录 session['userid'] = r[0]['id'] session['usertoken'] = r[0]['usertoken'] session['username'] = r[0]['username'] prev_url = data.get('url') if prev_url: # 用户从其它页面跳转而来 raise web.seeother(prev_url) else: return render.welcome(r[0]['username'], r[0]['usertoken'])
def POST(self): help.check_access() session = web.ctx.session usr = session.get("username", False) if usr: filedir = "./temp/uploads/" + usr + "/" try: stat(filedir) except: mkdir(filedir) else: raise web.forbidden() x = web.input(file={}) if 'file' in x: filepath = x.file.filename.replace( '\\', '/') # replaces the windows-style slashes with linux ones. filename = filepath.split( '/' )[-1] # splits by / and chooses the last part (the filename with extension) fout = open( filedir + filename, 'w' ) # creates the file where the uploaded file should be stored fout.write(x.file.file.read() ) # writes the uploaded file to the newly created file. fout.close() # closes the file, upload complete. return 200
def GET(self): get_input = web.input(_method='get') session = get_input['session'] response, code = session_request_get('session/%s' % session, None) if response.get('has_access'): start, count = get_pagination() tracks = sql.select("SELECT * FROM `tracks` LIMIT %s, %s" % (start, count)) tracks_count = sql.select("SELECT COUNT(*) FROM `tracks`") tracks_json_list = [] for track in tracks: track_json = {'id': str(track[0]), 'title': track[2], 'length': str(track[3]), 'file_size': str(track[4]), 'singer_id': track[1] } tracks_json_list.append(track_json) result = { 'tracks': tracks_json_list, 'start': str(start), 'count': str(count), 'total_count': str(tracks_count[0][0]) } web.header('Content-Type', 'json/text') return json.dumps(result) else: return web.forbidden()
def POST(self, api_key): try: data = json.loads(web.data()) if DEBUG: print(json.dumps(data)) except ValueError as e: raise web.badrequest('Invalid JSON request data') if not validate_api_key(api_key, api_config, data): raise web.forbidden('Invalid API Key') try: headers = {'Content-type': 'application/json'} if SENSU_API_USER and SENSU_API_PASS: if DEBUG: print "AUTH: SENSU_API_USER, XXX" auth = (SENSU_API_USER, SENSU_API_PASS) else: auth = None r = requests.post(SENSU_API_URI, json=data, headers=headers, auth=auth) r.raise_for_status() return web.accepted() except requests.exceptions.RequestException as e: print(e) raise web.internalerror('RequestException calling Sensu')
def GET(self): user_token = has_access() if user_token: start, count = get_pagination() tracks = select("SELECT * FROM `tracks` LIMIT %s, %s" % (start, count)) tracks_count = select("SELECT COUNT(*) FROM `tracks`") tracks_json_list = [] for track in tracks: track_json = {'id': str(track[0]), 'title': track[2], 'length': str(track[3]), 'file_size': str(track[4]), 'singer_id': track[1] } tracks_json_list.append(track_json) result = { 'tracks': tracks_json_list, 'start': str(start), 'count': str(count), 'total_count': str(tracks_count[0][0]) } web.header('Content-Type', 'json/text') return json.dumps(result) else: return web.forbidden()
def GET(self, id, *args): if not hasattr(self, '_get'): web.nomethod() return None try: id = int(id) vm = model.getVM(web.ctx.veerezoDB, id) if vm['user'] != web.ctx.username: web.forbidden() return None except (ValueError, KeyError): web.notfound() return None return self._get(id, vm, *args)
def GET(self, id): response, code = tracks_request_get('track/%s' % id, get_session()) response2, code2 = singers_request_get('singer/%s' % response.get('singer_id'), get_session()) response['singer_name'] = response2.get('name') if code == 200: return response else: return web.forbidden()
def PUT(package_name): try: if pleasance.create_package(package_name): return "Created package " + package_name else: return web.internalerror() except pleasance.PackageIsPromotedError: return web.forbidden()
def get_openid(self, access_token): result = qqOAuth.request('GET', '/oauth2.0/me', access_token=access_token) result = result.lstrip("callback( ") result = result.rstrip(" );\n") result = json.loads(result) if 'openid' not in result: raise web.forbidden() return result['openid']
def new_func(*args, **kws): if web.ctx.get('account_id'): if web.ctx.get('account_actived'): return fn(*args, **kws) else: raise web.forbidden('Account has been locked') else: raise web.seeother(web.ctx.home + web.http.url('/'))
def DELETE(self, id): try: id = int(id) vm = model.getVM(web.ctx.veerezoDB, id) if vm['user'] != web.ctx.username: web.forbidden() return None except ValueError: web.notfound() return None # we must not delete the DB entry here so that we don't get confused by the async nature of the job queue jobID = web.ctx.postBackendJob('deleteVM', id) addJobIDsHeader([jobID]) web.nocontent() return None
def GET(self, screen_id, secret): """ Serves the pure web-based client for this screen. """ try: screen = Screen.get(screen_id) if screen.secret != secret: raise web.forbidden() except SQLObjectNotFound: raise web.notfound() return self.ictv_renderer.render_screen_client(screen)
def wrapper(*args, **kwargs): hasrole = self.hasrole(*rargs) if hasrole: return function(*args, **kwargs) else: if self._lgn_pg: return web.seeother(self._lgn_pg) else: raise web.forbidden()
def POST_unhide_workshop(self, workshop, i): user = account.get_current_user() if user and user.is_admin(): workshop.unhide() signals.workshop_unhidden.send(workshop) flash("Workshop visible.", category="success") raise web.seeother("/workshops/{}".format(workshop.id)) else: raise web.forbidden(render_template("permission_denied.html"))
def GET(self, path): # This is the callers IP. dip = web.ctx['ip'] # Get the helper for the incoming IP address helper = isyhelperRESTObj.helpers.get_helper(dip) if helper is False: web.forbidden() if not path: raise web.notfound("path not defined from "+dip+"!") # TODO: Allow value param to be passed in? # TODO: Make sure split only returns 2 objects? #udata = web.input(value=None) li = path.split("/") varname = li[0] varvalue = li[1] info = 'REST:setvar:GET: ' + dip + ' varname='+ varname + ' value=' + str(varvalue) isyhelperRESTObj.helpers.logger.info(info) helper.setvar(varname,varvalue) return info
def DELETE(self, id): try: id = int(id) network = model.getNetwork(web.ctx.veerezoDB, id) if network['user'] != web.ctx.username: web.forbidden() return None model.deleteNetwork(web.ctx.veerezoDB, id) except (ValueError, KeyError): web.notfound() return None jobID = web.ctx.postBackendJob('reconfigureNetworks') addJobIDsHeader([jobID]) web.nocontent() return None
def POST(self): post_input = web.input(_method='post') name = post_input['login'] password = post_input['pass'] response, code = session_request_post('session/', {'login': name, 'pass': password }) if code == 200: # user & client exists web.setcookie('session', response.get('session'), 3600) return text web.setcookie('session', '', 3600) return web.forbidden()
def GET(self): url_params = web.input(recipient='none', quantity=100, threading='threading') if url_params.recipient == 'none': return web.notfound() address = url_params.recipient if len(gutils.get_email_address(address)) < 2: return web.notfound() token = gutils.get_auth_token(address) if len(token) < 2: return web.forbidden() try: classified_mail = gutils.fetch_and_classify_recent_mail(token, address, 0, 100) except: return web.forbidden() if url_params.threading != 'threading': return json.dumps(classified_mail) classified_threads = {} # could just sort and would probably be much more efficient for msg in classified_mail: if msg['subject'] not in classified_threads: classified_threads[msg['subject']] = msg elif gutils.earlier_time(classified_threads[msg['subject']]['time'], msg['time']) == msg['time']: classified_threads[msg['subject']] = msg return json.dumps([msg for (subj, msg) in classified_threads.iteritems()])
def GET(self): get_input = web.input(_method="get") session = get_input["session"] response, code = session_request_get("session/%s" % session, None) if response.get("has_access"): user = sql.select("SELECT * FROM `users` where `id` = '%s'" % (response.get("user_id"))) user_json = {"id": user[0][1], "name": user[0][1], "email": user[0][3]} web.header("Content-Type", "json/text") return json.dumps(user_json) else: return web.forbidden()
def decorated_function(*args, **kwargs): app = web.ctx.app_stack[0] if 'user' in app.session: u = User.get(app.session['user']['id']) if 'real_user' in app.session: real_user = User.get(app.session['real_user']['id']) # if the real user has at least the same right as the "logged as" user if u.highest_permission_level not in real_user.highest_permission_level: raise web.seeother('/logas/nobody') if permission_level in u.highest_permission_level: return f(*args, **kwargs) raise web.forbidden()
def get_workshop(id): """Returns workshop by given id. If there is no workshop with that id, 404 error is raised. If it is hidden and the user is not an admin, 403 error is raised. """ workshop = Workshop.find(id=id) if not workshop: raise web.notfound() user = account.get_current_user() if workshop.is_hidden() and (not user or (user and not user.is_admin())): raise web.forbidden(render_template("permission_denied.html")) return workshop
def fetch_submission(self, submissionid): try: submission = self.submission_manager.get_submission(submissionid, False) if not submission: raise self.app.notfound(message=_("This submission doesn't exist.")) except InvalidId as ex: self._logger.info("Invalid ObjectId : %s", submissionid) raise web.forbidden(_("Invalid ObjectId.")) courseid = submission["courseid"] taskid = submission["taskid"] course, task = self.get_course_and_check_rights(courseid, taskid) return course, task, submission
def GET(self): user_token = has_access() if user_token: user = select("SELECT * FROM `users` where `id` = '%s'" % (user_token[0][1])) user_json = { 'id': user[0][1], 'name': user[0][1], 'email': user[0][3] } web.header('Content-Type', 'json/text') return json.dumps(user_json) else: return web.forbidden()
def GET(self, id): get_input = web.input(_method='get') session = get_input['session'] response, code = session_request_get('session/%s' % session, None) if response.get('has_access'): singer = sql.select("SELECT * FROM `singers` WHERE `id` = '%s'" % id) singer_json = {'id': str(singer[0][0]), 'name': singer[0][1] } web.header('Content-Type', 'json/text') return json.dumps(singer_json) else: return web.forbidden()
def POST(self, id, action): try: id = int(id) vm = model.getVM(web.ctx.veerezoDB, id) if vm['user'] != web.ctx.username: web.forbidden() return None except (ValueError, KeyError): web.notfound() return None args = [id] kwargs = {} jobIDs = [] if action == 'start': method = 'startVM' elif action == 'stop': method = 'stopVM' elif action == 'kill': method = 'killVM' elif action == 'rebuild': # TODO in the long term we would like to keep 'data'... jobIDs.append(web.ctx.postBackendJob('removeDiskImages', id)) jobIDs.append(web.ctx.postBackendJob('createDiskImages', id)) method = 'prepareDiskImages' args.append(['root', 'swap', 'data']) else: web.notfound() return None jobIDs.append(web.ctx.postBackendJob(method, *args, **kwargs)) addJobIDsHeader(jobIDs) web.accepted() return None
def GET(self): logger.info("woker %s" % 'url2key_without_save') if is_ip_deny(web): raise web.forbidden() url = web.input().get('url') logger.info("url=%s" % url) # print "url=%s" % url if url is None or len(url.strip()) == 0: logger.error("url is %s" % "None") return web.NotFound('url is null') key = toKey(url.strip()) logger.info("key=%s" % key) # print "key=%s" % key # TODO 构造json,返回 return key
def POST(self, session): post_input = web.input(_method='post') name = post_input['login'] password = post_input['pass'] user = sql.select("SELECT `id` FROM `users` where `name` = '%s' and `password` = '%s'" % (name, password)) if len(user) > 0: # user exists code = gen(__code_length__) exp_time = time.time()+60 q = "INSERT INTO `session` (`user_id` ,`session`, `expires_at`) VALUES ('%s', '%s', '%s')" %\ (user[0][0], code, exp_time) #print q sql.query(q) return json.dumps({'session': code,'exp_timestamp': exp_time}) return web.forbidden()