示例#1
0
文件: views.py 项目: Rdbaker/Rank
def add_score_and_list_controller(args):
    new_score = create_entry()
    order = Score.score.desc()
    if args['sort'] == 'ascending':
        order = Score.score
    del args['user_id']  # we don't want to filter based on this
    args['end_date'] = datetime.datetime.utcnow(
    )  # so that the end date is after the new score's date

    if args['filter_tag'] not in (None, args['tag']):
        raise InvalidUsage(
            "filter_tag must be either null or the same as the new score's tag"
        )

    if args['radius'] is None:
        raise InvalidUsage("radius is required")

    q = Score.query.order_by(order).filter(construct_and_(args))
    q_results = q.all()
    new_score_index = (i for i, row in enumerate(q_results)
                       if row.id == new_score.id).next()

    offset = max(0, new_score_index - args['radius'])
    return scores_from_query(
        result_set=q.offset(offset).limit(2 * args['radius'] + 1),
        args=args,
        endpoint='add_score_and_list',
    )
示例#2
0
文件: views.py 项目: Rdbaker/Rank
def freeze_user(user_id):
    if not current_user.is_admin:
        raise InvalidUsage('Forbidden', status_code=403)
    if user_id == current_user.id:
        raise InvalidUsage("You can't freeze yourself!")
    user = User.query.filter(User.id == user_id).first()
    user.game.frozen = not user.game.frozen
    user.game.save()
    return redirect(url_for('user.settings'))
示例#3
0
文件: views.py 项目: Rdbaker/Rank
 def decorated_function(*args, **kwargs):
     if "Authorization" in request.headers:
         api_key = request.headers["Authorization"][
             7:]  # from the string form "Bearer <api_key>"
     else:
         api_key = ""
     game = Game.query.filter(Game.api_key == api_key).first()
     if game:
         if game.frozen:
             raise InvalidUsage("This account has been frozen.", 403)
         g.game = game
         return f(*args, **kwargs)
     else:
         raise InvalidUsage("Unable to authenticate you.", 401)
示例#4
0
文件: views.py 项目: Rdbaker/Rank
def create_entry():
    try:
        data = json.loads(request.data)
    except:
        raise InvalidUsage('Malformed JSON')
    data["game_id"] = g.game.id
    results, errors = SCORESCHEMA.load(data, session=SESSION)
    if errors:
        raise InvalidUsage(errors)

    DB.session.add(results)
    DB.session.commit()

    return results
示例#5
0
def valid_user_id(user_id):
    """Returns the given user id as an integer array"""
    try:
        if user_id is not None:
            return [int(id) for id in str(user_id).split(',')]
    except TypeError:
        raise InvalidUsage("The user_id argument must be of type integer.")
示例#6
0
文件: views.py 项目: Rdbaker/Rank
def delete_user(id):
    if id == current_user.id:
        user = User.get_by_id(id)
        logout_user()
        user.delete()
        flash('Your account was successfully deleted.', 'info')
        return redirect(url_for('public.home'))
    if not current_user.is_admin:
        raise InvalidUsage('Forbidden', status_code=403)
    if id == current_user.id:
        raise InvalidUsage("You can't delete yourself!")
    user = User.query.filter(User.id == id).first()
    if user.is_admin:
        raise InvalidUsage("You can't delete an admin!")
    user.delete()
    return redirect(url_for('user.settings'))
示例#7
0
文件: views.py 项目: Rdbaker/Rank
def promote_to_admin(id):
    if not current_user.is_admin:
        raise InvalidUsage("Forbidden", 403)
    user = User.get_by_id(id)
    user.is_admin = True
    user.save()
    return redirect(url_for('user.settings'))
示例#8
0
def valid_offset(offset):
    """Returns the page offset if it's valid, else returns the default"""
    if offset is None:
        return DEFAULTS['offset']
    if isinstance(offset, unicode) and int(offset) > 0:
        return int(offset)
    else:
        raise InvalidUsage("The offset argument must be a positive integer.")
示例#9
0
def valid_start_date(date):
    """Returns the given date in datetime obj or returns the default"""
    try:
        if date is None:
            date = DEFAULTS['start_date'].replace(tzinfo=None).isoformat()
        return iso8601.parse_date(date).replace(tzinfo=None)
    except iso8601.iso8601.ParseError:
        raise InvalidUsage("The start_date argument must be a string in iso8601 date format.")
示例#10
0
def valid_radius(radius):
    """Returns the given radius as an integer"""
    try:
        if radius is not None:
            radius = int(radius)
            return min(radius, 12)
        else:
            return None
    except TypeError:
        raise InvalidUsage("The radius argument must be of type integer.")
示例#11
0
文件: views.py 项目: Rdbaker/Rank
def manage_data(user_id):
    user = current_user
    if user_id != user.id:
        if not current_user.is_admin:
            raise InvalidUsage("Forbidden", 403)
        user = User.get_by_id(user_id)
    return render_template(
        "user/managedata.html",
        scores=[
            SCORESCHEMA.dump(score).data
            for score in Score.query.filter(Score.game == user.game)
        ])
示例#12
0
def compare_dates(start, end):
    try:
        if start is None:
            start = DEFAULTS['start_date'].replace(tzinfo=None)
        else:
            start = iso8601.parse_date(start).replace(tzinfo=None)
        if end is None:
            end = DEFAULTS['end_date']().replace(tzinfo=None)
        else:
            end = iso8601.parse_date(end).replace(tzinfo=None)
        if end < start:
            raise InvalidUsage("The end_date argument must be a date after the start_date argument.")
    except iso8601.iso8601.ParseError:
        # This will be caught later
        pass
示例#13
0
 def throttle():
     """
     Throttle the request if need be
     """
     if api.blueprint.url_prefix not in request.path:
         # don't need to throttle these requests
         return None
     if "Authorization" not in request.headers:
         # let somebody else handle this situation
         return None
     api_key = request.headers["Authorization"][7:]  # from the string form "Bearer <api_key>"
     game = Game.query.filter(Game.api_key == api_key).first()
     if not game:
         # let somebody else handle this situation
         return None
     g.game = game
     if game.user.request_count_today() >= app.config['THROTTLE_LIMIT']:
         return handle_invalid_usage(InvalidUsage("Exceeded maximum API requests.", 429))
示例#14
0
 def get_args():
     """Get the URL and POST data arguments from a request."""
     both = {k: v[0] for k,v in dict(request.args).iteritems()}
     try:
         both.update(json.loads(request.data or "{}"))
     except:
         raise InvalidUsage('Malformed JSON received.')
     args = {}
     compare_dates(start=both.get('start_date'), end=both.get('end_date'))
     args['start_date'] = valid_start_date(both.get('start_date'))
     args['filter_tag'] = valid_tag(both.get('filter_tag'))
     args['page_size'] = valid_page_size(both.get('page_size'))
     args['end_date'] = valid_end_date(both.get('end_date'))
     args['user_id'] = valid_user_id(both.get('user_id'))
     args['radius'] = valid_radius(both.get('radius'))
     args['offset'] = valid_offset(both.get('offset'))
     args['sort'] = valid_sort(both.get('sort'))
     args['tag'] = valid_tag(both.get('tag'))
     return view_func(args)
示例#15
0
文件: views.py 项目: Rdbaker/Rank
def metrics():
    if not current_user.is_admin:
        raise InvalidUsage("Forbidden", 403)
    return render_template(
        "user/admin/health.html",
        num_users=User.query.filter(User.is_admin == False).count())