def get_object(self, req, resp, path_params, for_update=False): pk = req.context['doc'].get('pk') if not pk: raise HTTPNotFound() obj = self.objects_class.get(pk) if obj is None: raise HTTPNotFound() return obj
def on_get(self, req, resp, wf_id): self.log.debug("Determining pods in workflow '{}'".format(wf_id)) wf = self.parent.rubin_mgr.workflow_mgr.get_workflow(wf_id) if not wf: raise HTTPNotFound() nd = wf.status.nodes if not nd: raise HTTPNotFound() rv = [] for k in nd: rv.append({"name": k}) resp.media = rv
def on_get(req, resp, team): team = unquote(team) fields = req.get_param_as_list('fields') active = req.get_param('active', default=True) connection = db.connect() cursor = connection.cursor(db.DictCursor) cursor.execute('SELECT `id`, `name`, `email`, `slack_channel`, `scheduling_timezone` ' 'FROM `team` WHERE `name`=%s AND `active` = %s', (team, active)) results = cursor.fetchall() if not results: raise HTTPNotFound() [team_info] = results if not fields: # default to get all data fields = populate_map.keys() for field in fields: populate = populate_map.get(field) if not populate: continue populate(cursor, team_info) cursor.close() connection.close() resp.body = json_dumps(team_info)
def on_put(self, req, resp, **kwargs): # Load update object raw_json = req.stream.read() obj = json.loads(raw_json.decode('utf-8')) if raw_json else None if 'endpoint' in kwargs and kwargs.get( 'endpoint').lower() not in PackageAPI.PACKAGE_PUT_OPTIONS: raise HTTPNotFound() elif 'endpoint' in kwargs and kwargs.get( 'endpoint').lower() in PackageAPI.PACKAGE_PUT_OPTIONS: endpoint = '{}{}/{}'.format( ConfReader().get('APP_CATALOGUE', 'url'), kwargs.get('package_id'), 'action') request_post_patch(endpoint, method='PUT', params=dict(status=kwargs.get('endpoint'))) elif not obj or 'app' not in obj: raise HTTPBadRequest( title='No data', description='No data provided to update package', code='211') else: endpoint = "{}{}".format(ConfReader().get('APP_CATALOGUE', 'url'), kwargs.get('package_id')) request_post_patch(endpoint, method='PUT', json=obj.get('app')) resp.status = HTTP_200
def on_get(self, req, resp, **kwargs): """ diagnosis.symptom.oid :param req: :param resp: :param kwargs: :return: """ offset, limit, query = prepare_query(req) value, offset = Tal.objects.find(query=query, limit=limit, offset=offset) if not kwargs: tal = self._get_tal_list_(req, resp, value) else: for _tal_ in value: if kwargs.get('tal_id') == _tal_.get('reaction')[0].get('diagnosis').get('symptom').get('oid'): _tal_.pop('className') tal = _tal_ break if not tal: raise HTTPNotFound() response = dict(tal=tal) if offset: response['offset'] = offset resp.body = self.format_body(response, from_dict=True, paginate=True, req=req)
def on_delete(req, resp, team): ''' Soft delete for teams. Does not remove data from the database, but sets the team's active param to false. Note that this means deleted teams' names remain in the namespace, so new teams cannot be created with the same name a sa deleted team. **Example request:** .. sourcecode:: http DELETE /api/v0/teams/team-foo HTTP/1.1 :statuscode 200: Successful delete :statuscode 404: Team not found ''' team = unquote(team) check_team_auth(team, req) connection = db.connect() cursor = connection.cursor() # Soft delete: set team inactive, delete future events for it cursor.execute('UPDATE `team` SET `active` = FALSE WHERE `name`=%s', team) cursor.execute( 'DELETE FROM `event` WHERE `team_id` = (SELECT `id` FROM `team` WHERE `name` = %s) ' 'AND `start` > UNIX_TIMESTAMP()', team) create_audit({}, team, TEAM_DELETED, req, cursor) deleted = cursor.rowcount connection.commit() cursor.close() connection.close() if deleted == 0: raise HTTPNotFound()
def on_get(req, resp, team): """Get the secret key that grants public access to team's oncall calendar for the logged-in user. Current policy only allows access to the team that the logged-in user is part of. **Example request:** .. sourcecode:: http GET /api/v0/ical_key/team/jteam HTTP/1.1 Content-Type: text/plain ef895425-5f49-11ea-8eee-10e7c6352aff """ challenger = req.context['user'] check_calendar_auth(team, req) key = get_ical_key(challenger, team, 'team') if key is None: raise HTTPNotFound() resp.body = key resp.set_header('Content-Type', 'text/plain')
def on_post(req, resp): login_info = uri.parse_query_string(req.context['body']) user = login_info.get('username') password = login_info.get('password') if user is None or password is None: raise HTTPBadRequest('Invalid login attempt', 'Missing user/password') if not auth_manager.authenticate(user, password): raise HTTPUnauthorized('Authentication failure', 'bad login credentials', '') connection = db.connect() cursor = connection.cursor(db.DictCursor) data = get_user_data(None, {'name': user}, dbinfo=(connection, cursor)) if not data: cursor.close() connection.close() raise HTTPNotFound() session = req.env['beaker.session'] session['user'] = user session.save() csrf_token = '%x' % SystemRandom().getrandbits(128) cursor.execute( 'INSERT INTO `session` (`id`, `csrf_token`) VALUES (%s, %s)', (req.env['beaker.session']['_id'], csrf_token)) connection.commit() cursor.close() connection.close() # TODO: purge out of date csrf token data[0]['csrf_token'] = csrf_token resp.body = dumps(data[0])
def on_get(req, resp, service): """ Get service id by name **Example request** .. sourcecode:: http GET /api/v0/services/service-foo HTTP/1.1 Host: example.com **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json { "id": 1234, "name": "service-foo" } """ connection = db.connect() cursor = connection.cursor(db.DictCursor) cursor.execute('SELECT `id`, `name` FROM `service` WHERE `name`=%s', service) results = cursor.fetchall() if not results: raise HTTPNotFound() [service] = results cursor.close() connection.close() resp.body = dumps(service)
def on_delete(req, resp, user_name, team_name): ''' Delete a pinned team **Example request:** .. sourcecode:: http DELETE /api/v0/users/jdoe/pinned_teams/team-foo HTTP/1.1 :statuscode 200: Successful delete :statuscode 403: Delete not allowed; logged in user does not match user_name :statuscode 404: Team not found in user's pinned teams ''' check_user_auth(user_name, req) connection = db.connect() cursor = connection.cursor() cursor.execute( '''DELETE FROM `pinned_team` WHERE `user_id` = (SELECT `id` FROM `user` WHERE `name` = %s) AND `team_id` = (SELECT `id` FROM `team` WHERE `name` = %s)''', (user_name, team_name)) deleted = cursor.rowcount connection.commit() cursor.close() connection.close() if deleted == 0: raise HTTPNotFound()
def on_get(self, req: Request, resp: Response): token = req.get_param('token', required=True) user_data = get_user_data(token) if not user_data: raise HTTPNotFound( title=f'No admin found for provided token', description=f'No admin found for provided token') with self.uowm.start() as uow: admin = uow.site_admin.get_by_username(user_data['name']) if not admin: raise HTTPNotFound( title=f'No admin found for provided token', description=f'No admin found for provided token') resp.body = json.dumps(admin.to_dict())
def raise_error(self, error_code=None, desc='Something went wrong in server'): if error_code and error_code != 500: if error_code == 401 or error_code == 403: redis_cli = Redis.get_redis_client() if redis_cli is not None: access_token = redis_cli.delete('sheets_v4_access') else: print('Redis client is not active') if error_code == 400: raise HTTPBadRequest(description=desc or '') elif error_code == 401: raise HTTPUnauthorized(description=desc or '') elif error_code == 403: raise HTTPForbidden(description=desc or '') elif error_code == 404: raise HTTPNotFound(description=desc or '') elif error_code == 409: raise HTTPConflict(description=desc or '') elif error_code == 412: raise HTTPPreconditionFailed(description=desc or '') elif error_code == 422: raise HTTPUnprocessableEntity(description=desc or '') elif error_code == 503: raise HTTPServiceUnavailable(description=desc or '') else: raise HTTPError(HTTP_400, description=desc or '', code=error_code) else: raise HTTPInternalServerError(description=desc or '')
def login(username, password): try: u = db.session.query(User).filter(User.username == username).one() except NoResultFound: raise HTTPNotFound(title='Cannot', description='asdfas') return {'token': generate_token(u)}
def on_post(self, req, resp): request_start_time = time.perf_counter() logger.info("processing html content") content = self._extract_content_from_request(req) try: processing_result = self.content_analyser.process_content(content) except TASError as e: logger.warning("TAS failed to failed to process content") raise self._error_handler.handle_exception(e) from e except Exception as e: logger.exception("failed to process content") raise HTTPNotFound(title="Processing error", description="Failed to process content", code=error_codes.TAS_ERROR) from e resp.status = HTTP_200 resp.content_type = "application/json" resp.body = json.dumps(processing_result) execution_time = time.perf_counter() - request_start_time log_msg = "page processing request executed: " \ "execution_time({execution_time})" logger.info(log_msg.format(execution_time=execution_time))
def on_get(req, resp, user_name): """Get the secret key that grants public access to user_name's oncall calendar for the logged-in user. Current policy only allows the logged-in user to get its own key, so user_name parameter must be the same as the logged-in user. **Example request:** .. sourcecode:: http GET /api/v0/ical_key/user/jdoe HTTP/1.1 Content-Type: text/plain ef895425-5f49-11ea-8eee-10e7c6352aff """ challenger = req.context['user'] if challenger != user_name: raise HTTPForbidden( 'Unauthorized', 'Action not allowed: "%s" is not allowed to view ical_key of "%s"' % (challenger, user_name)) key = get_ical_key(challenger, user_name, 'user') if key is None: raise HTTPNotFound() resp.body = key resp.set_header('Content-Type', 'text/plain')
def on_patch_potential(self, req: Request, resp: Response, id: int): token = req.get_param('token', required=True) vote = req.get_param_as_int('vote', required=True, min_value=-1, max_value=1) user_data = get_user_data(token) if not user_data: raise HTTPUnauthorized('Invalid user token provided', 'Invalid user token provided') with self.uowm.start() as uow: template = uow.meme_template_potential.get_by_id(id) if not template: raise HTTPNotFound(title=f'Unable to find template with ID {id}', description=f'Unable to find template with ID {id}') existing_vote = next((x for x in template.votes if x.user == user_data['name']), None) if existing_vote and existing_vote.vote == vote: raise HTTPBadRequest(title='Invalid vote', description='You have already cast a vote for this template') elif existing_vote: template.vote_total += vote existing_vote.vote = vote else: template.vote_total += vote template.votes.append( MemeTemplatePotentialVote( post_id=template.post_id, user=user_data['name'], vote=vote, meme_template_potential_id=template.id ) ) uow.commit()
def on_delete(req, resp, team, user): """ Delete team admin user """ check_team_auth(team, req) connection = db.connect() cursor = connection.cursor() cursor.execute( '''DELETE FROM `team_admin` WHERE `team_id`=(SELECT `id` FROM `team` WHERE `name`=%s) AND `user_id`=(SELECT `id` FROM `user` WHERE `name`=%s)''', (team, user)) deleted = cursor.rowcount if deleted == 0: raise HTTPNotFound() create_audit({'user': user}, team, ADMIN_DELETED, req, cursor) # Remove user from the team if needed query = '''DELETE FROM `team_user` WHERE `user_id` = (SELECT `id` FROM `user` WHERE `name`=%s) AND `user_id` NOT IN (SELECT `roster_user`.`user_id` FROM `roster_user` JOIN `roster` ON `roster`.`id` = `roster_user`.`roster_id` WHERE team_id = (SELECT `id` FROM `team` WHERE `name`=%s) UNION (SELECT `user_id` FROM `team_admin` WHERE `team_id` = (SELECT `id` FROM `team` WHERE `name`=%s))) AND `team_user`.`team_id` = (SELECT `id` FROM `team` WHERE `name` = %s)''' cursor.execute(query, (user, team, team, team)) if cursor.rowcount != 0: unsubscribe_notifications(team, user, cursor) connection.commit() cursor.close() connection.close()
def on_get(self, req, resp, wf_id): self.log.debug("Getting workflow '{}'".format(wf_id)) rm = RubinWorkflowManager(req=req) wf = rm.get_workflow(wf_id) if not wf: raise HTTPNotFound() resp.media = sanitize(wf)
def on_delete(req, resp, notification_id): ''' Delete user notification settings by id. **Example request:** .. sourcecode:: http DELETE /api/v0/notifications/1234 HTTP/1.1 :statuscode 200: Successful delete :statuscode 404: Notification setting not found ''' connection = db.connect() cursor = connection.cursor() try: cursor.execute( 'SELECT `user`.`name` FROM `notification_setting` ' 'JOIN `user` ON `notification_setting`.`user_id` = `user`.`id` ' 'WHERE `notification_setting`.`id` = %s', notification_id) username = cursor.fetchone()[0] check_user_auth(username, req) cursor.execute('DELETE FROM notification_setting WHERE `id` = %s', notification_id) num_deleted = cursor.rowcount except: raise else: connection.commit() finally: cursor.close() connection.close() if num_deleted != 1: raise HTTPNotFound()
def get_instance(self, req, resp, ns_id, **kwargs): s = Services.__request_service__(kwargs.get('s_id')) for ns in s.network_services: if ns.id == ns_id: resp.body = self.format_body(ns) return raise HTTPNotFound()
def on_delete(req, resp, team, service): """ Delete service team mapping. Only allowed for team admins. **Example request:** .. sourcecode:: http DELETE /api/v0/teams/team-foo/services/service-foo HTTP/1.1 :statuscode 200: Successful delete :statuscode 404: Team-service mapping not found """ team = unquote(team) check_team_auth(team, req) connection = db.connect() cursor = connection.cursor() cursor.execute( '''DELETE FROM `team_service` WHERE `team_id`=(SELECT `id` FROM `team` WHERE `name`=%s) AND `service_id`=(SELECT `id` FROM `service` WHERE `name`=%s)''', (team, service)) deleted = cursor.rowcount if deleted == 0: raise HTTPNotFound() connection.commit() cursor.close() connection.close()
def on_delete(req, resp, team, user): """ Delete user from a team **Example request:** .. sourcecode:: http DELETE /api/v0/teams/team-foo/users/jdoe HTTP/1.1 :statuscode 200: Successful delete :statuscode 404: User not found in team """ team = unquote(team) check_team_auth(team, req) connection = db.connect() cursor = connection.cursor() cursor.execute( '''DELETE FROM `team_user` WHERE `team_id`=(SELECT `id` FROM `team` WHERE `name`=%s) AND `user_id`=(SELECT `id` FROM `user` WHERE `name`=%s)''', (team, user)) deleted = cursor.rowcount if deleted == 0: raise HTTPNotFound() connection.commit() cursor.close() connection.close()
def __handle__(*args, **kwargs): service = kwargs.get('service_name', 'Service') try: r = function(*args, **kwargs) if r.status_code == 404: raise HTTPNotFound() if r.status_code == 500: raise HTTPInternalServerError( 'Failed to process request on {}'.format(service), code='102') if r.status_code > 299: raise HTTPError(str(r.status_code)) return r except requests.exceptions.Timeout: logger.error('{} Inventory Timeout'.format(service)) raise HTTPError( HTTP_REQUEST_TIMEOUT, title='{} Timeout'.format(service), description='{} connection timeout'.format(service), code='100') except requests.exceptions.ConnectionError: raise HTTPError(HTTP_INTERNAL_SERVER_ERROR, title='{} Connection Error'.format(service), description='{} connection error'.format(service), code='101')
def on_delete(req, resp, team, roster, user): """ Delete user from roster **Example request**: .. sourcecode:: http DELETE /v0/api/teams/team_foo/rosters/best_coast/users/user1 HTTP/1.1 **Example response**: .. sourcecode:: http HTTP/1.1 200 OK Content-Type: application/json [] :statuscode 200: no error, user deleted from roster. :statuscode 404: roster not found. """ team, roster = unquote(team), unquote(roster) check_team_auth(team, req) connection = db.connect() cursor = connection.cursor() cursor.execute('''DELETE FROM `roster_user` WHERE `roster_id`=( SELECT `roster`.`id` FROM `roster` JOIN `team` ON `team`.`id`=`roster`.`team_id` WHERE `team`.`name`=%s AND `roster`.`name`=%s) AND `user_id`=(SELECT `id` FROM `user` WHERE `name`=%s)''', (team, roster, user)) deleted = cursor.rowcount if deleted == 0: raise HTTPNotFound() create_audit({'roster': roster, 'user': user}, team, ROSTER_USER_DELETED, req, cursor) # Remove user from the team if needed query = '''DELETE FROM `team_user` WHERE `user_id` = (SELECT `id` FROM `user` WHERE `name`=%s) AND `user_id` NOT IN ( SELECT `roster_user`.`user_id` FROM `roster_user` JOIN `roster` ON `roster`.`id` = `roster_user`.`roster_id` WHERE team_id = (SELECT `id` FROM `team` WHERE `name`=%s) UNION ( SELECT `user_id` FROM `team_admin` WHERE `team_id` = (SELECT `id` FROM `team` WHERE `name`=%s) ) ) AND `team_user`.`team_id` = (SELECT `id` FROM `team` WHERE `name` = %s)''' cursor.execute(query, (user, team, team, team)) if cursor.rowcount != 0: unsubscribe_notifications(team, user, cursor) connection.commit() cursor.close() connection.close() resp.status = HTTP_200 resp.body = '[]'
def on_get(self, req, resp, username): try: redis_cli = super().redis_client if redis_cli is not None: user_info = redis_cli.hget('USERS', username) access_info = redis_cli.hget('USERS_APIKEY', user_info['api_key']) access_token = '' if access_info is not None and access_info['access_token']: if redis_cli.exists(access_info['access_token']): access_token = access_info['access_token'] if user_info is not None: user_info = json.loads(user_info) resp.status = HTTP_200 resp.body = json.dumps( dict(status='Success', user=dict(username=user_info['username'], api_key=user_info['api_key'], access_token=access_token))) else: raise HTTPNotFound(description='No user with username {}'. format(username)) else: raise HTTPServiceUnavailable( description='Data instances are not yet active') except (HTTPNotFound, HTTPServiceUnavailable) as e: raise e except Exception as e: print('Exception in getting user', e) raise HTTPInternalServerError( description='Something went wrong while getting user info')
def get_instance(self, req, resp, app_id, **kwargs): s = Services.__request_service__(kwargs.get('s_id')) for app in s.sdn_apps: if app.id == app_id: resp.body = self.format_body(app) return raise HTTPNotFound()
def on_get(self, req, resp, wf_id, pod_id): self.log.debug( "Getting details for pod '{}' in workflow '{}'".format( pod_id, wf_id ) ) rm = RubinWorkflowManager(req=req) wf = rm.get_workflow(wf_id) if not wf: raise HTTPNotFound() nd = wf.status.nodes if not nd: raise HTTPNotFound() pod = nd.get(pod_id) if not pod: raise HTTPNotFound() resp.media = sanitize(pod)
def on_delete(self, req, resp, **kwargs): if len(kwargs) != 1 or 'package_id' not in kwargs: raise HTTPNotFound() endpoint = '{}{}'.format(ConfReader().get('APP_CATALOGUE', 'url'), kwargs.get('package_id')) request(endpoint, method='DELETE') resp.status = HTTP_204
def on_get(self, req: Request, res: Response, name: str): info = self.store.load(name) if info is None: raise HTTPNotFound() res.body = info["ip"] res.set_header("X-Updated", info["updated"])
def on_get(self, req, resp): db_session = req.context["db_session"] params = {} if not req.get_param("product", store=params): raise HTTPNotFound() try: product = db_session.query(Product).filter_by( id=int(params["product"])).one() except NoResultFound: raise HTTPNotFound() else: self.render_template(req, resp, "admin/product_configure.html", product=product)