def edit(): """Edit a certain users details in the central server. The entry with the certain users username is edited in the users table in the database. Returns: Success JSON response if the operation is successful. Else a failed JSON response is returned with the correct error message. """ username = get_jwt_identity() if users.exists(username=username): if 'new_address' in request.form: new_address = request.form['new_address'] if 'new_address' != '': if servers.exists(address=new_address): new_id = servers.export_one('id', address=new_address) users.update({'server_id': new_id}, username=username) return good_json_response({'new_address': new_address}) else: return bad_json_response( 'This address does not exist in the database.') else: return bad_json_response('Address undefined.') else: return bad_json_response('Incorrect form.') else: return bad_json_response('No user found with the username ' + username + '.')
def register(): """Register a user to the central server. For this registration, the username and server address are requested in the form. A check is performed to see if the server is live. Then the user is inserted into the users table. Returns: Success JSON response if the operation is successful. If the username is valid or the server is not live, a failed JSON response is returned. """ username = request.form['username'] address = request.form['server_address'] if not servers.exists(address=address): return bad_json_response('Server is not registered.') server_id = servers.export_one('id', address=address) if ping(address): if not users.exists(username=username): users.insert(username=username, server_id=server_id) else: return bad_json_response( 'Username is already taken. Try again :).') else: return bad_json_response('This data server is not available. ' 'Please contact the server owner.') return good_json_response('success')
def user_posts(): """Retrieve all posts from a certain username. Checks are in place to check if the user is indeed a member of FedNet. This function uses the get_posts function below to actually retrieve the posts. Returns: JSON response that contains all posts of a certain user. """ username = request.args.get('username') if username is None or username == '': username = auth_username() if username is None: return bad_json_response("Bad request: Missing parameter 'username'.") # Check if user id exists. if not users.exists(username=username): return bad_json_response('User not found.') # Send no data in case the users are not friends. if username != get_jwt_identity() and is_friend(username) != 1: return good_json_response({'posts': {}}) return good_json_response({ 'posts': get_posts(username) })
def address(): """Get the address of a certain user. From the users and servers tables, necessary details are extracted from entries containing the given username. Returns: JSON response containing the address details of a certain user. If the user is not found or the server is non existant, a failed JSON response is returned. """ username = request.args.get('username') # If username is not given, use the logged in username. if username is None or username == '': username = auth_username() if username is None or username == '': return bad_json_response("Bad request: Missing parameter 'username'.") if users.exists(username=username): server_id = users.export_one('server_id', username=username) if not servers.exists(id=server_id): bad_json_response('Server is not registered.') name, address = servers.export_one('name', 'address', id=server_id) return good_json_response({ 'name': name, 'address': address, 'username': username }) else: return bad_json_response('User is not found.')
def delete(): """Delete a post. For a post to be deleted, the post ID is requested in the form. The post entry corresponding to the given post ID is then deleted from the posts table. Returns: Success JSON response if the operation succeeded. Else a failed JSON response is returned with the correct error message. """ username = get_jwt_identity() post_id = request.form['post_id'] if username is None: return bad_json_response("Bad request: Missing parameter 'username'.") if post_id is None: return bad_json_response("Bad request: Missing parameter 'post_id'.") if not users.exists(username=username): return bad_json_response('User not found') if not posts.exists(id=post_id): return bad_json_response('Post not found') # Check if the user is the post owner. post_username = posts.export_one('username', id=post_id) if post_username != username: return bad_json_response('Not your post') # Delete post. posts.delete(id=post_id) return good_json_response('success')
def timeline(): """This function handles the timeline, making sure you only see posts from the correct people. If you are friends with a certain user, that users posts will be shown in your timeline. Imported: get_friends function from api/data/friend.py Returns: JSON reponse that contains all the posts that are shown in the timeline. """ from app.api.data.friend import get_friends username = get_jwt_identity() # Check if user exists. if not users.exists(username=username): return bad_json_response('user not found') # Get the user's own posts. posts_array = get_posts(username) # Get the user's friends. friends = get_friends(username) for i in range(len(friends)): try: friend = friends[i]['username'] friend_address = get_user_ip(friend) # Get the posts of the friend. response = requests.get( friend_address + '/api/user/posts', params={ 'username': friend }, headers=request.headers ).json() if response['success']: posts = response['data']['posts'] posts_array = posts_array + posts except BaseException: continue posts_array = sorted( posts_array, key=lambda k: datetime.datetime.strptime(k['creation_date'], '%Y-%m-%d %H:%M:%S'), reverse=True ) return good_json_response({ 'posts': posts_array })
def delete(): """Delete a user from FedNet. The users details in the users table are deleted. """ username = get_jwt_identity() if users.exists(username=username): # Everything that belongs to user is deleted automatically. users.delete(username=username) return good_json_response({'user': username}) else: return bad_json_response('Username is not registered.')
def export_zip_(): """Export all the data of a certain user as a zip. Returns: If the user exists, the user details will be exported. """ username = get_jwt_identity() if users.exists(username=username): return send_file(export_zip(username), mimetype='application/zip', as_attachment=True, attachment_filename='export.zip') else: return bad_json_response('User does not exist in database.')
def search(): """Searches for existing usernames. Returns: JSON reponse based on failure/succes. """ input_data = request.form['search_input'] if users.exists(username=username): return bad_json_response('Username is already registered.') users.insert(username=username, location=location, study=study) return good_json_response('success')
def register(): """Registers a user to this data server. All the given information is stored in the users table in the database. """ # Exit early. if users.exists(username=request.form['username']): return bad_json_response('Username is already taken. Try again :)') if users.exists(email=request.form['email']): return bad_json_response( 'A user with this email is already registered on this data server.' ) username = request.form['username'] firstname = request.form['firstname'] lastname = request.form['lastname'] email = request.form['email'] password = sha256_crypt.encrypt(request.form['password']) users.insert(username=username, firstname=firstname, lastname=lastname, password=password, email=email) return good_json_response('success')
def registered(): """Check if a certain user is registered in the users table. Returns: JSON response containing username of the certain user if the user is indeed registered. If the username is not found, a failed JSON response is returned. """ username = request.args.get('username') if username is None: return bad_json_response('Username should be given as parameter.') exists = users.exists(username=username) return good_json_response({'registered': exists})
def delete(): """Delete a certain user from the central server. The entry with the certain users username is removed from the users table in the database. Returns: Success JSON response if the operation is successful. Else a failed JSON response is returned with the correct error message. """ username = get_jwt_identity() if users.exists(username=username): users.delete(username=username) return good_json_response() else: return bad_json_response('No user found with the username ' + username)
def login(): """Function that handles the login. An access token is created. A check is in place to verify the encrypted password and to check if the user is verified through e-mail. Returns: A success JSON reponse that contains the access token. """ username = request.form['username'] password = request.form['password'] if username is None: return bad_json_response("Bad request: Missing parameter 'username'.") if password is None: return bad_json_response("Bad request: Missing parameter 'password'.") if not users.exists(username=username): return bad_json_response( "User does not exist yet. Feel 'free' to join FedNet! :)" ) password_db = users.export('password', username=username)[0] # Verify the given password. if not sha256_crypt.verify(password, password_db): return bad_json_response('Password is incorrect.') # Check if the account has been verified through e-mail. email_confirmed = users.export_one('email_confirmed', username=username) if not email_confirmed: return bad_json_response( 'The email for this user is not authenticated yet. ' 'Please check your email.' ) # Login success. access_token = create_access_token(identity=username) return good_json_response({ 'token': access_token })
def create(): """Create a new post. For a post to be created, details are submitted in the form. These details are then inserted into the posts table in the database. Returns: Success JSON response if the operation succeeded. Else a failed JSON response is returned with the correct error message. """ username = get_jwt_identity() title = request.form['title'] body = request.form['body'] if username is None: return bad_json_response("Bad request: Missing parameter 'username'.") if title is None: return bad_json_response("Bad request: Missing parameter 'title'.") if body is None: return bad_json_response("Bad request: Missing parameter 'body'.") if not users.exists(username=username): return bad_json_response('User not found.') # Insert post. if 'file' in request.files: image_filename = request.files['file'].filename image = request.files['file'].read() if image is not 0: uploads_id = save_file(image, filename=image_filename) if uploads_id is not False: posts.insert(username=username, body=body, title=title, uploads_id=uploads_id) else: posts.insert(username=username, body=body, title=title) return good_json_response('success')
def registered(): """Look up if the given username is a registered username in FedNet. Returns: JSON reponse that succeeds if the username is registered and fails if the user is not registered. """ username = request.args.get('username') if username is None: return bad_json_response("Bad request: Missing parameter 'username'.") if not users.exists(username=username): return bad_json_response('Username not found (in data server)') # This request checks if the given username is registered. r = requests.get( get_central_ip() + '/api/user/registered', params={ 'username': username } ).json() return good_json_response(r)
def confirm_email(token): """Checks if the email verification is successful. If succesful email_confirmed is set to 1 and user is now able to login. Returns: JSON responde based on succes/failure. """ try: # Create the secret key based on our little secret :) secret = URLSafeTimedSerializer(current_app.config['EMAIL_SECRET']) # Confirm key is in pool and has not expired yet. email = secret.loads(token, max_age=3600, salt=current_app.config['EMAIL_REGISTER_SALT']) # If user exists update the status 'email_confirmed' to 1. # The user will now be able to login. if users.exists(email=email): users.update({'email_confirmed': 1}, email=email) # Redirect the user to the login page, trigger # 'registration complete' process. return redirect( get_central_ip() + '?message=registration_complete') else: return bad_json_response('No user with the email ' + email + ' exists.') except SignatureExpired: message = 'The token has expired, please try registering again.' return redirect(get_central_ip() + '?message=' + message) except BadTimeSignature: message = 'The token did not match. Are you trying to hack FedNet? Q_Q' return redirect(get_central_ip() + '?message=' + message)
def confirm_forgotpass(): """Handles password resetting via email. Returns: JSON reponse based on succes/failure. """ try: token = request.form['token'] password = request.form['password'] # Create the secret key based on our little secret :) secret = URLSafeTimedSerializer(current_app.config['EMAIL_SECRET']) # Confirm key is in pool and has not expired yet. # Extract email from secret. email = secret.loads(token, max_age=3600, salt=current_app.config['EMAIL_FORGOTPASS_SALT']) # Error if no user with given email is found. if not users.exists(email=email): return bad_json_response('No user with the email ' + email + ' exists.') # Encrypt password for storage in database. password = sha256_crypt.encrypt(request.form['password']) users.update({'password': password}, email=email) return good_json_response('Change password succesfull') except SignatureExpired: message = 'The token has expired, please try requesting a new password.' return redirect(get_central_ip() + '?message=' + message) except BadTimeSignature: message = ( 'The token did not match. Are you trying to hack some user? Q_Q' ) return redirect(get_central_ip() + '?message=' + message)