def get_credentials_by_user_id(user_id): user_name = minitwit.query_db( '''select username from user where user.user_id = ?''', [user_id], one=True) pw_hash = minitwit.query_db( '''select pw_hash from user where user.user_id = ?''', [user_id], one=True) app.config['BASIC_AUTH_USERNAME'] = user_name[0] app.config['BASIC_AUTH_PASSWORD'] = pw_hash[0]
def messages(): # update LATEST update_latest(request) not_from_sim_response = not_req_from_simulator(request) if not_from_sim_response: return not_from_sim_response no_msgs = request.args.get("no", type=int, default=100) if request.method == "GET": query = """SELECT message.*, user.* FROM message, user WHERE message.flagged = 0 AND message.author_id = user.user_id ORDER BY message.pub_date DESC LIMIT ?""" messages = query_db(query, [no_msgs]) filtered_msgs = [] for msg in messages: filtered_msg = {} filtered_msg["content"] = msg["text"] filtered_msg["pub_date"] = msg["pub_date"] filtered_msg["user"] = msg["username"] filtered_msgs.append(filtered_msg) return jsonify(filtered_msgs)
def remove_follow(user_id): '''Unfollow: json data: whom_id''' if not request.json: return make_error( 400, "Bad Request", "The browser (or proxy) sent a request that this server could not understand." ) if request.method != 'DELETE': return make_error(405, 'Method Not Allowed', 'The method is not allowed for the requested URL.') data = request.json get_credentials_by_user_id(user_id) if not basic_auth.check_credentials(data["username"], data["pw_hash"]): return make_error(401, 'Unauthorized', 'Correct username and password are required.') if data: '''Check who_id and whom_id existing''' cur = minitwit.query_db( 'select count(*) from follower where who_id = ? and whom_id = ?', [user_id, data["whom_id"]], one=True) if cur[0] == 0: return make_error( 404, 'Not Found', 'The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.' ) db = minitwit.get_db() db.execute( '''delete from follower where who_id = ? and whom_id = ?''', [user_id, data["whom_id"]]) db.commit() print 'You are no longer following user has ', data["whom_id"] return jsonify(data)
def add_follow(user_id): '''Insert follow: json data: whom_id''' if not request.json: return make_error( 400, "Bad Request", "The browser (or proxy) sent a request that this server could not understand." ) if request.method != 'POST': return make_error(405, 'Method Not Allowed', 'The method is not allowed for the requested URL.') data = request.json get_credentials_by_user_id(user_id) if not basic_auth.check_credentials(data["username"], data["pw_hash"]): return make_error(401, 'Unauthorized', 'Correct username and password are required.') if data: '''Check duplicate''' cur = minitwit.query_db( 'select count(*) from follower where who_id = ? and whom_id = ?', [user_id, data["whom_id"]], one=True) if cur[0] > 0: return make_error(422, "Unprocessable Entity", "Data duplicated") db = minitwit.get_db() db.execute( '''insert into follower (who_id, whom_id) values (?, ?)''', [user_id, data["whom_id"]]) db.commit() print 'You are following user has user_id ', data['whom_id'] return jsonify(data)
def add_follow_user(username1, username2): """Adds the username1 as follower of the given username2.""" data = request.get_json() get_credentials(username1) if not basic_auth.check_credentials(data["username"], data["pw_hash"]): return make_error(401, 'Unauthorized', 'Correct username and password are required.') who_id = minitwit.get_user_id(username1) whom_id = minitwit.get_user_id(username2) if whom_id is None: return make_error( 404, 'Not Found', 'The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.' ) cur = minitwit.query_db( 'select count(*) from follower where who_id = ? and whom_id = ?', [who_id, whom_id], one=True) if cur[0] > 0: return make_error(422, "Unprocessable Entity", "Data duplicated") if request.method == 'POST': db = minitwit.get_db() db.execute('insert into follower (who_id, whom_id) values (?, ?)', [who_id, whom_id]) db.commit() print 'You are now following %s' % username2 return jsonify(data) return make_error(405, 'Method Not Allowed', 'The method is not allowed for the requested URL.')
def get_user_id(username): user_id = query_db("SELECT user.user_id FROM user WHERE username = ?", [username], one=True) if user_id: return user_id["user_id"] else: return None
def Sign_up(): '''User Sign up: json data: username, email, password, confirmed_password''' if not request.json: return make_error( 400, "Bad Request", "The browser (or proxy) sent a request that this server could not understand." ) if request.method != 'POST': return make_error(405, 'Method Not Allowed', 'The method is not allowed for the requested URL.') data = request.json if data: if not data["username"] or not data["email"] or not data["password"] \ or not data["confirmed_password"] or data["password"] != data["confirmed_password"]: return make_error( 400, "Bad Request", "The browser (or proxy) sent a request that this server could not understand." ) '''check duplicate''' cur = minitwit.query_db('select count(*) from user where username = ?', [data["username"]], one=True) cur1 = minitwit.query_db('select count(*) from user where email = ?', [data["email"]], one=True) if cur[0] > 0: return make_error(422, "Unprocessable Entity", "Duplicated Username") if cur1[0] > 0: return make_error(422, "Unprocessable Entity", "Duplicated email") pw = generate_password_hash(data["password"]) db = minitwit.get_db() db.execute( '''insert into user (username, email, pw_hash) values (?, ?, ?)''', [data["username"], data["email"], pw]) db.commit() print 'You were successfully registered' return jsonify(data)
def follow(username): # update LATEST update_latest(request) not_from_sim_response = not_req_from_simulator(request) if not_from_sim_response: return not_from_sim_response user_id = get_user_id(username) if not user_id: abort(404) no_followers = request.args.get("no", type=int, default=100) if request.method == "POST" and "follow" in request.json.keys(): follows_username = request.json["follow"] follows_user_id = get_user_id(follows_username) if not follows_user_id: # TODO: This has to be another error, likely 500??? abort(404) query = """INSERT INTO follower (who_id, whom_id) VALUES (?, ?)""" g.db.execute(query, [user_id, follows_user_id]) g.db.commit() return "", 204 elif request.method == "POST" and "unfollow" in request.json.keys(): unfollows_username = request.json["unfollow"] unfollows_user_id = get_user_id(unfollows_username) if not unfollows_user_id: # TODO: This has to be another error, likely 500??? abort(404) query = "DELETE FROM follower WHERE who_id=? and WHOM_ID=?" g.db.execute(query, [user_id, unfollows_user_id]) g.db.commit() return "", 204 elif request.method == "GET": no_followers = request.args.get("no", type=int, default=100) query = """SELECT user.username FROM user INNER JOIN follower ON follower.whom_id=user.user_id WHERE follower.who_id=? LIMIT ?""" followers = query_db(query, [user_id, no_followers]) follower_names = [f["username"] for f in followers] followers_response = {"follows": follower_names} return jsonify(followers_response)
def get_messages(): '''return all messages from all users ''' if request.method != 'GET': return make_error(405, 'Method Not Allowed', 'The method is not allowed for the requested URL.') messages = minitwit.query_db( ''' select message.text, user.username from message, user where message.author_id = user.user_id order by message.pub_date desc''', ) messages = map(dict, messages) return jsonify(messages)
def get_message_user(user_id): '''return all messages form the user <user_id>''' if request.method != 'GET': return make_error(405, 'Method Not Allowed', 'The method is not allowed for the requested URL.') data = request.json messages = minitwit.query_db( ''' select message.text, user.username from message, user where message.author_id = user.user_id and user.user_id = ? ''', [user_id]) messages = map(dict, messages) return jsonify(messages)
def get_user_messages(username): """Displays a user's tweets""" profile_user = minitwit.query_db('select * from user where username = ?', [username], one=True) if profile_user is None: return make_error( 404, 'Not Found', 'The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.' ) data = request.get_json() get_credentials(data["username"]) if not basic_auth.check_credentials(data["username"], data["pw_hash"]): return make_error(401, 'Unauthorized', 'Correct username and password are required.') if request.method == 'GET': messages = minitwit.query_db( '''select message.*, user.* from message, user where user.user_id = message.author_id and user.user_id = ? order by message.pub_date desc limit ?''', [profile_user['user_id'], minitwit.PER_PAGE]) messages = map(dict, messages) return jsonify(messages) return make_error(405, 'Method Not Allowed', 'The method is not allowed for the requested URL.')
def user_info(username): """Gets user's information""" data = request.get_json() get_credentials(data["username"]) if not basic_auth.check_credentials(data["username"], data["pw_hash"]): return make_error(401, 'Unauthorized', 'Correct username and password are required.') if request.method == 'GET': user = minitwit.query_db( '''select * from user where user.username = ?''', [username]) user = map(dict, user) return jsonify(user) return make_error(405, 'Method Not Allowed', 'The method is not allowed for the requested URL.')
def user_follow(user_id): '''return all users that the user <user_id> is following''' if request.method != 'GET': return make_error(405, 'Method Not Allowed', 'The method is not allowed for the requested URL.') data = request.json get_credentials_by_user_id(user_id) if not basic_auth.check_credentials(data["username"], data["pw_hash"]): return make_error(401, 'Unauthorized', 'Correct username and password are required.') messages = minitwit.query_db( ''' select u1.username as followee, u2.username as follower from user u1, follower f, user u2 where u1.user_id = f.who_id and u2.user_id = f.whom_id and u1.user_id = ? ''', [user_id]) messages = map(dict, messages) return jsonify(messages)
def messages_per_user(username): # update LATEST update_latest(request) not_from_sim_response = not_req_from_simulator(request) if not_from_sim_response: return not_from_sim_response no_msgs = request.args.get("no", type=int, default=100) if request.method == "GET": user_id = get_user_id(username) if not user_id: abort(404) query = """SELECT message.*, user.* FROM message, user WHERE message.flagged = 0 AND user.user_id = message.author_id AND user.user_id = ? ORDER BY message.pub_date DESC LIMIT ?""" messages = query_db(query, [user_id, no_msgs]) filtered_msgs = [] for msg in messages: filtered_msg = {} filtered_msg["content"] = msg["text"] filtered_msg["pub_date"] = msg["pub_date"] filtered_msg["user"] = msg["username"] filtered_msgs.append(filtered_msg) return jsonify(filtered_msgs) # post message as <username> elif request.method == "POST": request_data = request.json query = """INSERT INTO message (author_id, text, pub_date, flagged) VALUES (?, ?, ?, 0)""" g.db.execute( query, (get_user_id(username), request_data["content"], int(time.time())), ) g.db.commit() return "", 204
def change_email(user_id): '''Change email: json data: email, confirmed_email''' if not request.json: return make_error( 400, "Bad Request", "The browser (or proxy) sent a request that this server could not understand." ) if request.method != 'PUT': return make_error(405, 'Method Not Allowed', 'The method is not allowed for the requested URL.') data = request.json get_credentials_by_user_id(user_id) if not basic_auth.check_credentials(data["username"], data["pw_hash"]): return make_error(401, 'Unauthorized', 'Correct username and password are required.') if data: '''Check user_id existing''' cur = minitwit.query_db('select count(*) from user where user_id = ?', [user_id], one=True) if cur[0] == 0: return make_error( 404, 'Not Found', 'The requested URL was not found on the server. If you entered the URL manually please check your spelling and try again.' ) '''check password and confirmed password are equal''' if data["email"] != data["confirmed_email"]: return make_error( 422, "Unprocessable Entity", "password and confirmed password not consistent") db = minitwit.get_db() email = data["email"] db.execute( '''update user set email = ? where user_id = ?''', [email, user_id]) db.commit() print 'Your email was successfully changed' return jsonify(data)
def get_username(user_id): cur = minitwit.query_db('select username from user where user_id = ?', [user_id], one=True) return cur[0] if cur else None