def registracija(): uporabnisko_ime = request.forms.uporabnisko_ime geslo = request.forms.geslo if modeli.ustvari_uporabnika(uporabnisko_ime, geslo): bottle.response.set_cookie('prijavljen', 'da', secret=SKRIVNOST, path='/') redirect('/') else: raise bottle.HTTPError( 403, "Uporabnik s tem uporabniškim imenom že obstaja!")
def gh_hook(): if 'X-Hub-Signature' not in bottle.request.headers: logging.error('Unsigned POST request to webhook URL.') raise bottle.HTTPError(403, 'Request not signed (no X-Hub-Signature)') payload = bottle.request.body.read() received_sig = bottle.request.headers['X-Hub-Signature'] if not received_sig.startswith('sha1='): logging.error('X-Hub-Signature not HMAC-SHA1 (%r)' % received_sig) raise bottle.HTTPError(500, 'X-Hub-Signature not HMAC-SHA1') received_sig = received_sig.split('=', 1)[1] computed_sig = hmac.new(cfg.github.hook_hmac_secret.encode('ascii'), payload, hashlib.sha1).hexdigest() if received_sig != computed_sig: logging.error('Received signature %r does not match' % received_sig) raise bottle.HTTPError(403, 'Signature mismatch') evt_type = bottle.request.headers['X-Github-Event'] evt = events.RawGHHook(evt_type, bottle.request.json) events.dispatcher.dispatch('webserver', evt) return 'OK'
def wrapper(*args, **kwargs): session = db.Session() try: body = callback(session, *args, **kwargs) except sqlalchemy.exc.SQLAlchemyError as exc: session.rollback() raise bottle.HTTPError(500, "A database error occurred.", exc) finally: session.close() return body
def get_graph(): epoch = int(bottle.request.query['epoch']) since_v = int(bottle.request.query['since_v']) since_e = int(bottle.request.query['since_e']) if epoch != -1 and epoch != EPOCH: return bottle.HTTPError(418) if not READY: return _json({'vertices': [], 'edges': []}) return _json({'vertices': VERTICES[since_v:], 'edges': EDGES[since_e:]})
def ustvari_kuverto(ime: str, gledalec: 'Uporabnik'): racun = gledalec.racuni.get(ime) if racun is None: return bottle.HTTPError(404) return { "racun": racun, "kuverte": racun.kuverte, "barve": BarvaKuverte.values(), "ikone": IkonaKuverte.values() }
def snapshot_get(self, name): name = os.path.basename(name) ret = self.snapshot_ctl.get(name) if ret is None: raise bottle.HTTPError(404, "Not Found") else: bottle.response.set_header('Content-Type', APPLICATION_JSON) return ret
def dodaj_vozilo(): if not prijavljen_uporabnik(): raise bottle.HTTPError(401) naziv = bottle.request.forms.naziv try: modeli.dodajTecaj(naziv) except: return template('dodaj_tecaj', naziv = naziv ) bottle.redirect('/tecaji')
def getL3Report(self, dbSession, podId): try: cached = bottle.request.query.get('cached', '1') if cached == '1': cachedData = True else: cachedData = False bottle.response.headers['Content-Type'] = 'application/json' return self.l3Report.generateReport(podId, cachedData) except Exception as e: raise bottle.HTTPError(404, exception=PodNotFound(podId, e))
def handle_error(self, error, req, schema, error_status_code, error_headers): """Handles errors during parsing. Aborts the current request with a 400 error. """ status_code = error_status_code or self.DEFAULT_VALIDATION_STATUS raise bottle.HTTPError( status=status_code, body=error.messages, headers=error_headers, exception=error, )
def dodaj_uporabo_ida(): if not prijavljen_uporabnik(): raise bottle.HTTPError(401) intervencije = modeli.vse_intervencije() clani = modeli.vsi_clani() return template( 'dodaj_uporabo_ida', intervencije = intervencije, clani = clani, intervencija = "", clan = "" )
def asp_get(self, name, host, arch, name2): base = os.path.basename(name2) if wayround_i2p.utils.system_type.parse_triplet(host) is None: raise bottle.HTTPError(400, "Invalid host triplet") if wayround_i2p.utils.system_type.parse_triplet(arch) is None: raise bottle.HTTPError(400, "Invalid arch triplet") path = self.pkg_repo_ctl.get_package_path_string(name) filename = wayround_i2p.utils.path.abspath( wayround_i2p.utils.path.join( self.pkg_repo_ctl.get_repository_dir(), path, 'pack', host, arch, base ) ) if not filename.startswith( self.pkg_repo_ctl.get_repository_dir() + os.path.sep ): raise bottle.HTTPError(404, "Wrong package name `{}'".format(name)) logging.info("trying to find file: {}".format(filename)) if not os.path.isfile(filename): raise bottle.HTTPError(404, "File `{}' not found".format(base)) ret = bottle.static_file( filename=base, root=os.path.dirname(filename), mimetype='application/binary' ) return ret
def update_visit(id, mongodb): visit = mongodb.visits.find_one({'_id': id}) if not visit: return bottle.HTTPError(404) data = bottle.request.json if not data: return bottle.HTTPError(400) if 'id' in data: return bottle.HTTPError(400) for key in data: if data[key] is None: return bottle.HTTPError(400) # TODO validate if 'user' in data: user = mongodb.users.find_one({'_id': data['user']}) if not user: return bottle.HTTPError(400) data['user__age'] = user['age'] data['user__gender'] = user['gender'] if 'location' in data: location = mongodb.locations.find_one({'_id': data['location']}) if not location: return bottle.HTTPError(400) data['location__distance'] = location['distance'] data['location__country'] = location['country'] data['place'] = location['place'] mongodb.visits.update({"_id": id}, {"$set": data}) return {}
def endpoint_create(): context = get_context() payload = bottle.request.json payload.pop('idnr', None) kind = extract_payload_fields(payload, 'type')[0] try: klass = model.EndpointKind(kind) klass = model.endpoint_klass_map[klass] except (TypeError, KeyError): return bottle.HTTPError(400, 'Invalid endpoint type {!r}'.format(kind)) try: bind_address = payload.pop('bind_address', None) if bind_address: bind_address = unpack_idnr(bind_address) bind_address = context.service.address.lookup(bind_address) if klass is model.ConsumerEndpoint: if bind_address is None: raise bottle.HTTPError(400, "bind_address field is missing") entity = klass(bind_address, **payload) elif klass is model.ProducerEndpoint: address = extract_payload_fields(payload, 'remote_address')[0] address, port = extract_payload_fields(address, 'address', 'port') entity = klass(model.EndpointAddress(address, port), bind_address=bind_address, **payload) else: raise bottle.HTTPError(500, 'Unreachable point have been reached!') except exc.ServiceLookupError as e: return bottle.HTTPError(400, 'Invalid resource reference: {}'.format(e)) except TypeError as e: return bottle.HTTPError(400, str(e)) context.service.endpoint.create(entity) bottle.response.status = 201 return endpoint_response(entity)
def showdiff(db, parent, id): this = _get_paste(db, id) if not this: return bottle.HTTPError(404, 'This paste does not exist') that = _get_paste(db, parent) if not that: return bottle.HTTPError(404, 'Parent paste does not exist') if this.password or that.password: return bottle.HTTPError( 403, 'Can only show differences between unprotected entries') diff = '\n'.join([ _ for _ in difflib.unified_diff( that.content.splitlines(), this.content.splitlines(), fromfile=that.filename or 'Paste #{0}'.format(that.id), tofile=this.filename or 'Paste #{0}'.format(this.id)) ]) lexer = lexers.get_lexer_by_name('diff') content = pygments.highlight( diff, lexer, formatters.HtmlFormatter( linenos='table', encoding='utf-8', lineanchors='ln', anchorlinenos=True, )) return bottle.template( 'pygmentize.html', pygmentized=content, title='Showing differences between #{0} and #{1}'.format(parent, id), version=pasttle.__version__, current_year=CURRENT_YEAR, url=get_url(), id=id, parent=parent, pygments_style=util.conf.get(util.cfg_section, 'pygments_style'), )
def getDeviceConfig(self, podName, deviceName): if not self.isDeviceExists(podName, deviceName): raise bottle.HTTPError( 404, "No device found with pod name: '%s', device name: '%s'" % (podName, deviceName)) fileName = os.path.join(podName, deviceName + '.conf') logger.debug('webServerRoot: %s, fileName: %s, exists: %s' % (webServerRoot, fileName, os.path.exists(os.path.join(webServerRoot, fileName)))) config = bottle.static_file(fileName, root=webServerRoot) if isinstance(config, bottle.HTTPError): logger.debug( "Device exists but no config found. Pod name: '%s', device name: '%s'" % (podName, deviceName)) raise bottle.HTTPError( 404, "Device exists but no config found, probably fabric script is not ran. Pod name: '%s', device name: '%s'" % (podName, deviceName)) return config
def wrapper(*args, **kwargs): try: user = self.get_user() if user: permissions = callback.__dict__.get('permission', None) authorization_error = self.security_scheme.authorize( user, permissions) if authorization_error: raise bottle.HTTPError(403, authorization_error) kwargs['user'] = user return callback(*args, **kwargs) else: raise AuthenticationException('Authentication required.') except AuthenticationException as e: response = bottle.HTTPError(401, str(e)) # don't request basic auth from ajax requests if not bottle.request.is_xhr: response.headers[ 'WWW-Authenticate'] = 'Basic realm="%s"' % self.realm_name raise response except XsrfTokenException as e: raise bottle.HTTPError(403, str(e))
def wrapper(*args, **kwargs): # macaronage(dbfile, lazy=True, autocommit=False, keep=True) try: ret_value = callback(*args, **kwargs) if self.commit_on_success: bake() # commit except sqlite3.IntegrityError, e: rollback() traceback = None if bottle.DEBUG: traceback = (history.lastsql, history.lastparams) sqllog = "[Macaron]LastSQL: %s\n[Macaron]Params : %s\n" % traceback bottle.request.environ["wsgi.errors"].write(sqllog) raise bottle.HTTPError(500, "Database Error", e, tb.format_exc())
def _action_resolve_approval(self): if bottle.request.method != "POST": raise bottle.HTTPError(405, "Method not allowed.") try: approval_id = bottle.request.POST.get("approval_id") except KeyError: raise bottle.HTTPError(400, "approval is missing.") try: solution = bottle.request.POST.get("solution").strip() except KeyError: raise bottle.HTTPError(400, "solution is missing.") if solution not in ("grant", "deny"): raise bottle.HTTPError( 400, "wrong solution value (expected 'grant' or 'deny').") bottle.response.set_header("Content-Type", "application/json") return current_state.backend.perform("updater", "resolve_approval", { "hash": approval_id, "solution": solution })
def call_action(self, action): if bottle.request.method != 'POST': # all actions here require POST messages.error("Wrong HTTP method.") bottle.redirect(reverse("config_page", page_name="tls")) if action == "get-token": if bottle.request.POST.get("qrcode"): # Button for QR token generation has been clicked return self._action_generate_token_qrcode_data() return self._action_get_token() elif action == "reset-ca": return self._action_reset_ca() raise bottle.HTTPError(404, "Unknown action.")
def getZtpConfig(self, dbSession, podId): pod = self.report.getPod(dbSession, podId) if pod is not None: logger.debug('pod name: %s' % (pod.name)) podFolder = pod.id + '-' + pod.name fileName = os.path.join(podFolder, "dhcpd.conf") logger.debug( 'webServerRoot: %s, fileName: %s, exists: %s' % (webServerRoot, fileName, os.path.exists(os.path.join(webServerRoot, fileName)))) ztpConf = bottle.static_file(fileName, root=webServerRoot) if isinstance(ztpConf, bottle.HTTPError): raise bottle.HTTPError( 404, exception=DeviceConfigurationNotFound( "Pod exists but no ztp Config found. Pod name: '%s " % (pod.name))) return ztpConf else: raise bottle.HTTPError(404, exception=PodNotFound(podId))
def getCablingPlan(self, dbSession, podId): header = bottle.request.get_header('Accept') logger.debug('Accept header before processing: %s' % (header)) # hack to remove comma character, must be a bug on Bottle header = header.translate(None, ',') logger.debug('Accept header after processing: %s' % (header)) pod = self.report.getPod(dbSession, podId) if pod is not None: logger.debug('Pod name: %s' % (pod.name)) if header == 'application/json': cablingPlan = pod.cablingPlan if cablingPlan is not None and cablingPlan.json is not None: logger.debug('CablingPlan found in DB') return cablingPlan.json else: raise bottle.HTTPError(404, exception=CablingPlanNotFound( pod.id)) else: podFolder = pod.id + '-' + pod.name fileName = os.path.join(podFolder, 'cablingPlan.dot') logger.debug( 'webServerRoot: %s, fileName: %s, exists: %s' % (webServerRoot, fileName, os.path.exists(os.path.join(webServerRoot, fileName)))) logger.debug('Cabling file name: %s' % (fileName)) cablingPlan = bottle.static_file(fileName, root=webServerRoot) if isinstance(cablingPlan, bottle.HTTPError): raise bottle.HTTPError( 404, exception=CablingPlanNotFound(podFolder)) return cablingPlan else: raise bottle.HTTPError(404, exception=PodNotFound(podId))
def prijava(): nazaj = bottle.request.POST.get('Nazaj') if nazaj is not None: bottle.redirect('/') prijavljen = modeli.uporabnik_baze(bottle.request.forms.geslo, bottle.request.forms.uporabnik) if prijavljen: bottle.response.set_cookie( 'prijavljen', 'da', secret=SKRIVNOST, path='/') bottle.redirect('/izbira' ) else: raise bottle.HTTPError(403, "Napačno geslo ali uporabniško ime!")
def hosts(self, name): decoded_params = bottle.request.params.decode('utf-8') ret = '' resultmode = 'html' if 'resultmode' in decoded_params: resultmode = decoded_params['resultmode'] if not resultmode in ['html', 'json']: raise bottle.HTTPError(400, "Invalid resultmode") filesl = self.pkg_repo_ctl.get_package_hosts(name) if not isinstance(filesl, list): raise bottle.HTTPError( 404, "Error getting host list. Is package name correct?" ) filesl.sort() if resultmode == 'html': txt = self.ui.hosts( name, filesl ) ret = self.ui.html( title="Package: '{}'".format(name), body=txt ) elif resultmode == 'json': ret = json.dumps(filesl, sort_keys=True, indent=2) bottle.response.set_header('Content-Type', APPLICATION_JSON) return ret
def login(self, req): log.debug('login sslcert') username = req.forms.get('username') if not username: raise bottle.HTTPError(401, 'username not provided') uid = self.check(req) x = self.auth.get(username, fallback=None) if x is None: raise AuthError("invalid username: %s" % username) uid = self.digest(uid.strip()) if x != uid: raise AuthError("user %s: invalid id" % username) return username
def name_by_name(self): decoded_params = bottle.request.params.decode('utf-8') if not 'tarball' in decoded_params: raise bottle.HTTPError(400, "Wrong tarball parameter") if not 'resultmode' in decoded_params: decoded_params['resultmode'] = 'html' if not decoded_params['resultmode'] in ['html', 'json']: raise bottle.HTTPError(400, "Wrong resultmode parameter") tarball = decoded_params['tarball'] resultmode = decoded_params['resultmode'] res = self.info_ctl.get_package_name_by_tarball_filename( tarball, mute=True ) result_name = None if isinstance(res, list): result_name = res if result_name is None: raise bottle.HTTPError(404, "Not found") if resultmode == 'html': ret = self.ui.html( title="Result searching for package" " name by tarball name `{}'".format(tarball), body=self.ui.name_by_name(result=result_name) ) elif resultmode == 'json': ret = json.dumps(result_name, sort_keys=True, indent=2) bottle.response.set_header('Content-Type', APPLICATION_JSON) return ret
def _action_generic(self, action): if bottle.request.method != "POST": messages.error(_("Wrong HTTP method.")) bottle.redirect(reverse("config_page", page_name="remote")) form = self.get_serial_form(bottle.request.POST.decode()) if not form.data["serial"]: raise bottle.HTTPError(404, "serial not found") res = current_state.backend.perform("netboot", action, {"serial": form.data["serial"]}) bottle.response.set_header("Content-Type", "application/json") return res
def update_entry_state(id, query): try: state = getattr(State, query.state) except AttributeError: raise bottle.HTTPError(400) entry = get_entry_by_id(id) if query.soft and entry.state != State.pending: return entry entry.state = state return update_entry_by_id(id, entry)
def showpaste(db, id): """ Shows the highlighted entry on the browser. If the entry is protected with a password it will display a password entry and will compare against the database for a match """ paste = _get_paste(db, id) lang = bottle.request.query.lang or None if not paste: return bottle.HTTPError(404, 'This paste does not exist') form = bottle.request.forms password = form.get('password') if paste.password: if not password: return bottle.template( 'password_protect', url=get_url(), title=util.conf.get(util.cfg_section, 'title'), version=pasttle.__version__, current_year=CURRENT_YEAR, ) is_encrypted = bool(form.get('is_encrypted')) if is_encrypted: match = password else: match = hashlib.sha1(password.encode()).hexdigest() util.log.debug('{0} == {1} ? {2}'.format( match, paste.password, match == paste.password, )) if match == paste.password: bottle.response.content_type = 'text/html' return _pygmentize(paste, lang) else: return bottle.HTTPError(401, 'Wrong password provided') else: return _pygmentize(paste, lang)
def post_cc_connect(self, session): try: node = self.nodes[session['node']] except KeyError: self.sessions.delete_session(session) raise bottle.HTTPError(400) # This raises in case of issues self.connect_card_to_node(session, node) # Being here there's a valid connection! session['status'] = 'cc_ok'
def move(db, game_id, move=None): game = db.query(Game).get(game_id) if game is None: raise bottle.HTTPError(404) if not game.active: raise bottle.HTTPError(403, "Game is over") board = chess.Board() board.set_epd(game.epd) side = 'white' if board.turn else 'black' try: token = bottle.request.json['token'].encode('utf8') if not hmac.compare_digest(trusted_digest(game.uuid, side), token): raise bottle.HTTPError(403, "Bad token provided") except KeyError: raise bottle.HTTPError(403, "No token provided") if move is not None: move = chess.Move.from_uci(move) if move not in board.legal_moves: raise bottle.HTTPError(404) board.push(move) if game.moves: game.moves += "," + move.uci() else: game.moves = move.uci() else: if board.can_claim_draw(): game.claim_draw = True new_url = mint_game_url(game) game.move_count += 1 game.epd = board.epd(hmvc=board.halfmove_clock, fmvc=board.fullmove_number) if board.is_game_over(claim_draw=game.claim_draw): game.active = False game.turn = board.turn db.add(game) db.flush() if game.move_count == 1: mail_token(game, 'black', first=True) return dict(new_url=new_url)