def GET(self): if not GLOBALS['session']['loggedin']: raise web.Forbidden() try: data = memrise.user(GLOBALS['session']['loggedin']['username'], True) except HTTPError as e: if e.response.status_code == 403: raise web.Forbidden() else: raise web.NotFound() return data
def GET(self, idCourse, slug): if not GLOBALS['session']['loggedin']: raise web.Forbidden() sessionid = GLOBALS['session']['loggedin']['sessionid'] return _response( lambda: memrise.course_edit(sessionid, idCourse, slug))
def POST(self, ageid): creator = agedb.ageCreator(ageid) if userdb.ctx.uid != creator: raise web.Forbidden() x = web.input(agedata={}) agebits = {} try: agefile = x['agedata'].file gamever = x['gameversion'] agever = x['version'] except KeyError: raise common.MissingParam() # Confirm that the zip file looks like a real age plasma_utils.validate_zip(agefile, shortname, ageid) if not gamever in config.acceptable_game_versions: raise common.BadParam('gameversion') fileid = agedb.createFile(age=new_id, gamever=gamever, version=agever, status='NEW') filename = config.agefiles_path + str(fileid) + '.zip' out = open(filename, 'wb') agefile.seek(0) out.write(agefile.read()) out.close() raise web.redirect(config.ages_path + '/' + str(ageid))
def DELETE(self, request): if not web.ctx.env['REMOTE_ADDR'] in self.allowFlushFrom and not users.is_current_user_admin(): raise web.Forbidden() if request.split('/').pop() == '__ALL__': if 'memcache' in web.ctx.query: memcache.flush_all() return 'memcache flushed.\n' # entity selection is limited by 1000 but often timeout limit = 800 batch = [] for entity in Cache.all(keys_only=True).order('-expires').fetch(limit): batch.append(entity) n = len(batch) if n == 0: return 'No entries.\n' # batch deletion is limited by 500 but it timeouts above ~200 step = 200 if step > n: step = n for i in range(0, limit, step): db.delete(batch[i:i+step]) return '%s entries flushed\n' % n if self.ignoreQueryString is False: request += web.ctx.query cache = self.cache.get_by_key_name(request) if cache: cache.delete() memcache.delete('%s_%s' % (self.name, request)) return 'ok\n'
def wrapper(self, *args): if not logged_in(): with open('{0}/templates/session_expired.html'.format(ABS_PATH), 'rb') as session_template: raise web.Forbidden(session_template.read()) results = func(self, *args) return results
def wrap(*args, **kwds): username = web.input().get('_auth_user', None) password = web.input().get('_auth_pass', None) if (do_auth(admin, maintainer, username, password)): return method(*args, **kwds) else: raise web.Forbidden()
def POST(self, name): user = web.input('user')['user'] desc = web.input(desc=None)['desc'] machine = load_machine(name) if machine.locked: raise web.Forbidden() if machine.type == 'vps': curkey = machine.sshpubkey else: curkey, getstatus = get_sshkey(name) if getstatus != 0: curkey = machine.sshpubkey if machine.sshpubkey != curkey: newkey = curkey else: newkey = machine.sshpubkey res = DB.update('machine', where='name = $name AND locked = false', vars=dict(name=name), locked=True, description=desc, sshpubkey=newkey, locked_by=user, locked_since=web.db.SQLLiteral('NOW()')) assert res == 1, 'Failed to lock machine {name}'.format(name=name) print user, 'locked single machine', name, 'desc', desc
def POST(self, path): if not GLOBALS['session']['loggedin']: raise web.Forbidden() return _response(lambda: memrise.track_progress( path, web.input(), GLOBALS['session']['loggedin']['sessionid'], web.ctx.env.get('HTTP_X_CSRFTOKEN'), web.ctx.env.get('HTTP_X_REFERER')))
def GET(self): if not GLOBALS['session']['loggedin']: raise web.Forbidden() sessionid = GLOBALS['session']['loggedin']['sessionid'] _GET = web.input(period="week") return _response( lambda: memrise.user_leaderboard(sessionid, _GET.period))
def POST(self, idLevel): if not GLOBALS['session']['loggedin']: raise web.Forbidden() _POST = web.input() sessionid = GLOBALS['session']['loggedin']['sessionid'] return _response(lambda: memrise.level_multimedia_edit( sessionid, _POST.csrftoken, _POST.referer, idLevel, _POST.txt))
def POST(self, idThing): if not GLOBALS['session']['loggedin']: raise web.Forbidden() _POST = web.input() sessionid = GLOBALS['session']['loggedin']['sessionid'] return _response(lambda: memrise.level_thing_get( sessionid, _POST.csrftoken, _POST.referer, idThing))
def POST(self, idThing): if not GLOBALS['session']['loggedin']: raise web.Forbidden() _POST = web.input(file={}) sessionid = GLOBALS['session']['loggedin']['sessionid'] return _response(lambda: memrise.level_thing_upload_remove( sessionid, _POST.csrftoken, _POST.referer, idThing, _POST.cellId, _POST.fileId))
def GET(self, idCourse, slug): _GET = web.input(session=False) sessionid = False if _GET.session and _GET.session != "0": if not GLOBALS['session']['loggedin']: return web.Forbidden() sessionid = GLOBALS['session']['loggedin']['sessionid'] return _response(lambda: memrise.course(idCourse, sessionid))
def _error(e): # https://github.com/webpy/webpy/blob/master/web/webapi.py#L15 if e.response.status_code == 403: return web.Forbidden() elif e.response.status_code == 404: return web.NotFound() else: print(e) # traceback.print_exc() return web.NotFound()
def POST(self, name): user = web.input('user')['user'] machine = load_machine(name) if machine.locked: raise web.Forbidden() res = DB.update('machine', where='name = $name AND locked = false', vars=dict(name=name), locked=True, locked_by=user, locked_since=web.db.SQLLiteral('NOW()')) assert res == 1, 'Failed to lock machine {name}'.format(name=name)
def POST(self): data = web.data() data_json = json.loads(data) result = dna_expert.isMutant(data_json['dna']) r.set(data, int(0 if result == None else result)) if result == False: raise web.Forbidden() elif result: return web.OK() else: return web.HTTPError('400 Bad Request')
def GET(self, idCourse, path): if not GLOBALS['session']['loggedin']: raise web.Forbidden() sessionid = GLOBALS['session']['loggedin']['sessionid'] try: course = memrise.course_edit(sessionid, idCourse, path) except HTTPError as e: print(e) return GLOBALS['prender']._404() return GLOBALS['render'].course_edit(course)
def DELETE(self, name): user = web.input('user')['user'] machine = load_machine(name) if not machine.locked: raise web.BadRequest() if machine.locked_by != user: raise web.Forbidden() res = DB.update('machine', where='locked = true AND name = $name AND locked_by = $user', vars=dict(name=name, user=user), locked=False, locked_by=None) assert res == 1, 'Failed to unlock machine {name}'.format(name=name)
def GET(self): if not GLOBALS['session']['loggedin']: raise web.Forbidden() web.header('Content-type', 'text/plain') web.header('Transfer-Encoding', 'chunked') sessionid = GLOBALS['session']['loggedin']['sessionid'] offset = 0 c = 0 try: for courses in memrise.whatistudy(sessionid): yield json.dumps({ "content": GLOBALS['prender'].ajax_dashboard(courses, offset)['__body__'] }) + '$' offset += len(courses) # Take this opportunity to sync courses in session for course in courses: data = {} for k in [ 'num_things', 'learned', 'review', 'ignored', 'percent_complete' ]: data[k] = course[k] c += 1 except HTTPError as e: if e.response.status_code == 403: raise web.Forbidden() else: raise web.NotFound() except Exception as e: print(e) raise web.InternalError()
def GET(self, idCourse, slugCourse, lvl, kind="preview"): _GET = web.input(session=False) sessionid = False if _GET.session and _GET.session != "0": if not GLOBALS['session']['loggedin']: return web.Forbidden() sessionid = GLOBALS['session']['loggedin']['sessionid'] if slugCourse == "": slugCourse = "-" return _response( lambda: memrise.level(idCourse, slugCourse, lvl, kind, sessionid))
def GET(self, action): web.header("Cache-Control", "no-cache") if web.ctx.ip != "127.0.0.1": raise web.Forbidden() if action == "cleanup": return self.cleanup() elif action == "create": return self.create_task() elif action == "delete": return self.delete_task() elif action == "fetch": return self.fetch_data() elif action == "list": return self.list_tasks()
def handle_exceptions(ex): message = str(ex) if 'WEBENV' in os.environ and os.environ['WEBENV'] == 'test': pass elif (('WEBENV' in os.environ and os.environ['WEBENV'] == 'development') or ('WEBENV' in web.ctx.env and web.ctx.env['WEBENV'] == 'development')): message = traceback.format_exc(10) print message # to get this in the server logs else: print traceback.format_exc(10) if isinstance(ex, PermissionDenied): web.message = 'Permission Denied' raise web.Forbidden() elif isinstance(ex, IllegalState): # Sometimes we try to explain why illegal state, like # the assessment still has items, can't delete it. # web.message = 'IllegalState {0}'.format(message) # raise web.NotAcceptable() raise web.InternalError('IllegalState {0}'.format(message)) else: raise web.InternalError(message)
def generate_http_response(self, status_code, data=None, exc_cls=None, exc_msg=None): if status_code == HTTP_STATUS_CODE.OK: if data: raise web.OK(data=json.dumps(data), headers={}) else: raise web.OK() elif status_code == HTTP_STATUS_CODE.Created: raise web.Created() elif status_code == HTTP_STATUS_CODE.Accepted: raise web.Accepted() elif status_code == HTTP_STATUS_CODE.BadRequest: raise web.BadRequest( message=self.generate_message(exc_cls, exc_msg)) elif status_code == HTTP_STATUS_CODE.Unauthorized: raise web.Unauthorized( message=self.generate_message(exc_cls, exc_msg)) elif status_code == HTTP_STATUS_CODE.Forbidden: raise web.Forbidden( message=self.generate_message(exc_cls, exc_msg)) elif status_code == HTTP_STATUS_CODE.NotFound: raise web.NotFound(message=self.generate_message(exc_cls, exc_msg)) elif status_code == HTTP_STATUS_CODE.Conflict: raise web.Conflict(message=self.generate_message(exc_cls, exc_msg)) elif status_code == HTTP_STATUS_CODE.InternalError: raise web.InternalError( message=self.generate_message(exc_cls, exc_msg)) else: if data: raise web.HTTPError(status_code, data=json.dumps(data)) else: raise web.HTTPError(status_code)
def wrapper(req_obj, req_path): if _check_rw(req_obj, req_path): return f(req_obj, req_path) raise web.Forbidden()
def wrapper(*args, **kw): i = web.input() app = i.get('app') if app == None or app not in ['test']: return web.Forbidden() return func(*args, **kw)
def GET(self): raise web.Forbidden()
def disallowed(self): "Over-ride this method if you want to log incidents" raise web.Forbidden('Rate limit exceeded')
def checkAuth(self): if not web.ctx.env['REMOTE_ADDR'] in self.allowFrom and not users.is_current_user_admin(): raise web.Forbidden()
def GET(self, idLevel): if not GLOBALS['session']['loggedin']: raise web.Forbidden() sessionid = GLOBALS['session']['loggedin']['sessionid'] return _response(lambda: memrise.level_edit(sessionid, idLevel))
def wp_read(config_agent, tpl_render, req_path): view_settings = get_view_settings(config_agent) folder_pages_full_path = config_agent.get_full_path("paths", "pages_path") local_full_path = mdutils.req_path_to_local_full_path( req_path, folder_pages_full_path) static_file_prefix = static_file.get_static_file_prefix_by_local_full_path( config_agent=config_agent, local_full_path=local_full_path, req_path=req_path) path_info = web.ctx.environ["PATH_INFO"] HOME_PAGE = "" if req_path != HOME_PAGE and view_settings["button_mode_path"]: buf = mdutils.text_path_to_button_path("/%s" % req_path) button_path = mdutils.md2html(config_agent=config_agent, req_path=req_path, text=buf, static_file_prefix=static_file_prefix, **view_settings) else: button_path = None view_settings["show_quick_links"] = False title = "" if os.path.isfile(local_full_path): # os.path.exists(local_full_path) buf = commons.shutils.cat(local_full_path) buf = commons.strutils.strip_bom(buf) title = mdutils.get_title_by_file_path_in_md( folder_pages_full_path=folder_pages_full_path, file_path_suffix=local_full_path) elif os.path.isdir(local_full_path): # os.path.exists(local_full_path) if req_path == HOME_PAGE: a = os.path.join(local_full_path, "index.md") b = os.path.join(local_full_path, "index.markdown") if os.path.exists(a) or os.path.exists(b): fixed_req_path = os.path.join(path_info, "index") return web.seeother(fixed_req_path) else: fixed_req_path = os.path.join(path_info, "~all") return web.seeother(fixed_req_path) else: # listdir /path/to/folder/* buf = shell.get_page_file_list_by_req_path( folder_pages_full_path=folder_pages_full_path, req_path=req_path) if buf: buf = mdutils.sequence_to_unorder_list( folder_pages_full_path=folder_pages_full_path, seq=buf.split("\n"), **view_settings) title = req_path else: buf = "folder `%s` exists, but there is no files" % path_info else: # not os.path.exists(local_full_path) readonly = config_agent.config.get("main", "readonly") if readonly: raise web.Forbidden() else: if path_info.endswith("/"): fixed_req_path = path_info + "index?action=update" else: fixed_req_path = path_info + "?action=update" return web.seeother(fixed_req_path) content = mdutils.md2html(config_agent=config_agent, req_path=req_path, text=buf, static_file_prefix=static_file_prefix, **view_settings) static_files = get_the_same_folders_cssjs_files( req_path=req_path, local_full_path=local_full_path, folder_pages_full_path=folder_pages_full_path) if not static_files: static_files = static_file.get_global_static_files( **view_settings) + "\n" buf = tpl_render.canvas(config=config_agent.config, static_files=static_files, button_path=button_path, req_path=req_path, title=title, content=content, **view_settings) return buf