Ejemplo n.º 1
0
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.')
Ejemplo n.º 2
0
def send_verification_mail():
    """Handles the sending of verification email.

    Returns:
        JSON response based on succes/failure.
    """
    # Check if parameter email is set.
    send_to = request.form['email']
    if not send_to:
        return bad_json_response("Bad request: Missing parameter 'email'.")

    # Retrieve user from server for personal message in email.
    user = users.export_one('firstname', 'lastname',
                            email=request.form['email'])

    # If no user is found give an error.
    if not user:
        return bad_json_response('Error retrieving the user.')

    # Construct message object with receipient and sender
    msg = EmailMessage()
    msg['Subject'] = 'FedNet - Please verify your email!'
    msg['From'] = current_app.config['EMAIL_ADDRESS']
    msg['To'] = send_to

    # Create the secret key based on our little secret :)
    secret = URLSafeTimedSerializer(current_app.config['EMAIL_SECRET'])

    # Create token based on a user their email and salt to prevent same token.
    token = secret.dumps(send_to,
                         salt=current_app.config['EMAIL_REGISTER_SALT'])

    # Create link with token and add it to the body of the mail.
    link = url_for('data_mail.confirm_email', token=token, _external=True)

    # Load the HTML template for the email, and embed the information needed.
    with open('app/templates/email_template/verify-mail.html') as f:
        html = f.read()
    html = html.replace('VERIFY_LINK_HERE', link)
    html = html.replace('USERNAME_HERE', user[0] + ' ' + user[1])
    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('success')
Ejemplo n.º 3
0
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 + '.'))
Ejemplo n.º 4
0
def get_pub_key(username):
    """Helper function to get the public key of a user.
    
    Returns:
        The public key of a user if available, else a bad JSON response.
    """
    server_id = users.export_one('server_id', username=username)
    if server_id is None:
        return bad_json_response('No server_id')

    pub = servers.export_one('pub_key', id=server_id)
    if pub is None:
        return bad_json_response('No pub')

    return pub
Ejemplo n.º 5
0
def get_profile_image(username):
    """Get the profile picture url.

    Args:
        username (string): The involved user.

    Returns:
        The image url.
    """
    up_id = users.export_one('uploads_id', username=username)

    # Get image url.
    imageurl = '../static/images/default.jpg'
    if uploads.exists(id=up_id):
        filename = uploads.export_one('filename', id=up_id)
        imageurl = get_user_ip(username) + '/file/{}/{}'.format(up_id, filename)

    return imageurl
Ejemplo n.º 6
0
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
    })
Ejemplo n.º 7
0
def forgotpass():
    """Handles forgotten password, sends email to recover.

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

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

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

    # If no user is found give an error.
    if not firstname or not lastname or not username:
        return bad_json_response('Error retrieving the user.')

    # stuur mail met new ww link
    # Construct message object with receipient and sender
    msg = EmailMessage()
    msg['Subject'] = 'FedNet - Change your password.'
    msg['From'] = current_app.config['EMAIL_ADDRESS']
    msg['To'] = send_to

    # Create the secret key based on our little secret :)
    secret = URLSafeTimedSerializer(current_app.config['EMAIL_SECRET'])

    # Create token based on a user their email and salt to prevent same token.
    token = secret.dumps(send_to,
                         salt=current_app.config['EMAIL_FORGOTPASS_SALT'])

    # Create link with token and username so central knows how to handle it.
    parameters = '?username='******'&token=' + token
    link = get_central_ip() + '/forgotPassword' + parameters

    # Load the HTML template for the email, and embed the information needed.
    with open('app/templates/email_template/forgot-password.html') as f:
        html = f.read()
    html = html.replace('LINK_HERE', link)
    html = html.replace('USERNAME_HERE', username)
    html = html.replace('NAME_HERE', firstname + ' ' + lastname)
    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('success')