def wrapper(self, req, resp, *args, **kwargs):
            validated_params = None
            validated_payload = None

            if params_schema:
                validated_params, errors = params_schema().load(req.params)
                if errors:
                    if error_schema is not None:
                        errors, n = error_schema().dump(errors)
                    raise HTTPError(HTTP_422, description=errors)

            if payload_schema:
                validated_payload, errors = payload_schema().load(req.media)
                if errors:
                    if error_schema is not None:
                        errors, n = error_schema().dump(errors)
                    raise HTTPError(HTTP_422, description=errors)

            return func(self,
                        req,
                        resp,
                        *args,
                        validated_params=validated_params,
                        validated_payload=validated_payload,
                        description=description,
                        summary=summary,
                        response_schema=response_schema,
                        error_schema=error_schema,
                        success_response_code=success_response_code,
                        **kwargs)
Пример #2
0
def on_post(req, resp, team, roster):
    """
    Add user to a roster for a team
    """
    team, roster = unquote(team), unquote(roster)
    data = load_json_body(req)

    user_name = data.get('name')
    in_rotation = int(data.get('in_rotation', True))
    if not user_name:
        raise HTTPBadRequest('incomplete data', 'missing field "name"')
    check_team_auth(team, req)

    connection = db.connect()
    cursor = connection.cursor()
    cursor.execute(
        '''(SELECT `id` FROM `team` WHERE `name`=%s)
                      UNION
                      (SELECT `id` FROM `user` WHERE `name`=%s)''',
        (team, user_name))
    results = [r[0] for r in cursor]
    if len(results) < 2:
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError',
                        'invalid team or user')

    # TODO: validate roster
    (team_id, user_id) = results
    try:
        # also make sure user is in the team
        cursor.execute(
            '''INSERT IGNORE INTO `team_user` (`team_id`, `user_id`) VALUES (%r, %r)''',
            (team_id, user_id))
        cursor.execute(
            '''INSERT INTO `roster_user` (`user_id`, `roster_id`, `in_rotation`)
                          VALUES (
                              %r,
                              (SELECT `roster`.`id` FROM `roster`
                               JOIN `team` ON `team`.`id`=`roster`.`team_id`
                               WHERE `team`.`name`=%s AND `roster`.`name`=%s),
                               %s
                          )''', (user_id, team, roster, in_rotation))
        # subscribe user to notifications
        subscribe_notifications(team, user_name, cursor)

        create_audit(
            {
                'roster': roster,
                'user': user_name,
                'request_body': data
            }, team, ROSTER_USER_ADDED, req, cursor)
        connection.commit()
    except db.IntegrityError:
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError',
                        'user "%(name)s" is already in the roster' % data)
    finally:
        cursor.close()
        connection.close()

    resp.status = HTTP_201
    resp.body = json_dumps(get_user_data(None, {'name': user_name})[0])
Пример #3
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')
Пример #4
0
 def __init__(self, code=0):
     global Error_text
     self.code = code
     if self.code not in Error_text.keys():
         self.code = 0
     self.text = Error_text[self.code][0]
     self.http_code = Error_text[self.code][1]
     HTTPError.__init__(self, self.http_code, self.text, code=self.code)
Пример #5
0
 def __init__(self, code=0):
     global Error_text
     self.code = code
     if self.code not in Error_text.keys():
         self.code = 0
     self.text = Error_text[self.code][0]
     self.http_code = Error_text[self.code][1]
     HTTPError.__init__(self, self.http_code, self.text, code=self.code)
Пример #6
0
def score_message(hug_token, message_id: hug.types.number,
                  score: hug.types.number):
    try:
        msg = Message.get(Message.token == Token.get(Token.token == hug_token),
                          Message.id == message_id, Message.reply_to != None)
        Score.create(message=msg, value=score)
        return {"status": "ok"}
    except Message.DoesNotExist:
        raise HTTPError(HTTP_404)
    except peewee.IntegrityError:
        raise HTTPError(HTTP_409)
Пример #7
0
def registration(login: hug.types.text, password: hug.types.text):

    if len(password) >= 6:
        password = hashlib.sha1(password.encode()).hexdigest()
    else:
        raise HTTPError(HTTP_422)

    token = uuid.uuid4().hex
    token = Token.create(token=token)
    try:
        User.create(**locals())
    except peewee.IntegrityError:
        token.delete()
        raise HTTPError(HTTP_409)
    return {'status': 'ok'}
Пример #8
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')
Пример #9
0
def on_post(req, resp, team):
    """
    Add user as team admin
    """
    team = unquote(team)
    check_team_auth(team, req)
    data = load_json_body(req)

    user_name = data.get('name')
    if not user_name:
        raise HTTPBadRequest('name attribute missing from request')

    connection = db.connect()
    cursor = connection.cursor()

    cursor.execute('''(SELECT `id` FROM `team` WHERE `name`=%s)
                      UNION
                      (SELECT `id` FROM `user` WHERE `name`=%s)''', (team, user_name))
    results = [r[0] for r in cursor]
    if len(results) < 2:
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError', 'invalid team or user')
    (team_id, user_id) = results

    try:
        # also make sure user is in the team
        cursor.execute('''INSERT IGNORE INTO `team_user` (`team_id`, `user_id`) VALUES (%r, %r)''',
                       (team_id, user_id))
        cursor.execute('''INSERT INTO `team_admin` (`team_id`, `user_id`) VALUES (%r, %r)''',
                       (team_id, user_id))
        # subscribe user to team notifications
        subscribe_notifications(team, user_name, cursor)
        create_audit({'user': user_name}, team, ADMIN_CREATED, req, cursor)
        connection.commit()
    except db.IntegrityError as e:
        err_msg = str(e.args[1])
        if err_msg == "Column 'team_id' cannot be null":
            err_msg = 'team %s not found' % team
        if err_msg == "Column 'user_id' cannot be null":
            err_msg = 'user %s not found' % data['name']
        else:
            err_msg = 'user name "%s" is already an admin of team %s' % (data['name'], team)
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError', err_msg)
    finally:
        cursor.close()
        connection.close()

    resp.status = HTTP_201
    resp.body = json_dumps(get_user_data(None, {'name': user_name})[0])
Пример #10
0
def on_post(req, resp, team):
    data = load_json_body(req)
    check_team_auth(team, req)
    sub_name = data.get('subscription')
    role_name = data.get('role')
    if not sub_name or not role_name:
        raise HTTPBadRequest('Invalid subscription',
                             'Missing subscription name or role name')
    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute(
            '''INSERT INTO `team_subscription` (`team_id`, `subscription_id`, `role_id`) VALUES
                          ((SELECT `id` FROM `team` WHERE `name` = %s),
                           (SELECT `id` FROM `team` WHERE `name` = %s),
                           (SELECT `id` FROM `role` WHERE `name` = %s))''',
            (team, sub_name, role_name))
    except db.IntegrityError as e:
        err_msg = str(e.args[1])
        if err_msg == 'Column \'team_id\' cannot be null':
            err_msg = 'team "%s" not found' % team
        elif err_msg == 'Column \'role_id\' cannot be null':
            err_msg = 'role "%s" not found' % role_name
        elif err_msg == 'Column \'subscription_id\' cannot be null':
            err_msg = 'team "%s" not found' % sub_name
        logger.exception('Unknown integrity error in team_subscriptions')
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError', err_msg)
    else:
        connection.commit()
    finally:
        cursor.close()
        connection.close()

    resp.status = HTTP_201
Пример #11
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')
Пример #12
0
 def __call__(self, ex, req, resp, params):
     # type: (Exception, Request, response, dict) -> None
     logger.warning('Exception occurred on request %s %s',
                    req.method,
                    req.uri,
                    exc_info=ex)
     raise HTTPError(self._status, self._title, str(ex))
Пример #13
0
def on_put(req, resp, team):
    team = unquote(team)
    check_team_auth(team, req)
    data = load_json_body(req)

    connection = db.connect()
    cursor = connection.cursor()

    data_cols = data.keys()
    if 'name' in data:
        invalid_char = invalid_char_reg.search(data['name'])
        if invalid_char:
            raise HTTPBadRequest('invalid team name',
                                 'team name contains invalid character "%s"' % invalid_char.group())
    set_clause = ', '.join(['`{0}`=%s'.format(d) for d in data_cols if d in cols])
    query_params = tuple(data[d] for d in data_cols) + (team,)
    try:
        update_query = 'UPDATE `team` SET {0} WHERE name=%s'.format(set_clause)
        cursor.execute(update_query, query_params)
        create_audit({'request_body': data}, team, TEAM_EDITED, req, cursor)
        connection.commit()
    except db.IntegrityError as e:
        err_msg = str(e.args[1])
        if 'Duplicate entry' in err_msg:
            err_msg = "A team named '%s' already exists" % (data['name'])
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError', err_msg)
    finally:
        cursor.close()
        connection.close()
Пример #14
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 '')
Пример #15
0
def get_token(login: hug.types.text, password: hug.types.text):
    try:
        user = User.get(login=login,
                        password=hashlib.sha1(password.encode()).hexdigest())
        return {'token': user.token.token}
    except User.DoesNotExist:
        raise HTTPError(HTTP_404)
Пример #16
0
def on_post(req, resp, team):
    """
    Create team to service mapping
    """
    team = unquote(team)
    check_team_auth(team, req)
    data = load_json_body(req)

    service = data['name']
    connection = db.connect()
    cursor = connection.cursor()
    try:
        # TODO: allow many to many mapping for team/service?
        cursor.execute(
            '''SELECT `team`.`name` from `team_service`
                          JOIN `team` ON `team`.`id` = `team_service`.`team_id`
                          JOIN `service` ON `service`.`id` = `team_service`.`service_id`
                          WHERE `service`.`name` = %s''', service)
        claimed_team = [r[0] for r in cursor]
        if claimed_team:
            raise HTTPError(
                '422 Unprocessable Entity', 'IntegrityError',
                'service "%s" alread claimed by team "%s"' %
                (service, claimed_team[0]))

        cursor.execute(
            '''INSERT INTO `team_service` (`team_id`, `service_id`)
                          VALUES (
                              (SELECT `id` FROM `team` WHERE `name`=%s),
                              (SELECT `id` FROM `service` WHERE `name`=%s)
                          )''', (team, service))
        connection.commit()
    except db.IntegrityError as e:
        err_msg = str(e.args[1])
        if err_msg == 'Column \'service_id\' cannot be null':
            err_msg = 'service "%s" not found' % service
        elif err_msg == 'Column \'team_id\' cannot be null':
            err_msg = 'team "%s" not found' % team
        elif 'Duplicate entry' in err_msg:
            err_msg = 'service name "%s" is already associated with team %s' % (
                service, team)
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError', err_msg)
    finally:
        cursor.close()
        connection.close()

    resp.status = HTTP_201
Пример #17
0
def on_post(req, resp):
    if 'user' not in req.context:
        # ban API auth because we don't know who to set as team admin
        raise HTTPBadRequest('invalid login',
                             'API key auth is not allowed for team creation')

    data = load_json_body(req)
    if not data.get('name'):
        raise HTTPBadRequest('', 'name attribute missing from request')
    if not data.get('scheduling_timezone'):
        raise HTTPBadRequest(
            '', 'scheduling_timezone attribute missing from request')
    team_name = unquote(data['name'])
    invalid_char = invalid_char_reg.search(team_name)
    if invalid_char:
        raise HTTPBadRequest(
            'invalid team name',
            'team name contains invalid character "%s"' % invalid_char.group())

    scheduling_timezone = unquote(data['scheduling_timezone'])
    slack = data.get('slack_channel')
    if slack and slack[0] != '#':
        raise HTTPBadRequest('invalid slack channel',
                             'slack channel name needs to start with #')
    email = data.get('email')

    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute(
            '''
            INSERT INTO `team` (`name`, `slack_channel`, `email`, `scheduling_timezone`)
            VALUES (%s, %s, %s, %s)''',
            (team_name, slack, email, scheduling_timezone))
        team_id = cursor.lastrowid
        query = '''
            INSERT INTO `team_user` (`team_id`, `user_id`)
            VALUES (%s, (SELECT `id` FROM `user` WHERE `name` = %s))'''
        cursor.execute(query, (team_id, req.context['user']))
        query = '''
            INSERT INTO `team_admin` (`team_id`, `user_id`)
            VALUES (%s, (SELECT `id` FROM `user` WHERE `name` = %s))'''
        cursor.execute(query, (team_id, req.context['user']))
        subscribe_notifications(team_name, req.context['user'], cursor)
        create_audit({'team_id': team_id}, data['name'], TEAM_CREATED, req,
                     cursor)
        connection.commit()
    except db.IntegrityError:
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError',
                        'team name "%s" already exists' % team_name)
    finally:
        cursor.close()
        connection.close()

    resp.status = HTTP_201
Пример #18
0
def on_put(req, resp, team, roster):
    """
    Change roster name. Must have team admin privileges.

        **Example request:**

    .. sourcecode:: http

        PUT /api/v0/teams/team-foo/rosters/roster-foo HTTP/1.1
        Content-Type: application/json

        {
            "name": "roster-bar",
        }

    :statuscode 400: Invalid roster name, disallowed characters
    :statuscode 422: Duplicate roster name for team
    """
    team, roster = unquote(team), unquote(roster)
    data = load_json_body(req)
    name = data.get('name')
    check_team_auth(team, req)

    if not name:
        raise HTTPBadRequest('invalid team name', 'team name is missing')
    if name == roster:
        return
    invalid_char = invalid_char_reg.search(name)
    if invalid_char:
        raise HTTPBadRequest(
            'invalid team name',
            'team name contains invalid character "%s"' % invalid_char.group())

    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute(
            '''UPDATE `roster` SET `name`=%s
               WHERE `team_id`=(SELECT `id` FROM `team` WHERE `name`=%s)
                   AND `name`=%s''', (name, team, roster))
        create_audit({
            'old_name': roster,
            'new_name': name
        }, team, ROSTER_EDITED, req, cursor)
        connection.commit()
    except db.IntegrityError as e:
        err_msg = str(e.args[1])
        if 'Duplicate entry' in err_msg:
            err_msg = "roster '%s' already existed for team '%s'" % (name,
                                                                     team)
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError', err_msg)
    finally:
        cursor.close()
        connection.close()
Пример #19
0
def parse_item(req):
    """
    Do some validation on the request and decode the json
    :param req: a falcon request object
    :return: item dictionary
    """
    if not req.content_length:
        raise HTTPError(status="400 no content found")
    try:
        item = json.load(req.stream)
    except ValueError:
        raise HTTPError(status="400 invalid JSON")
    if 'cart_id' in item and not is_valid_cart_id(item.get('cart_id')):
        raise HTTPError(status="400 invalid cart_id")
    if 'cart_id' in req.cookies and not is_valid_cart_id(
            req.cookies.get('cart_id')):
        raise HTTPError(status="400 invalid cart_id")
    if 'external_id' not in item:
        raise HTTPError(status="400 external_id is required")
    return item
Пример #20
0
def start_new(filename, settings, overwrite):
    overwrite = str_to_bool(overwrite)
    if not overwrite and HoodTracker.saveFileExists(filename):
        raise HTTPError(
            falcon.HTTP_409,
            title="File Exists",
            description=f'A save file named {filename} already exists')

    global save_filename, settings_string
    save_filename = filename
    settings_string = settings
    return step(new_game=True)
Пример #21
0
def http_error_factory(status: str = HTTP_799,
                       title: str = __default_human_title,
                       description: str = __default_description,
                       headers: Union[Dict[str, str], List[Tuple[str,
                                                                 str]]] = None,
                       href: str = None,
                       href_text: str = None,
                       code: int = None) -> HTTPError:
    """ Returns a raise-able HTTPError based on the input parameters

    :param status: HTTP status code and text, such as '400 Bad Request'
    :type status: str
    :param title: Human-friendly error title. If not provided, defaults to the HTTP status line as determined by the
        :code`status` parameter
    :type title: str
    :param description: Human-friendly description of the error, along with a helpful suggestion or two (default `None`)
    :type description: str
    :param headers: A dict of header names and values to set, or a list of (*name*, *value*) tuples. Both *name* and
        *value* must be of type str or StringType, and only character values 0x00 through 0xFF may be used on platforms
        that use wide characters

        Note:
            The Content-Type header, if present, will be overridden. If
            you wish to return custom error messages, you can create
            your own HTTP error class, and install an error handler
            to convert it into an appropriate HTTP response for the
            client

        Note:
            Falcon can process a list of tuple slightly faster
            than a dict
    :type headers: Union[Dict[str, str], List[Tuple[str, str]]]
    :param href: A URL someone can visit to find out more information (default None). Unicode characters are
        percent-encoded
    :type href: str
    :param href_text: If href is given, use this as the friendly  title/description for the link (default 'API
        documentation for this error')
    :type href_text: str
    :param code: An internal code that customers can reference in their support request or to help them when searching
        for knowledge base articles related to this error (default ``None``)
    :type code: int
    :return: Falcon HTTP Error
    :rtype: HTTPError
    """
    logger.error(msg='{status}: {title}\n\t\t{description}'.format(
        status=status, title=title, description=description))
    return HTTPError(status=status,
                     title=title,
                     description=description,
                     headers=headers,
                     href=href,
                     href_text=href_text,
                     code=code)
Пример #22
0
def on_post(req, resp, team):
    """
    Add user to a team
    """
    check_team_auth(team, req)
    data = load_json_body(req)

    user_name = data.get('name')
    if not user_name:
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError',
                        'name missing for user')

    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute(
            '''INSERT INTO `team_user` (`team_id`, `user_id`)
                          VALUES (
                              (SELECT `id` FROM `team` WHERE `name`=%s),
                              (SELECT `id` FROM `user` WHERE `name`=%s)
                          )''', (team, user_name))
        connection.commit()
    except db.IntegrityError as e:
        err_msg = str(e.args[1])
        if err_msg == 'Column \'user_id\' cannot be null':
            err_msg = 'user %s not found' % user_name
        elif err_msg == 'Column \'team_id\' cannot be null':
            err_msg = 'team %s not found' % team
        elif 'Duplicate entry' in err_msg:
            err_msg = 'user name "%s" is already in team %s' % (user_name,
                                                                team)
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError', err_msg)
    finally:
        cursor.close()
        connection.close()

    resp.status = HTTP_201
    resp.body = json_dumps(get_user_data(None, {'name': user_name})[0])
Пример #23
0
def on_post(req, resp, user_name):
    '''
    Pin a team to the landing page for a user

    **Example request**:

    .. sourcecode:: http

        POST /api/v0/users/jdoe/pinned_teams HTTP/1.1
        Host: example.com

        {
            "team": "team-foo"
        }

    :statuscode 201: Successful team pin
    :statuscode 400: Missing team parameter or team already pinned
    '''
    check_user_auth(user_name, req)
    data = load_json_body(req)
    team = data.get('team')
    if team is None:
        raise HTTPBadRequest('Invalid team pin', 'Missing team parameter')
    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute('''INSERT INTO `pinned_team` (`user_id`, `team_id`)
                          VALUES ((SELECT `id` FROM `user` WHERE `name` = %s),
                                  (SELECT `id` FROM `team` WHERE `name` = %s))''',
                       (user_name, team))
        connection.commit()
    except db.IntegrityError as e:
        # Duplicate key
        if e.args[0] == 1062:
            raise HTTPBadRequest('Invalid team pin', 'Team already pinned for this user')
        # Team/user is null
        elif e.args[0] == 1048:
            err_msg = str(e.args[1])
            if err_msg == 'Column \'user_id\' cannot be null':
                err_msg = 'user "%s" not found' % user_name
            elif err_msg == 'Column \'team_id\' cannot be null':
                err_msg = 'team "%s" not found' % team
            raise HTTPError('422 Unprocessable Entity', 'IntegrityError', err_msg)
    finally:
        cursor.close()
        connection.close()
    resp.status = HTTP_201
Пример #24
0
def on_post(req, resp):
    data = load_json_body(req)

    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute('INSERT INTO `service` (`name`) VALUES (%(name)s)',
                       data)
        connection.commit()
    except db.IntegrityError:
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError',
                        'service name "%(name)s" already exists' % data)
    finally:
        cursor.close()
        connection.close()

    resp.status = HTTP_201
Пример #25
0
def on_post(req, resp):
    """
    Create user. Currently used only in debug mode.
    """
    data = load_json_body(req)
    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute('INSERT INTO `user` (`name`) VALUES (%(name)s)', data)
        connection.commit()
    except db.IntegrityError:
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError',
                        'user name "%(name)s" already exists' % data)
    finally:
        cursor.close()
        connection.close()

    resp.status = HTTP_201
Пример #26
0
def on_post(req, resp):
    data = load_json_body(req)
    new_role = data['name']
    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute('INSERT INTO `role` (`name`) VALUES (%s)', new_role)
        connection.commit()
    except db.IntegrityError as e:
        err_msg = str(e.args[1])
        if 'Duplicate entry' in err_msg:
            err_msg = 'role "%s" already existed' % new_role
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError', err_msg)
    finally:
        cursor.close()
        connection.close()

    resp.status = HTTP_201
Пример #27
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)
Пример #28
0
def on_get(req, resp, team):
    """
    Get roster info(including schedules) for a team
    """
    team = unquote(team)
    connection = db.connect()
    cursor = connection.cursor(db.DictCursor)

    cursor.execute('SELECT `id` FROM `team` WHERE `name`=%s', team)
    if cursor.rowcount != 1:
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError',
                        'team "%s" not found' % team)

    team_id = cursor.fetchone()['id']
    rosters = get_roster_by_team_id(cursor, team_id, req.params)

    cursor.close()
    connection.close()
    resp.body = json_dumps(rosters)
Пример #29
0
def on_post(req, resp, team):
    """
    Create a roster for a team
    """
    team = unquote(team)
    data = load_json_body(req)

    roster_name = data.get('name')
    if not roster_name:
        raise HTTPBadRequest('name attribute missing from request', '')
    invalid_char = invalid_char_reg.search(roster_name)
    if invalid_char:
        raise HTTPBadRequest(
            'invalid roster name',
            'roster name contains invalid character "%s"' %
            invalid_char.group())

    check_team_auth(team, req)

    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute(
            '''INSERT INTO `roster` (`name`, `team_id`)
                          VALUES (%s, (SELECT `id` FROM `team` WHERE `name`=%s))''',
            (roster_name, team))
    except db.IntegrityError:
        raise HTTPError(
            '422 Unprocessable Entity', 'IntegrityError',
            'roster name "%s" already exists for team %s' %
            (roster_name, team))
    create_audit({
        'roster_id': cursor.lastrowid,
        'request_body': data
    }, team, ROSTER_CREATED, req, cursor)
    connection.commit()
    cursor.close()
    connection.close()

    resp.status = HTTP_201
Пример #30
0
def on_put(req, resp, team, roster):
    """
    Change roster name
    """
    team, roster = unquote(team), unquote(roster)
    data = load_json_body(req)

    check_team_auth(team, req)
    if data['name'] == roster:
        return
    invalid_char = invalid_char_reg.search(data['name'])
    if invalid_char:
        raise HTTPBadRequest(
            'invalid team name',
            'team name contains invalid character "%s"' % invalid_char.group())

    connection = db.connect()
    cursor = connection.cursor()
    try:
        cursor.execute(
            '''UPDATE `roster` SET `name`=%s
               WHERE `team_id`=(SELECT `id` FROM `team` WHERE `name`=%s)
                   AND `name`=%s''', (data['name'], team, roster))
        create_audit({
            'old_name': roster,
            'new_name': data['name']
        }, team, ROSTER_EDITED, req, cursor)
        connection.commit()
    except db.IntegrityError as e:
        err_msg = str(e.args[1])
        if 'Duplicate entry' in err_msg:
            err_msg = "roster '%s' already existed for team '%s'" % (
                data['name'], team)
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError', err_msg)
    finally:
        cursor.close()
        connection.close()
Пример #31
0
def on_get(req, resp, team):
    """
    Get roster info for a team. Returns a JSON object with roster names
    as keys, and info as values. This info includes the roster id, any
    schedules associated with the rosters, and roster users (along
    with their status as in/out of rotation).

    **Example request**:

    .. sourcecode:: http

       GET /api/v0/teams/team-foo/rosters  HTTP/1.1
       Host: example.com

    **Example response**:

    .. sourcecode:: http

        HTTP/1.1 200 OK
        Content-Type: application/json

            {
                "roster-foo": {
                    "id": 2923,
                    "schedules": [
                        {
                            "advanced_mode": 0,
                            "auto_populate_threshold": 30,
                            "events": [
                                {
                                    "duration": 604800,
                                    "start": 266400
                                }
                            ],
                            "id": 1788,
                            "role": "primary",
                            "role_id": 1,
                            "roster": "roster-foo",
                            "roster_id": 2923,
                            "team": "team-foo",
                            "team_id": 2122,
                            "timezone": "US/Pacific"
                        }
                    ],
                    "users": [
                        {
                            "in_rotation": true,
                            "name": "jdoe"
                        },
                        {
                            "in_rotation": true,
                            "name": "asmith"
                        }
                    ]
                }
            }

    :statuscode 422: Invalid team

    """
    team = unquote(team)
    connection = db.connect()
    cursor = connection.cursor(db.DictCursor)

    cursor.execute('SELECT `id` FROM `team` WHERE `name`=%s', team)
    if cursor.rowcount != 1:
        raise HTTPError('422 Unprocessable Entity', 'IntegrityError',
                        'team "%s" not found' % team)

    team_id = cursor.fetchone()['id']
    rosters = get_roster_by_team_id(cursor, team_id, req.params)

    cursor.close()
    connection.close()
    resp.body = json_dumps(rosters)