Ejemplo n.º 1
0
def flask_exception_handler(ex):
    """
    Handle exceptions that reach the top level of our Flask application and
    return an appropriate error response.

    :param ex: The exception caught at the top level.
    :type ex: Exception
    :rtype: flask.Response

    """
    logger.critical("Exception: {}".format(ex))

    error_type = 'UnknownError'
    error_message = 'An unknown error occurred'
    status_code = 400
    if isinstance(ex, BaseApiException) or isinstance(ex, BaseInternalException):
        error_type = ex.__class__.__name__.replace('Exception', '')
        try:
            status_code = ex.status_code
        except:
            status_code = 400
        error_message = str(ex)
    else:
        logger.critical(ex)

    return response.error(
        errors={'type': error_type, 'message': error_message},
        status_code=status_code
    )
Ejemplo n.º 2
0
def import_lastfm_artists():
    """
    Import artists from Last.FM
    Arguments:
    - username: last.FM username to import artists from
    - period: ['7day', '1month', '3month', '6month', '12month', 'overall']
    - (optional) limit: maximum 500, default 500
    """
    user = g.user
    import_processor = ImportProcessor()
    username = request.json.get("username")
    period = request.json.get("period")
    limit = request.json.get("limit")
    if username is None or period not in [
        "7day",
        "1month",
        "3month",
        "6month",
        "12month",
        "overall",
    ]:
        return response.error("Username empty or period is incorrect.")

    if limit is None or limit > 500:
        limit = 500

    result = import_processor.import_from_lastfm(user.id, username, limit, period)

    return response.success({"artists_imported": result})
Ejemplo n.º 3
0
def route_weibo_index(request):
    headers = {
        'Content-Type': 'text/html',
    }
    # username = current_user(request)
    # if username == '游客':
    #     # 没登录 不让看 重定向到 /
    #     return redirect('/login')
    # else:
    header = response_with_headers(headers)
    user_id = request.query.get('user_id', -1)
    user_id = int(user_id)
    user = User.find(user_id)
    if user is None:
        return error(request)
    # 找到 user 发布的所有 weibo
    weibos = Weibo.find_all(user_id=user_id)
    log('weibos', weibos)

    def weibo_tag(weibo):
        return '<p>{} from {}@{} <a href="/weibo/delete?id={}">删除</a></p>'.format(
            weibo.content,
            user.username,
            weibo.created_time,
            weibo.id,
        )

    weibos = '\n'.join([weibo_tag(w) for w in weibos])
    body = template('weibo_index.html', weibos=weibos)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')
Ejemplo n.º 4
0
    def write_error(self, status_code, exc_info):
        error_class = exc_info[0]
        error_object = exc_info[1]

        if issubclass(error_class, ApiException):
            self.write_json(error_with(error_object.to_response()))
        else:
            self.write_json(error())
Ejemplo n.º 5
0
def post_delete_category(id):
    # This is meant to be reached from AJAX request.
    # We return a JSON response that will be used by
    # The JS code making the request.
    if not auth.is_user_admin():
        return response.error('Unauthorized')
    db_utils.delete_category(id)
    return response.success()
Ejemplo n.º 6
0
def route_weibo_index(request):
    headers = {
        'Content-Type': 'text/html',
    }
    header = response_with_header(headers)
    user_id = request.query.get('user_id', -1)
    user_id = int(user_id)
    user = User.find(user_id)
    if user is None:
        return error(request)
    # 找到 user 发布的所有 weibo
    weibos = Weibo.find_all(user_id=user.id)

    # 任一 user 访问任一 index
    current_username = current_user(request)
    u = User.find_by(username=current_username)
    if u is None:
        return redirect('/login')

    def weibo_tag(weibo):
        comment_list = Comment.find_all(weibo_id=weibo.id)
        comments = '<br>'.join([c.content for c in comment_list])
        # format 函数的字典用法
        # 注意 u.id 是 current_user
        # user.username 是博主
        w = {
            'id': weibo.id,
            'user_id': u.id,
            'content': weibo.content,
            'username': user.username,
            'time': weibo.created_time,
            'comments': comments,
        }
        # 手动处理 weibos 这个 list
        # 把每个 weibo 以 <p> 的形式展现在页面
        return """
            <p>{content} from {username}@{time}
                <a href="/weibo/delete?id={id}">删除</a>
                <a href="/weibo/edit?id={id}">修改</a></p>
                <button class="weibo-show-comment" data-id="{id}">评论</button>
                <div>
                    {comments}
                </div>
                <div id="id-div-comment-{id}" class="weibo-comment-form weibo-hide">
                    <form action="/weibo/comment/add" method="post">
                        <input name="user_id" value="{user_id}" type="hidden">
                        <input name="weibo_id" value="{id}" type="hidden">
                        <textarea name="content"></textarea>
                        <button type="submit">添加评论</button>
                    </form>
                </div>
            </p>
            """.format(**w)
    # 用 join() 返回 str
    weibos = '\n'.join([weibo_tag(w) for w in weibos])
    body = template('weibo_index.html', weibos=weibos)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')
Ejemplo n.º 7
0
def import_artists_endpoint():
    """
    Import artists
    Arguments:
    - artists: [string]
    - import_method: ['apple', 'spotify']
    """
    import_processor = ImportProcessor()
    artists = request.json.get("artists")
    import_method = request.json.get("import_method")
    if not artists or len(artists) == 0:
        return response.error("Missing artists dictionary.")
    if not import_method:
        return response.error("Missing import_method")

    saved_imports = import_processor.save_imports(g.user.id, artists, import_method)

    return response.success({"artists_imported": saved_imports})
Ejemplo n.º 8
0
def import_artists_endpoint():
    """
    Import artists
    Arguments:
    - artists: [string]
    - import_method: ['apple', 'spotify']
    """
    user = g.user
    artists = request.json.get('artists')
    import_method = request.json.get('import_method')
    if not artists or len(artists) == 0:
        return response.error("Missing artists dictionary.")
    if not import_method:
        return response.error("Missing import_method")

    result = import_processing.import_artists(user, artists, import_method)

    return response.success({'artists_imported': result})
Ejemplo n.º 9
0
def do_sign_in():
    # This is meant to be reached from AJAX request.
    # We return a JSON response that will be used by
    # The JS code making the request.
    if (request.form['signin_request_token'] !=
            login_session['signin_request_token']):
        return response.error('Invalid token.')

    g_id_token = request.form['id_token']
    try:
        idinfo = id_token.verify_oauth2_token(g_id_token, requests.Request(),
                                              CLIENT_ID)
        if (idinfo['iss']
                not in ['accounts.google.com', 'https://accounts.google.com']):
            raise ValueError('Wrong issuer.')

        if idinfo['aud'] != CLIENT_ID:
            raise ValueError('Invalid client id.')

    except ValueError:
        return response.error('Could not sign in')

    user_id = idinfo['sub']

    stored_id_token = login_session.get('id_token')
    stored_user_id = login_session.get('user_id')

    user = db_utils.get_user(user_id)
    if user is None:
        # Add user to database if id does not exist.
        db_utils.add_user(user_id, idinfo['email'], idinfo['name'])

    if stored_id_token is not None and stored_user_id == user_id:
        return response.success()

    # Store the access token in the session for later use.
    login_session['id_token'] = g_id_token
    login_session['user_id'] = user_id
    login_session['name'] = idinfo['name']
    login_session['email'] = idinfo['email']
    login_session['picture'] = idinfo['picture']
    return response.success()
Ejemplo n.º 10
0
def new_user():
    email = request.json.get("email")
    password = request.json.get("password")
    icloud = request.json.get("icloud")
    if (email is None or password is None) and icloud is None:
        return response.error("Proper account credentials were not provided.")

    if icloud and repo.get_user_by_icloud(icloud):
        return response.error("Registration failed.")

    if email and repo.get_user_by_email(email):
        return response.error("Registration failed.")

    user = repo.insert_user(email, icloud, password)
    if user:
        aeon_app.logger.info("New user created: {}".format(user.id))
        return response.success("New user created: {}".format(user.id))
    else:
        aeon_app.logger.error("New user failed to save.")
        return response.error("An unknown error occurred when creating this account.")
Ejemplo n.º 11
0
def route_weibo_index(request):
    headers = {
        'Content-Type': 'text/html',
    }
    header = response_with_headers(headers)
    user_id = request.query.get('user_id', -1)
    user_id = int(user_id)
    user = User.find(user_id)
    if user is None:
        return error(request)
    # 找到 user 发布的所有 weibo
    weibos = Weibo.find_all(user_id=user_id)
    log('weibos', weibos)
    current_username = current_user(request)
    u = User.find_by(username=current_username)
    if u is None:
        return redirect('/login')

    def weibo_tag(weibo):
        comment_list = Comment.find_all(weibo_id=weibo.id)
        comments = '<br>'.join([c.content for c in comment_list])
        w = {
            "id": weibo.id,
            "user_id": u.id,
            "content": weibo.content,
            "username": user.username,
            "time": weibo.created_time,
            "comments": comments,
        }
        log('comments debug', comment_list)
        return """
        <p>{content} from {username}@{time}
            <a href="/weibo/delete?id={id}">删除</a>
            <a href="/weibo/edit?id={id}">修改</a>
            <button class="gua-show-comment" data-id="{id}">评论</button>
            <div>
                {comments}
            </div>
            <div id="id-div-comment-{id}" class="gua-comment-form gua-hide">
            <form action="/weibo/comment/add" method="post">
                <input name="user_id" value="{user_id}" type="hidden">
                <input name="weibo_id" value="{id}" type="hidden">
                <textarea name="content"></textarea>
                <button type="submit">添加评论</button>
            </form>
            </div>
        </p>
        """.format(**w)

    weibos = '\n'.join([weibo_tag(w) for w in weibos])
    body = template('weibo_index.html', weibos=weibos)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')
Ejemplo n.º 12
0
def route_weibo_update(request):
    username = current_user(request)
    user = User.find_by(username=username)
    form = request.form()
    content = form.get('content', '')
    weibo_id = int(form.get('id', -1))
    w = Weibo.find(weibo_id)
    if user.id != w.user_id:
        return error(request)
    w.content = content
    w.save()
    return redirect('/weibo?user_id={}'.format(user.id))
Ejemplo n.º 13
0
def route_weibo_delete(request):
    username = current_user(request)
    user = User.find_by(username=username)
    # 删除微博
    weibo_id = request.query.get('id', None)
    weibo_id = int(weibo_id)
    w = Weibo.find(weibo_id)
    if w.user_id == user.id:
        w.delete()
        return redirect('/weibo?user_id={}'.format(user.id))
    else:
        return error(request)
Ejemplo n.º 14
0
def route_weibo_update(request):
    username = current_user(request)
    user = User.find_by(username=username)
    form = request.form()
    content = form.get('content', '')
    weibo_id = int(form.get('id', -1))
    w = Weibo.find(weibo_id)
    if user.id != w.user_id:
        return error(request)
    w.content = content
    w.save()
    # 重定向到用户的主页
    return redirect('/weibo?user_id={}'.format(user.id))
Ejemplo n.º 15
0
def route_weibo_edit(request):
    headers = {
        'Content-Type': 'text/html',
    }
    header = response_with_headers(headers)
    weibo_id = request.query.get('id', -1)
    weibo_id = int(weibo_id)
    w = Weibo.find(weibo_id)
    if w is None:
        return error(request)
    # 生成一个 edit 页面
    body = template('weibo_edit.html', weibo_id=w.id, weibo_content=w.content)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')
Ejemplo n.º 16
0
def wx_access(func):
    """
    获取微信信息
    """
    def _(self, *args, **kwargs):
        try:
            redirect_url = request.values.get("redirect_url", "http%3A%2F%2Fdata.haojin.in")
            unionid = session["unionid"]
        except Exception, e:
            return render_template("qrlogin.html", redirect=redirect_url)
        db = app.mongodb.bi
        if db.wisemeuser.find({"unionid": unionid, "main": 1}).count():
            return func(self, *args, **kwargs)
        else:
            return error(QFRET.SESSIONERR, respmsg="用户未经授权,请在蜂巢中授权", escape=False)
Ejemplo n.º 17
0
def get_item_json():
    id = request.args.get('id')
    if not id:
        return response.error('Item id not specified.')

    item = db_utils.get_item(id)
    item_dict = {
        'id': item.id,
        'name': item.name,
        'created_at': item.created_at,
        'updated_at': item.updated_at,
        'category_id': item.category_id,
        'category_name': item.category.name,
        'user_id': item.user_id,
        'short_desc': item.short_desc,
        'desc': item.desc
    }
    return jsonify(item_dict), 200
Ejemplo n.º 18
0
def route_weibo_edit(request):
    headers = {
        'Content-Type': 'text/html',
    }
    header = response_with_header(headers)
    # 这个 query.get 是在 weibo_index路由 里面放上去的
    # 用来指定要修改那一条微博
    weibo_id = request.query.get('id', -1)
    weibo_id = int(weibo_id)
    w = Weibo.find(weibo_id)
    if w is None:
        return error(request)
    # 生成一个 edit 页面
    body = template('weibo_edit.html',
                    weibo_id=w.id,
                    weibo_content=w.content)
    r = header + '\r\n' + body
    return r.encode(encoding='utf-8')
Ejemplo n.º 19
0
def get_edit_category_page(id=0):
    if request.method == 'GET':
        if not auth.is_user_admin():
            # Only admins can add and edit catories
            return render_template('unauthorized.html')
        if id and id != 0:
            # id is specified, render edit category page
            category = db_utils.get_category(id)
            return render_template('edit-category.html',
                                   category=category,
                                   CLIENT_ID=CLIENT_ID,
                                   signed_in=auth.is_signed_in(),
                                   picture=login_session.get('picture'))
        else:
            return render_template('edit-category.html',
                                   CLIENT_ID=CLIENT_ID,
                                   signed_in=auth.is_signed_in(),
                                   picture=login_session.get('picture'))
    elif request.method == 'POST':
        # This is meant to be reached from AJAX request.
        # We return a JSON response that will be used by
        # The JS code making the request.
        if not auth.is_user_admin():
            return response.error('Unauthorized')
        if request.form['name'] and request.form['desc']:
            if id and id != 0:
                # id is specified, update existing category
                category = db_utils.update_category(id, request.form['name'],
                                                    request.form['desc'])
                categoryData = {
                    'id': category.id,
                    'name': category.name,
                    'desc': category.desc
                }
                return response.success(url_for('get_index'), categoryData)
            else:
                category = db_utils.add_category(request.form['name'],
                                                 request.form['desc'])
                categoryData = {
                    'id': category.id,
                    'name': category.name,
                    'desc': category.desc
                }
                return response.success(url_for('get_index'), categoryData)
Ejemplo n.º 20
0
def import_lastfm_artists():
    """
    Import artists from Last.FM
    Arguments:
    - username: last.FM username to import artists from
    - period: ['7day', '1month', '3month', '6month', '12month', 'overall']
    - (optional) limit: maximum 500, default 500
    """
    user = g.user
    username = request.json.get('username')
    period = request.json.get('period')
    limit = request.json.get('limit')
    if username is None or period not in [
            '7day', '1month', '3month', '6month', '12month', 'overall'
    ]:
        return response.error("Username empty or period is incorrect.")

    if limit is None or limit > 500:
        limit = 500

    result = import_processing.import_from_lastfm(user, username, limit,
                                                  period)

    return response.success({'artists_imported': result})
Ejemplo n.º 21
0
def get_edit_item_page(id=0):

    if request.method == 'GET':
        if not auth.is_signed_in():
            # Redirect to login page.
            # The url to which we are redirected will contain a paramenter
            # which will be the url to redirect back to
            # after logging in
            redirect_parameter = None
            if id and id != 0:
                redirect_parameter = 'redirect={}'.format(
                    url_for('edit_item', id=id))
            else:
                redirect_parameter = 'redirect={}'.format(url_for('new_item'))
                url = '{path}?{parameter}'.format(
                    path=url_for('get_login_page'),
                    parameter=redirect_parameter)
                return redirect(url, 302)
        categories = db_utils.get_categories()
        item = None
        if id and id != 0:
            item = db_utils.get_item(id)
            if item is None:
                return render_template('404.html')
            else:
                if (not auth.is_user_admin()
                        and item.user_id != auth.get_user_id()):
                    # Cannot edit item that does not belong to user
                    # But admins are allowed
                    return render_template('unauthorized.html')
        return render_template('edit-item.html',
                               item=item,
                               categories=categories,
                               CLIENT_ID=CLIENT_ID,
                               signed_in=auth.is_signed_in(),
                               user_name=auth.get_user_name(),
                               picture=login_session.get('picture'))
    elif request.method == 'POST':
        # This is meant to be reached from AJAX request.
        # We return a JSON response that will be used by
        # The JS code making the request.
        if not auth.is_signed_in():
            return response.error('Unauthorized')

        if id and id != 0:
            # Update item
            item = db_utils.get_item(id)
            if (not auth.is_user_admin()
                    and item.user_id != auth.get_user_id()):
                # Only item owners and admins allowed to update item
                return response.error('Unauthorized')

            if (request.form['name'] and request.form['desc']
                    and request.form['cat-id']):
                item = db_utils.update_item(request.form['item-id'],
                                            request.form['name'],
                                            request.form['desc'],
                                            request.form['cat-id'])
                itemData = {
                    'id': item.id,
                    'name': item.name,
                    'desc': item.desc,
                    'short_desc': item.short_desc,
                    'category_id': item.category_id
                }
                return response.success(
                    url_for('get_item_page', id=itemData['id']), itemData)
            else:
                return response.error('Failed to save')
        else:
            # Create new item
            if (request.form['name'] and request.form['desc']
                    and request.form['cat-id']):
                item = db_utils.add_item(request.form['name'],
                                         request.form['desc'],
                                         request.form['cat-id'],
                                         auth.get_user_id())
                itemData = {
                    'id': item.id,
                    'name': item.name,
                    'desc': item.desc,
                    'short_desc': item.short_desc,
                    'category_id': item.category_id
                }
                return response.success(
                    url_for('get_item_page', id=itemData['id']), itemData)
            else:
                return response.error('Failed to save')
Ejemplo n.º 22
0
def not_found(error):
    """
    Return the HTTP 404 Not Found error.
    """
    return response.error(errors={'type': 'NotFound'}, status_code=404)