Example #1
0
    def on_post(self, req: Request, resp: Response, subreddit: Text):
        log.info('Attempting to create monitored sub %s', subreddit)
        try:
            self.reddit.subreddit(subreddit).mod.accept_invite()
        except APIException as e:
            if e.error_type == 'NO_INVITE_FOUND':
                log.error('No open invite to %s', subreddit)
                raise HTTPInternalServerError(
                    f'No available invite for {subreddit}',
                    f'We were unable to find a '
                    f'pending mod invote for r/{subreddit}')
            else:
                log.exception('Problem accepting invite', exc_info=True)
                raise HTTPInternalServerError(
                    f'Unknown error accepting mod invite for r/{subreddit}',
                    f'Unknown error accepting mod invite for r/{subreddit}.  Please contact us'
                )
        except Exception as e:
            log.exception('Failed to accept invite', exc_info=True)
            raise HTTPInternalServerError(
                f'Unknown error accepting mod invite for r/{subreddit}',
                f'Unknown error accepting mod invite for r/{subreddit}.  Please contact us'
            )

        with self.uowm.start() as uow:
            existing = uow.monitored_sub.get_by_sub(subreddit)
            if existing:
                resp.body = json.dumps(existing.to_dict())
                return
            monitored_sub = create_monitored_sub_in_db(subreddit, uow)
            resp.body = json.dumps(monitored_sub.to_dict())
Example #2
0
 def call_jasmin(self, url, params=None):
     try:
         r = requests.get('%s/%s' % (old_api_uri, url), params=params)
     except requests.exceptions.ConnectionError as e:
         raise HTTPInternalServerError(
             'Jasmin httpapi connection error',
             'Could not connect to Jasmin http api (%s): %s' %
             (old_api_uri, e))
     except Exception as e:
         raise HTTPInternalServerError('Jasmin httpapi unknown error',
                                       str(e))
     else:
         return r.status_code, r.content.decode('utf-8').strip('"')
Example #3
0
 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')
Example #4
0
 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 '')
Example #5
0
 def main(self, run):
     try:
         if callable(run):
             run()
         else:
             raise Exception('run argument must be executable')
     # HttpError is different from HTTPError
     # HttpError is error from googleapiclient
     # HTTPError belongs to falcon
     except HttpError as err:
         status_code = err.resp.status
         if status_code == 404:
             from falcon import HTTP_404
             falcon_status = HTTP_404
         elif status_code == 403:
             from falcon import HTTP_403
             falcon_status = HTTP_403
         else:
             from falcon import HTTP_400
             falcon_status = HTTP_400
         raise HTTPError(falcon_status,
                         description=err._get_reason() or '',
                         code=status_code)
     except Exception as err:
         print('Exception in getting spreadsheet info', err)
         raise HTTPInternalServerError(
             description='Something went wrong while getting sheets info')
Example #6
0
 def _serialize_json_to_string(self, resp):
     if self._has_json(resp):
         if not isinstance(resp.json, (dict, list)):
             raise HTTPInternalServerError(
                 f'Unexpected error parsing response: payload={resp.json}')
         return json.dumps(resp.json)
     return json.dumps({})
Example #7
0
 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')
Example #8
0
 async def on_post(self, req, res, table):
     data = req.context['data']
     db_session = req.context['db_session']
     result = await self.insert_data(db_session, table, data)
     if result and "success" in result:
         if result["success"]:
             res.status = HTTP_200
             res.body = json.dumps(result)
         else: raise HTTPBadRequest(description=result["description"])
     else: raise HTTPInternalServerError()
Example #9
0
    def on_post(self, req, resp, spreadsheet_id):
        sheet_range = req.get_param('range', required=True)
        try:
            req_body = json.load(req.bounded_stream)
            if 'values' in req_body and isinstance(
                    req_body['values'], list) and len(req_body['values']):
                dimensions = 'dimensions' in req_body and req_body[
                    'dimensions'] or 'ROWS'
                value_input = 'value_input_option' in req_body and req_body[
                    'value_input_option'] or 'USER_ENTERED'
                insert_option = 'insert_option' in req_body and req_body[
                    'insert_option'] or 'INSERT_ROWS'
                try:
                    spreadsheets = DataStore.get_sheet_instance()
                except Exception as e:
                    print('Datastore is not configured properly', e)
                    raise HTTPServiceUnavailable(
                        description='Datastore is not configured properly')

                def run():
                    sheet_body = {
                        "values": req_body['values'],
                        "majorDimension": dimensions
                    }
                    response = spreadsheets.values().append(
                        spreadsheetId=spreadsheet_id,
                        body=sheet_body,
                        range=sheet_range,
                        valueInputOption=value_input,
                        insertDataOption=insert_option).execute()
                    resp.body = json.dumps(
                        dict(
                            status='Success',
                            message='Successfully Inserted data into sheet',
                            spreadsheet_id=response['spreadsheetId'],
                        ))
                    resp.status = HTTP_201

                super().main(run)
            else:
                raise HTTPPreconditionFailed(
                    description=
                    'Values is a mandatory and must be valid for this request')
        except JSONDecodeError as err:
            print('Request body received', req.bounded_stream.read())
            print('Error while processing request', err)
            raise HTTPUnprocessableEntity(
                description='Cannot parse the body from the request')
        except (HTTPServiceUnavailable, HTTPPreconditionFailed,
                HTTPError) as err:
            raise err
        except Exception as e:
            print('Exception in creating sheet', e)
            raise HTTPInternalServerError(
                description='Something went wrong while creating sheet')
Example #10
0
 def __handle__(*args, **kwargs):
     try:
         r = function(*args, **kwargs)
         return r
     except Exception as e:
         logger.exception('DB error: Topology')
         error = dict(title='Topology: Database Error')
         try:
             error['description'] = e.orig.msg
         except Exception:
             error['description'] = e.args[0]
         error['code'] = '105'
         raise HTTPInternalServerError(**error)
Example #11
0
    def on_put(self, req, resp, spreadsheet_id):
        value_input = req.get_param('value_input_option',
                                    default='USER_ENTERED')
        try:
            req_body = json.load(req.bounded_stream)
            if 'data' in req_body and isinstance(
                    req_body['data'], list) and len(req_body['data']):
                try:
                    spreadsheets = DataStore.get_sheet_instance()
                except Exception as e:
                    print('Datastore is not configured properly', e)
                    raise HTTPServiceUnavailable(
                        description='Datastore is not configured properly')

                def run():
                    sheet_body = {
                        "data": req_body['data'],
                        "valueInputOption": value_input
                    }
                    response = spreadsheets.values().batchUpdate(
                        spreadsheetId=spreadsheet_id,
                        body=sheet_body).execute()
                    resp.body = json.dumps(
                        dict(
                            status='Success',
                            message=
                            'Successfully updated the data in the sheet',
                            spreadsheet_id=response['spreadsheetId'],
                        ))
                    resp.status = HTTP_200

                super().main(run)
            else:
                raise HTTPPreconditionFailed(
                    description=
                    'Data is a mandatory and must be valid for this request')
        except JSONDecodeError as err:
            print('Request body received', req.bounded_stream.read())
            print('Error while processing request', err)
            raise HTTPUnprocessableEntity(
                description='Cannot parse the body from the request')
        except (HTTPServiceUnavailable, HTTPPreconditionFailed,
                HTTPError) as err:
            raise err
        except Exception as e:
            print('Exception in updating sheet info', e)
            raise HTTPInternalServerError(
                description='Something went wrong while updating sheet')
Example #12
0
    def __handle__(*args, **kwargs):
        """

        :param args:
        :param kwargs:
                        service_name: the name of the service that is using the requester
        :return: the response object if no error detected
        :raises:
                requests.exceptions.Timeout: when the timeout is reached
                requests.exceptions.ConnectionError: When no connection is available
        """
        service = kwargs.get('service_name', 'Service')
        if 'ignore_exception' in kwargs:
            r = function(*args, **kwargs)
            return r
        try:
            r = function(*args, **kwargs)
            if r.status_code == 401:
                raise HTTPUnauthorized(
                    title='You are not authorized',
                    description='Please validate your authentication')
            if r.status_code == 404:
                raise HTTPNotFound()
            if r.status_code == 500:
                logger.error('Internal server error, message {}'.format(
                    r.text))
                raise HTTPInternalServerError(
                    'Failed to process request on {}'.format(service),
                    code='102')
            if r.status_code > 299:
                logger.error('Failed to process request, message {}'.format(
                    r.text))
                raise HTTPError(str(r.status_code),
                                description=r.text,
                                code='103')
            return r
        except requests.exceptions.Timeout:
            logger.error('{} 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')
Example #13
0
def create_connection():
    # Build an object to manage our db connections.
    try:
        db_host = os.environ["DB_HOST"]
        db_name = os.environ["DB_NAME"]
        db_user = os.environ["DB_USER"]
        db_pass = os.environ["DB_PASS"]

        return "postgresql+psycopg2://{user}:{pwd}@{host}/{name}".format(
            user=db_user, pwd=db_pass, host=db_host, name=db_name)
    except KeyError:
        raise HTTPInternalServerError(
            description="The server could not reach the database, "
            "please contact your account manager.",
            code=9,
        )
Example #14
0
def internal_error_handler(ex, req, resp, params):
    """Whenever an non-falcon exception is raised, it wraps it into a falcon.HTTPInternalServererror exception.

    :param ex: The exception caught
    :type ex: Exception
    :param req: The falcon request object
    :type req: falcon.Request
    :param resp: The falcon response object
    :type resp: falcon.Response
    :param params: Additional requests parameters
    :type params: dict
    """
    if not isinstance(ex, HTTPError):
        raise HTTPInternalServerError(description=repr(ex))
    else:
        raise ex
Example #15
0
    def process_resource(self, req, resp, resource, params):
        if (self._is_middleware_enabled(resource)
                and self._has_request_method_payload(req)):
            if not self._is_content_type_valid(req):
                raise HTTPUnsupportedMediaType()

            try:
                req.text = self._get_payload(req)
                req.json = (json.loads(req.text, encoding='utf-8')
                            if req.text.strip() != '' else {})
            except JSONDecodeError as error:
                raise HTTPBadRequest(
                    f'Invalid JSON received: error={error}, payload={req.text}'
                )
            except Exception as error:
                raise HTTPInternalServerError(
                    f'Unexpected error: error={error}, payload={req.text}')
Example #16
0
    def on_post(self, req, resp):
        logger.info('Lambda function invoked')

        region_name = os.environ.get('AWS_REGION')
        bucket_name = os.getenv('SOURCE_BUCKET_NAME')

        try:
            response = client('s3', region_name=region_name).put_object(
                Bucket=bucket_name,
                Key=req.get_param('image').filename,
                Body=req.get_param('image').file,
                ContentType='application/jpeg')
        except BaseException as e:
            logger.exception(e)
            raise HTTPInternalServerError("Error storing response")

        resp.status = HTTP_201
        resp.media = json.dumps({"s3_put_response": response})
Example #17
0
    def on_patch(self, req: Request, resp: Response, subreddit: Text):
        token = req.get_param('token', required=True)
        user_data = get_user_data(token)
        if not is_sub_mod_token(token, subreddit,
                                self.config.reddit_useragent):
            raise HTTPUnauthorized(
                f'Not authorized to make changes to {subreddit}',
                f'You\'re not a moderator on {subreddit}')
        with self.uowm.start() as uow:
            monitored_sub = uow.monitored_sub.get_by_sub(subreddit)
            if not monitored_sub:
                raise HTTPNotFound(
                    title=f'Subreddit {subreddit} Not Found',
                    description=f'Subreddit {subreddit} Not Found')
            raw = json.load(req.bounded_stream)
            for k, v in raw.items():
                if k not in self.config.sub_monitor_exposed_config_options:
                    continue
                if hasattr(monitored_sub, k):
                    if getattr(monitored_sub, k) != v:
                        log.debug('Update %s config | %s: %s => %s', subreddit,
                                  k, getattr(monitored_sub, k), v)
                        uow.monitored_sub_config_change.add(
                            MonitoredSubConfigChange(
                                source='site',
                                subreddit=subreddit,
                                config_key=k,
                                old_value=str(getattr(monitored_sub, k)),
                                new_value=str(v),
                                updated_by=user_data['name']))
                        setattr(monitored_sub, k, v)
            try:
                uow.commit()
            except Exception as e:
                log.exception('Problem saving config', exc_info=True)
                raise HTTPInternalServerError(
                    title='Problem Saving Config',
                    description='Something went t**s up when saving the config'
                )

        celery.send_task(
            'redditrepostsleuth.core.celery.admin_tasks.update_subreddit_config_from_database',
            args=[monitored_sub, user_data],
            queue='monitored_sub_config_update')
Example #18
0
 def __handle__(*args, **kwargs):
     try:
         r = function(*args, **kwargs)
         return r
     except ServerSelectionTimeoutError:
         logger.error('DB Timeout')
         raise HTTPError(HTTP_REQUEST_TIMEOUT,
                         title='DB Timeout',
                         description='DB connection timeout',
                         code='100')
     except Exception as e:
         logger.exception('DB error')
         error = dict(title='Database Error')
         try:
             error['description'] = e.orig.msg
         except Exception:
             error['description'] = e.args[0]
         error['code'] = '105'
         raise HTTPInternalServerError(**error)
Example #19
0
 def on_get(self, req, resp):
     if self.dummy_status:
         status = self.dummy_status
     else:
         try:
             connection = db.connect()
             cursor = connection.cursor()
             cursor.execute("SELECT VERSION();")
             cursor.close()
             connection.close()
         except:
             raise HTTPInternalServerError()
         try:
             with open(self.path) as f:
                 status = f.readline().strip()
         except:
             raise HTTPNotFound()
     resp.content_type = 'text/plain'
     resp.body = status
Example #20
0
 def on_get(self, req, resp):
     if self.dummy_status:
         status = self.dummy_status
     else:
         try:
             connection = db.connect()
             cursor = connection.cursor()
             cursor.execute("SELECT VERSION();")
             cursor.close()
             connection.close()
         except Exception:
             logger.exception('failed to query DB for healthcheck')
             raise HTTPInternalServerError()
         try:
             with open(self.path) as f:
                 status = f.readline().strip()
         except IOError:
             logger.error('could not open healthcheck file')
             raise HTTPNotFound()
     resp.content_type = 'text/plain'
     resp.body = status
Example #21
0
 def on_post(self, req: Request, resp: Response):
     token = req.get_param('token', required=True)
     user_data = get_user_data(token)
     raw = json.load(req.bounded_stream)
     if not is_site_admin(user_data, self.uowm):
         raise HTTPUnauthorized(
             f'Not authorized to make this request',
             f'You are not authorized to make this request')
     with self.uowm.start() as uow:
         new_template = ConfigMessageTemplate(
             template_name=raw['template_name'],
             template=raw['template'],
             template_slug=raw['template_slug'])
         uow.config_message_template.add(new_template)
         try:
             resp.body = json.dumps(new_template.to_dict())
             uow.commit()
         except IntegrityError as e:
             raise HTTPInternalServerError(
                 title='Failed to save message template',
                 description=str(e))
Example #22
0
    async def on_get(self, req, res, table, id_):
        db_session = req.context['db_session']
        depth = 0

        if req.query_string:
            query = parse_query_string(req.query_string)

            if 'depth' in query:
                try:
                    depth = int(query['depth'])
                except ValueError:
                    pass

        result = await self.select_data(db_session, table, id_, depth=depth)

        if result and "success" in result:
            if result["success"]:
                res.status = HTTP_200
                res.body = json.dumps(result)
            else: raise HTTPBadRequest(description=result["description"])
        else: raise HTTPInternalServerError()
Example #23
0
 def on_delete(self, req, resp, username):
     try:
         redis_cli = super().redis_client
         if redis_cli is not None:
             user_info = redis_cli.hdel('USERS', username)
             if user_info:
                 resp.status = HTTP_200
                 resp.body = json.dumps(
                     dict(status='Success',
                          message='Successfully deleted the user'))
             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 deleting user', e)
         raise HTTPInternalServerError(
             description='Something went wrong while deleting user info')
Example #24
0
 def on_put(self, req, resp, username):
     token = req.get_header('Authorization')
     is_active = req.get_param_as_bool('is_active', required=True)
     try:
         redis_cli = super().redis_client
         if redis_cli is not None and 'auth_info' in req.context:
             temp_auth_info = json.loads(req.context['auth_info'])
             temp_auth_info.is_active = is_active
             redis_cli.hset('USERS_APIKEY', token,
                            json.dumps(temp_auth_info))
             resp.status = HTTP_200
             resp.body = json.dumps(
                 dict(status='Success',
                      message='Successfully updated the staus of the user'))
         else:
             raise HTTPServiceUnavailable(
                 description='Data instances are not yet active')
     except (HTTPNotFound, HTTPServiceUnavailable) as e:
         raise e
     except Exception as e:
         print('Exception in deleting user', e)
         raise HTTPInternalServerError(
             description='Something went wrong while deleting user info')
Example #25
0
 def on_post(self, req, resp, auth_type):
     if auth_type == 'login':
         try:
             req_body = json.load(req.bounded_stream)
             if 'username' in req_body and req_body[
                     'username'] and 'password' in req_body and len(
                         req_body['password']) > 5:
                 username = req_body['username']
                 redis_cli = super().redis_client
                 if redis_cli is not None:
                     user_info = redis_cli.hget('USERS', username)
                     if user_info is not None:
                         user_info = json.loads(user_info)
                         api_key = user_info['api_key']
                         hash_password = hashlib.pbkdf2_hmac(
                             'sha256',
                             req_body['password'].encode('utf-8'),
                             api_key[8:32].encode('utf-8'),
                             100000,
                             dklen=128)
                         if user_info['password'] == hash_password.hex():
                             access_info = redis_cli.hget(
                                 'USERS_APIKEY', api_key)
                             access_info = json.loads(access_info)
                             if access_info is not None and access_info[
                                     'is_active']:
                                 access_token = access_info['access_token']
                                 if not redis_cli.exists(access_token):
                                     access_token = super().generate_token(
                                         32)
                                     access_info[
                                         'access_token'] = access_token
                                     access_info = redis_cli.hset(
                                         'USERS_APIKEY', api_key,
                                         json.dumps(access_info))
                                 redis_cli.set(access_token,
                                               api_key,
                                               ex=28800)
                                 resp.status = HTTP_200
                                 resp.body = json.dumps(
                                     dict(status='Success',
                                          user=dict(
                                              api_key=api_key,
                                              access_token=access_token,
                                              username=username)))
                             else:
                                 raise HTTPNotAcceptable(
                                     description='User is not active')
                         else:
                             raise HTTPUnauthorized(
                                 description=
                                 'Username and password doesnot match')
                     else:
                         raise HTTPNotFound(
                             description='No user with username {}'.format(
                                 username))
                 else:
                     raise HTTPServiceUnavailable(
                         description='Data instances are not yet active')
             else:
                 raise HTTPPreconditionFailed(
                     description=
                     'Username and password are mandatory and must be valid for this request'
                 )
         except JSONDecodeError as err:
             print('Request body received', req.bounded_stream.read())
             print('Error while processing request', err)
             raise HTTPUnprocessableEntity(
                 description='Cannot parse the body from the request')
         except (HTTPPreconditionFailed, HTTPServiceUnavailable,
                 HTTPNotFound, HTTPUnauthorized, HTTPNotAcceptable) as err:
             raise err
         except Exception as e:
             print('Exception in signing in user', e)
             raise HTTPInternalServerError(
                 description='Something went wrong while creating user info'
             )
     elif auth_type == 'logout':
         try:
             api_key = req.get_header('Authorization')
             redis_cli = super().redis_client
             if redis_cli is not None:
                 access_info = redis_cli.hget('USERS_APIKEY', api_key)
                 access_info = json.loads(access_info)
                 access_token = access_info['access_token']
                 redis_cli.delete(access_token)
                 resp.status = HTTP_200
                 resp.body = json.dumps(
                     dict(status='Succcess',
                          message='Successfully signed out'))
             else:
                 raise HTTPServiceUnavailable(
                     description='Data instances are not yet active')
         except Exception as err:
             print('Exception while signing out', err)
             raise HTTPInternalServerError(
                 description='Something went wrong while signing out')
     else:
         raise HTTPBadRequest(description='The request is not valid')
Example #26
0
 def on_post(self, req, resp, username):
     try:
         req_body = json.load(req.bounded_stream)
         if username and 'password' in req_body and len(
                 req_body['password']) > 5:
             redis_cli = super().redis_client
             if redis_cli is not None:
                 password = req_body['password']
                 api_key = super().generate_token(32)
                 access_token = super().generate_token(32)
                 hash_password = hashlib.pbkdf2_hmac(
                     'sha256',
                     password.encode('utf-8'),
                     api_key[8:32].encode('utf-8'),
                     100000,
                     dklen=128)
                 user_info = dict(username=username,
                                  password=hash_password.hex(),
                                  api_key=api_key)
                 access_info = dict(username=username,
                                    is_active=True,
                                    access_token=access_token)
                 try:
                     if not redis_cli.hexists('USERS', username):
                         redis_cli.hset('USERS', username,
                                        json.dumps(user_info))
                         redis_cli.hset('USERS_APIKEY', api_key,
                                        json.dumps(access_info))
                         redis_cli.set(access_token, api_key, ex=28800)
                         resp.status = HTTP_201
                         resp.body = json.dumps(
                             dict(status='Succcess',
                                  message='Successfully created the user',
                                  user=dict(api_key=api_key,
                                            access_token=access_token,
                                            username=username)))
                     else:
                         raise HTTPConflict(
                             description=
                             'User already exists with username {}'.format(
                                 username))
                 except HTTPConflict as err:
                     raise err
                 except Exception as err:
                     raise Exception(
                         'Something went wrong while executing redis commands',
                         err)
             else:
                 raise HTTPServiceUnavailable(
                     description='Data instances are not yet active')
         else:
             raise HTTPPreconditionFailed(
                 description=
                 'Username and password are mandatory and must be valid for this request'
             )
     except JSONDecodeError as err:
         print('Request body received', req.bounded_stream.read())
         print('Error while processing request', err)
         raise HTTPUnprocessableEntity(
             description='Cannot parse the body from the request')
     except (HTTPPreconditionFailed, HTTPServiceUnavailable,
             HTTPConflict) as err:
         raise err
     except Exception as e:
         print('Exception in creating user', e)
         raise HTTPInternalServerError(
             description='Something went wrong while creating user info')
Example #27
0
 def process_resource(self, req, resp, resource, params):
     template = req.uri_template
     method = req.method
     if 'auth_type' in params and params['auth_type'] == 'login':
         pass
     else:
         if template in AUTHENTICATION_VALIDATION_PATHS and method in AUTHENTICATION_VALIDATION_PATHS[
                 template]:
             auth = req.get_header('Authorization')
             if auth and auth is not None:
                 try:
                     redis_cli = Redis.get_redis_client()
                     auth_info = redis_cli.hget('USERS_APIKEY', auth)
                     if auth_info is not None:
                         auth_info = json.loads(auth_info)
                         if auth_info['is_active']:
                             if template in ACCESS_TOKEN_VALIDATION_PATHS and method in ACCESS_TOKEN_VALIDATION_PATHS[
                                     template]:
                                 access_token = req.get_param(
                                     'access_token')
                                 if access_token and access_token is not None:
                                     if auth_info[
                                             'access_token'] == access_token:
                                         if not redis_cli.exists(
                                                 auth_info['access_token']):
                                             raise HTTPUnauthorized(
                                                 description=
                                                 'Access token is expired. Please login again and continue'
                                             )
                                     else:
                                         raise HTTPForbidden(
                                             description=
                                             'Access token is not valid.')
                                 else:
                                     raise HTTPBadRequest(
                                         description=
                                         'Access token is not valid.')
                             else:
                                 raise HTTPUnauthorized(
                                     description=
                                     'access_token is mandatory to acccess the api.'
                                 )
                         else:
                             raise HTTPBadRequest(
                                 description='Client is not active.')
                     else:
                         raise HTTPUnauthorized(
                             description=
                             'Token sent in Authroization header is not valid.'
                         )
                 except (HTTPUnauthorized, HTTPBadRequest) as err:
                     raise err
                 except Exception as err:
                     print(
                         'Exception while accessing redis client instance',
                         err)
                     raise HTTPInternalServerError(
                         description='Something went wrong in server')
             else:
                 raise HTTPUnauthorized(
                     description=
                     'Authorization header is mandatory to process the request.'
                 )
Example #28
0
 def unexpected(ex, req, resp, params):
     ex_msg = ''.join(traceback.format_tb(ex.__traceback__))
     raise HTTPInternalServerError(ex.__class__.__name__, ex_msg)
Example #29
0
"""
DebateService exceptions
"""
from falcon import (HTTPBadRequest, HTTPInternalServerError, HTTPNotFound)


class ParseException(Exception):
    """
    An exception to raise if an error occurs while parsing an opinion page
    """


parse_error = HTTPInternalServerError({
    "title":
    "Internal server error",
    "description":
    "The opinion could not be parsed."
})

not_understood = HTTPBadRequest({
    "title":
    "Bad request",
    "description":
    "The request was not understood."
})

not_found = HTTPNotFound()

internal_server_error = HTTPInternalServerError({
    "title":
    "Internal server error",