コード例 #1
0
ファイル: post.py プロジェクト: NYUSHer/Widgets
def post_delete():
    post_by = request.headers.get('userid')
    post_id = request.form.get('pid')
    # Check if requested post exists
    sql = "SELECT * FROM posts WHERE pid='{}'".format(post_id)
    if VERBOSE:
        print("delete post pid check" + sql)
    check = query_fetch(sql, DB)
    if check is None:
        response = ErrorResponse()
        response.error['errorCode'] = '105'
        response.error['errorMsg'] = 'post does not exist'
        return jsonify(response.__dict__)
    # Check if user have authorization to delete
    sql = "SELECT authorid FROM posts WHERE pid='{}'".format(post_id)
    if VERBOSE:
        print("delete post authorization check" + sql)
    indicator = query_fetch(sql, DB)
    # Authorid and userid matchs and have authority to delete post
    if indicator['authorid'] == int(post_by):
        # Delete the post
        sql = "DELETE FROM posts WHERE authorid = '{}' AND pid = '{}'"\
            .format(post_by, post_id)
        if VERBOSE:
            print("delete post" + sql)
        query_mod(sql, DB)
        response = PostList()
        response.data['pid'] = post_id
    # No authority to delete post
    else:
        response = ErrorResponse()
        response.error['errorCode'] = '104'
        response.error['errorMsg'] = 'No authority.'
    return jsonify(response.__dict__)
コード例 #2
0
def create_a_comment():
    author_id     = int(request.headers.get('userid'))
    subscriber_id = request.form.get('suid')
    pid           = int(request.form.get('pid'))
    content       = replace(request.form.get('content'))
    if content.strip() == '':
        # No empty content allowed
        response = ErrorResponse()
        response.error['errorCode'] = '108'
        response.error['errorMsg'] = 'content cannot be empty'
        return jsonify(response.__dict__)
    sql = "INSERT INTO comments(content, pid, uid, subscriber) VALUES ('{}', '{}', '{}', '{}')" \
        .format(content, pid, author_id, subscriber_id)
    if VERBOSE:
        print("insert query:" + sql)
    query_mod(sql, DB)
    # Get the generated comment
    sql = "SELECT users.user_name,comments.* FROM comments, users " \
          "WHERE users.user_id = comments.uid AND pid = {} AND uid = {} AND subscriber = '{}' " \
          "ORDER BY timestamp DESC LIMIT 1" .format(pid, author_id, subscriber_id)
    if VERBOSE:
        print("get post_id query:" + sql)
    indicator = query_fetch(sql, DB)
    response = PostList()
    if indicator:
        print()
        response.data = indicator
    else:
        response = ErrorResponse()
        response.error['errorCode'] = '106'
        response.error['errorMsg'] = 'Somehow comment is not posted.'
    return jsonify(response.__dict__)
コード例 #3
0
def delete_a_comment(cid):
    uid = int(request.headers.get('userid'))
    sql = "SELECT uid FROM comments WHERE cid = '{}'".format(cid)
    indicator = query_fetch(sql, DB)
    # authentication
    if indicator:
        if uid != indicator['uid']:
            response = ErrorResponse()
            response.error['errorCode'] = '104'
            response.error['errorMsg'] = "No authority."
            return jsonify(response.__dict__)
    else:
        response = ErrorResponse()
        response.error['errorCode'] = '105'
        response.error['errorMsg'] = 'cid does not exist.'
        return jsonify(response.__dict__)

    # deletion
    sql = "DELETE FROM comments WHERE cid = '{}'" \
        .format(cid)
    if VERBOSE:
        print("delete post" + sql)
    query_mod(sql, DB)
    response = PostList()
    response.data['cid'] = cid
    return jsonify(response.__dict__)
コード例 #4
0
def login_by_email(user_email):
    sql = 'SELECT user_id, user_name FROM users WHERE user_email = "{}"'.format(
        user_email)
    indicator = query_fetch(sql, DB)
    # Login Success
    if indicator:
        response = SuccessResponse()
        response.data['userid'] = indicator['user_id']
        token = uuid.uuid4()  # generate token
        key = uuid.uuid4()  # generate key
        response.data['token'] = token

        # Insert generated token to database
        sql = "UPDATE users SET user_tokens = '{}', user_key = '{}' WHERE user_id = {} "\
            .format(token, key, indicator['user_id'])
        query_mod(sql, DB)

        # send email in this block
        verify_url = PROTOCOL + DOMAIN + ':' + str(PORT) + url_for(
            'auth.verify', key=key)
        params = dict(USER=indicator['user_name'], URL=verify_url)
        msg = Message('NYUSHer: Verify Your Login',
                      sender='*****@*****.**',
                      recipients=[user_email])
        msg.html = render_template('login-verification.html', **params)
        send_mail(msg)
    # Login Fail
    else:
        response = ErrorResponse()
        response.error['errorCode'] = LOGIN_ERR
        response.error['errorMsg'] = "Email doesn't not exist"
    return jsonify(response.__dict__)
コード例 #5
0
def get_info():
    user_id = request.form.get('userid')  # TODO: change api book @jerry
    if VERBOSE:
        print(user_id)

    # retrieve user's info from DB
    sql = 'SELECT user_name, user_email, user_motto, user_avatar ' \
          'FROM users WHERE user_id = "{}" '.format(user_id)
    indicator = query_fetch(sql, DB)
    if VERBOSE:
        print(indicator)

    # User exists
    if indicator:
        response = SuccessResponse()
        response.data['email'] = indicator['user_email']
        response.data['username'] = indicator['user_name']
        response.data['imageuri'] = indicator['user_avatar']
        response.data['motto'] = indicator['user_motto']
    # User does not exist
    else:
        response = ErrorResponse()
        response.error['errorCode'] = UID_ERR
        response.error['errorMsg'] = "User ID does not exist"
    return jsonify(response.__dict__)
コード例 #6
0
ファイル: post.py プロジェクト: NYUSHer/backend
def get_list():
    offset = request.form.get('offset')
    size = request.form.get('size')
    if offset is None:
        offset = 0
    else:
        offset = int(offset)
    if size is None:
        size = 20
    else:
        size = int(size)

    # offset = (int(temp)+1)*int(size)
    sql = "SELECT pid, title, content, authorid, user_avatar, user_name FROM " \
          "posts INNER JOIN users ON users.user_id = posts.authorid ORDER BY priority DESC, pid DESC LIMIT {} OFFSET {}".format(size, offset)
    if VERBOSE:
        print('get list query:' + sql)
    indicator = query_dict_fetch(sql, DB)
    if indicator:
        response = PostList()
        response.data['offset'] = offset
        response.data['size'] = size
        response.data['count'] = str(len(indicator))
        response.data['postlist'] = indicator
    else:
        response = ErrorResponse()
        response.error['errorCode'] = '105'
        response.error['errorMsg'] = 'No post found.'
    return jsonify(response.__dict__)
コード例 #7
0
def register():
    user_email = request.form.get('email')
    user_name = request.form.get('username')
    user_pass = request.form.get('passwdtoken')

    sql = 'SELECT user_id FROM users WHERE user_email = "{}"'.format(
        user_email)
    indicator = query_fetch(sql, DB)

    # Invalid (user exists)
    if indicator:
        response = ErrorResponse()
        response.error['errorCode'] = REG_ERR
        response.error['errorMsg'] = "User already exists"

    # Valid (user doesn't exist)
    else:
        response = SuccessResponse()
        user_token = uuid.uuid4()
        key = uuid.uuid4()
        sql = "INSERT INTO users(user_name, user_email, user_pass, user_tokens, user_key) VALUES ('{}', '{}', '{}', '{}', '{}')"\
            .format(user_name, user_email, user_pass, user_token, key)
        if VERBOSE:
            print("insert query:" + sql)
        query_mod(sql, DB)

        sql = "SELECT user_id FROM users WHERE user_name = '{}'".format(
            user_name)
        if VERBOSE:
            print("get userid query:" + sql)
        user_id = query_fetch(sql, DB)

        response.data['userid'] = user_id['user_id']
        response.data['email'] = user_email
        response.data['username'] = user_name
        response.data['token'] = user_token

        # send email in this block
        verify_url = PROTOCOL + DOMAIN + ':' + str(PORT) + url_for(
            'auth.verify', key=key)
        params = dict(USER=user_name, USER_EMAIL=user_email, URL=verify_url)
        print(verify_url)
        msg = Message('NYUSHer: Verify Your Email',
                      sender='*****@*****.**',
                      recipients=[user_email])
        msg.html = render_template('email-verification.html', **params)
        send_mail(msg)
    if VERBOSE:
        print(response)
    return jsonify(response.__dict__)
コード例 #8
0
def check_email():
    user_email = request.form.get('email')
    sql = 'SELECT user_id FROM users WHERE user_email = "{}"'.format(
        user_email)
    indicator = query_fetch(sql, DB)
    if indicator:
        response = SuccessResponse()
    else:
        response = ErrorResponse()
    return jsonify(response.__dict__)
コード例 #9
0
def login():
    user_email = request.form.get('email')
    user_pass = request.form.get('passwdtoken')
    if VERBOSE:
        print(user_email, user_pass)

    # user must finish all verifications to login
    sql = 'SELECT user_key FROM users WHERE user_email = "{}"'.format(
        user_email)
    key = query_fetch(sql, DB)
    if key is None:
        return jsonify(
            dict(state=False,
                 error={
                     'errorCode': LOGIN_ERR,
                     'errorMsg': 'User does not exist.'
                 },
                 timestamp=int(time())))
    elif key['user_key'] is not None:
        return jsonify(
            dict(state=False,
                 error={
                     'errorCode': VERIFY_ERR,
                     'errorMsg': 'Verification has not been finished.'
                 },
                 timestamp=int(time())))

    # user chooses to login by email
    if user_pass == "NYUSHer_by_email_login":
        return login_by_email(user_email)

    # Check of the input email and token match database
    sql = 'SELECT user_id FROM users WHERE user_email = "{}" and user_pass = "******"'.format(
        user_email, user_pass)
    indicator = query_fetch(sql, DB)
    if VERBOSE:
        print(indicator)

    # Login Success
    if indicator:
        response = SuccessResponse()
        response.data['userid'] = indicator['user_id']
        token = uuid.uuid4()  # generate token
        response.data['token'] = token

        # Insert generated token to database
        sql = "UPDATE users SET user_tokens = '{}' WHERE user_id = {} ".format(
            token, indicator['user_id'])
        query_mod(sql, DB)
    # Login Fail
    else:
        response = ErrorResponse()
        response.error['errorCode'] = LOGIN_ERR
        response.error['errorMsg'] = "Password is incorrect"
    return jsonify(response.__dict__)
コード例 #10
0
ファイル: post.py プロジェクト: NYUSHer/backend
def post_get():
    post_id = request.form.get('pid')
    sql = "SELECT title, category, tags, content FROM posts WHERE pid = '{}'".format(post_id)
    if VERBOSE:
        print("post get query:" + sql)
    indicator = query_fetch(sql, DB)
    response = PostList()
    if indicator:
        response.data['pid'] = post_id
        response.data['title'] = indicator['title']
        response.data['category'] = indicator['category']
        """
        NOTE: Tags must be deserialized first.
              Split with comma
        e.g. post_tags = 'dog, 2017, happy, weekend'
        """
        response.data['tags'] = indicator['tags']
        response.data['content'] = indicator['content']
    else:
        response = ErrorResponse()
        response.error['errorCode'] = '105'
        response.error['errorMsg'] = 'Post does not exist'
    return jsonify(response.__dict__)
コード例 #11
0
def get_comments_for_a_post():
    try:
        offset = int(request.args.get('offset'))
        size   = int(request.args.get('size'))
    except TypeError:
        offset = 0
        size   = 10
    try:
        pid    = int(request.args.get('pid'))
    except TypeError:
        response = ErrorResponse()
        response.error['errorCode'] = 'missing args.'
        response.error['errorMsg'] = '107'
        return jsonify(response.__dict__)
    sql = "SELECT users.user_name, comments.* FROM comments, users " \
          "WHERE users.user_id = comments.uid AND pid = {} ORDER BY cid DESC LIMIT {} OFFSET {}".format(pid, size, offset)
    if VERBOSE:
        print('Get comment list query:' + sql)
    indicator = query_dict_fetch(sql, DB)
    if indicator:
        response = PostList()
        response.data['offset'] = offset
        response.data['size'] = size
        response.data['count'] = str(len(indicator))
        response.data['postlist'] = indicator
    else:
        response = ErrorResponse()
        response.error['errorCode'] = 'No comments found.'
        response.error['errorMsg'] = '105'
    return jsonify(response.__dict__)
コード例 #12
0
def get_comments_for_a_user(suid=None):
    uid = int(request.headers.get("userid"))
    if uid != suid:
        response = ErrorResponse()
        response.error['errorCode'] = '104'
        response.error['errorMsg'] = "No authority."
        return jsonify(response.__dict__)
    try:
        offset = int(request.args.get('offset'))
        size   = int(request.args.get('size'))
    except TypeError:
        offset = 0
        size = 20
    sql = "SELECT users.user_name, comments.* FROM comments, users WHERE comments.uid = users.user_id AND" \
          " subscriber LIKE '%{}%' ORDER BY timestamp DESC LIMIT {} OFFSET {}"\
        .format(suid, size, offset)
    if VERBOSE:
        print('Get comment list query:' + sql)
    indicator = query_dict_fetch(sql, DB)
    if indicator:
        response = PostList()
        response.data['offset'] = offset
        response.data['size'] = size
        response.data['count'] = str(len(indicator))
        response.data['postlist'] = indicator
    else:
        response = ErrorResponse()
        response.error['errorCode'] = 'No comments found.'
        response.error['errorMsg'] = '105'
    return jsonify(response.__dict__)
コード例 #13
0
def edit_a_comment(cid=None):
    uid  = int(request.headers.get('userid'))
    content = replace(request.form.get('content')) # could be a problem
    sql = "SELECT uid FROM comments WHERE cid = '{}'" .format(cid)
    indicator = query_fetch(sql, DB)
    # authentication
    if indicator:
        if uid != indicator['uid']:
            response = ErrorResponse()
            response.error['errorCode'] = '104'
            response.error['errorMsg'] = "No authority."
            return jsonify(response.__dict__)
    else:
        response = ErrorResponse()
        response.error['errorCode'] = '105'
        response.error['errorMsg'] = 'cid does not exist.'
        return jsonify(response.__dict__)

    # modification
    if content.strip() == '':
        # No empty content
        response = ErrorResponse()
        response.error['errorCode'] = '108'
        response.error['errorMsg'] = 'content cannot be empty.'
    sql = "UPDATE comments SET content='{}', timestamp = (CURRENT_TIMESTAMP) WHERE cid='{}'" \
        .format(content, cid)
    if VERBOSE:
        print(sql)
    query_mod(sql, DB)

    # get the changed comment
    sql = "SELECT * FROM comments WHERE cid = '{}'" .format(cid)
    if VERBOSE:
        print("get post_id query:" + sql)
    indicator = query_fetch(sql, DB)
    response = PostList()
    if indicator:
        response.data = indicator
    else:
        response = ErrorResponse()
        response.error['errorCode'] = '106'
        response.error['errorMsg'] = 'Somehow comment is not posted.'
    return jsonify(response.__dict__)
コード例 #14
0
ファイル: post.py プロジェクト: NYUSHer/Widgets
def post_submit():
    post_title = replace(request.form.get('title'))
    post_category = replace(request.form.get('category'))
    post_tags = replace(request.form.get('tags'))
    post_content = replace(request.form.get('content'))
    post_by = request.headers.get('userid')
    if VERBOSE:
        print(post_title, post_category, post_tags, post_content, post_by)

    # No empty title
    if post_title == "":
        response = ErrorResponse()
        response.error['errorCode'] = '108'
        response.error['errorMsg'] = 'title cannot be empty'
        return jsonify(response.__dict__)

    # No empty content
    elif post_content == "":
        response = ErrorResponse()
        response.error['errorCode'] = '108'
        response.error['errorMsg'] = 'content cannot be empty'
        return jsonify(response.__dict__)

    # Modify Existing Post
    elif request.form.get('pid') is not None and request.form.get(
            'pid').isdigit():
        post_id = request.form.get('pid')
        # Check if user_id and post_by matches
        sql = "SELECT authorid FROM posts WHERE pid = '{}'".format(post_id)
        if VERBOSE:
            print(sql)
        indicator = query_fetch(sql, DB)
        user_id = request.headers.get('userid')
        response = PostList()
        if indicator['authorid'] == int(user_id):
            sql = "UPDATE posts SET title='{}', category='{}', tags='{}', content='{}', timestamp = (CURRENT_TIMESTAMP) WHERE pid='{}'"\
                .format(post_title, post_category, post_tags, post_content, post_id)
            if VERBOSE:
                print(sql)
            query_mod(sql, DB)
            response.data['pid'] = post_id
    # New Post
    elif request.form.get('pid') is None:
        sql = "INSERT INTO posts(title, content, tags, category, authorid) VALUES ('{}', '{}', '{}', '{}', '{}')" \
            .format(post_title, post_content, post_tags, post_category, post_by)

        if VERBOSE:
            print("insert query:" + sql)
        query_mod(sql, DB)

        # Get the generated post_id
        sql = "SELECT pid FROM posts WHERE category = '{}' AND content = '{}' AND authorid = '{}'" \
            .format(post_category, post_content, post_by)
        if VERBOSE:
            print("get post_id query:" + sql)
        indicator = query_fetch(sql, DB)
        response = PostList()
        if indicator:
            response.data['pid'] = indicator['pid']
    else:
        response = ErrorResponse()
        response.error['errorCode'] = '106'
        response.error['errorMsg'] = 'How did you wind up here??'
    return jsonify(response.__dict__)