def get_posts(username):
    """Extract all the posts of a certain username from the
    posts table database.

    Args:
        username (string): The involved user.

    Returns:
        JSON response with all data from the posts table
    """
    # Get all posts of a user.
    user_posts = posts.export('id', 'title', 'body', 'creation_date',
                              'uploads_id', username=username)

    # Transfrom to array including dictionaries.
    posts_array = []

    for item in user_posts:
        up_id = item[4]
        imageurl = ''

        if uploads.exists(id=up_id):
            filename = uploads.export_one('filename', id=up_id)
            imageurl = get_own_ip() + 'file/{}/{}'.format(up_id, filename)

        posts_array.append({
            'post_id': item[0],
            'title': item[1],
            'body': item[2],
            'image_url': imageurl,
            'profile_image' : get_profile_image(username),
            'creation_date': str(item[3]),
            'username': username
        })
    return posts_array
def forgot_username():
    """Sends email to reset username.

    Returns:
        JSON reponse based on succes/failure.
    """
    email = request.form['email']

    if not email:
        return bad_json_response("Bad request: Missing parameter 'email'.")

    # Retrieve email for given username.
    # Also retrieve firstname and lastname for personal message.
    username = users.export_one('username', email=email)

    # If no user is found for given email, don't send email.
    if not username:
        return bad_json_response(
            'No user with this e-mail exists on this server: ' + get_own_ip()
        )

    # Construct message object with receipient and sender.
    msg = EmailMessage()
    msg['Subject'] = 'FedNet - Your username is ' + username
    msg['From'] = current_app.config['EMAIL_ADDRESS']
    msg['To'] = email

    # Load the HTML template for the email, and embed the information needed.
    with open('app/templates/email_template/forgot-username.html') as f:
        html = f.read()
    html = html.replace('USERNAME_HERE', username)
    msg.add_alternative(html, subtype='html')

    # Add image to the contents of the email.
    with open('app/static/images/LogoBackOpaque.png', 'rb') as img:
        # Know the Content-Type of the image
        maintype, subtype = mimetypes.guess_type(img.name)[0].split('/')

        # Attach it to the email. The cid='0' is linked to the cid in the html,
        # which loads it.
        msg.get_payload()[0].add_related(img.read(), maintype=maintype,
                                         subtype=subtype, cid='0')
    # Connect to the mailserver from google and send the e-mail.
    with smtplib.SMTP_SSL('smtp.gmail.com', 465) as smtp:
        smtp.login(current_app.config['EMAIL_ADDRESS'],
                   current_app.config['EMAIL_PASSWORD'])
        smtp.send_message(msg)

    return good_json_response(('Email was sent to ' + email + '.'))
def get_key():
    """Function for getting the public key.

    Returns:
        JSON reponse with either public key on success or error message on
        failure.
    """
    with open('jwtRS256.key.pub') as f:
        pub_key = f.read()

    if pub_key is not None:
        return good_json_response(pub_key)
    else:
        return bad_json_response(
            'Error retrieving the public key of server: ' + get_own_ip())
Example #4
0
def post():
    """Get all the necessary details for a post.

    The post ID is checked to see if the post actually exists. The same is done
    with the upload ID.

    Returns:
        JSON response with the post details.
    """
    post_id = request.args.get('post_id')

    if post_id is None:
        return bad_json_response('post_id should be given as parameter.')

    post_db = posts.export('id', id=post_id)
    if not post_db:
        return bad_json_response('post not found')

    post_db = posts.export('body',
                           'title',
                           'username',
                           'uploads_id',
                           'creation_date',
                           'last_edit_date',
                           id=post_id)[0]

    # Get image.
    up_id = post_db[3]

    if uploads.exists(id=up_id):
        filename = uploads.export_one('filename', id=up_id)
        imageurl = get_own_ip() + 'file/{}/{}'.format(up_id, filename)

    return good_json_response({
        'post_id': post_id,
        'body': post_db[0],
        'title': post_db[1],
        'username': post_db[2],
        'profile_image': get_profile_image(post_db[2]),
        'image_url': imageurl,
        'creation_date': str(post_db[4]),
        'last_edit_date': str(post_db[5])
    })
def user():
    """Get user details depending on friendship.

    If you are friends, sensitive data will be shown aswell.

    Returns:
        JSON reponse with the basic and sensitive user details.
    """
    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'.")

    # Export used details of the user.
    user_details = users.export(
        'username', 'firstname', 'lastname', 'uploads_id',
        'location', 'study', 'bio', 'creation_date',
        'last_edit_date', 'relationship_status', 'phone_number',
        username=username
    )

    if not user_details:
        return bad_json_response('User not found')

    # Check what the status of the friendship is between the users.
    friend_status = is_friend(username)
    if username == get_jwt_identity():
        friend_status = 1

    # Get image.
    up_id = user_details[0][3]
    imageurl = '../static/images/default.jpg'
    if friend_status == 1 and uploads.exists(id=up_id):
        filename = uploads.export_one('filename', id=up_id)
        imageurl = get_own_ip() + 'file/{}/{}'.format(up_id, filename)

    # Basic information visible if not friends.
    basic_info = {
        'username': user_details[0][0],
        'friend': friend_status,
        'image_url': imageurl
    }

    if friend_status != 1:
        return good_json_response(basic_info)

    # All information visible if friends.
    sensitive_info = {
        'firstname': user_details[0][1],
        'lastname': user_details[0][2],
        'location': user_details[0][4],
        'study': user_details[0][5],
        'bio': user_details[0][6],
        'creation_date': str(user_details[0][7]),
        'last_edit_date': str(user_details[0][8]),
        'relationship_status': user_details[0][9],
        'phone_number': user_details[0][10]

    }

    return good_json_response({**basic_info, **sensitive_info})