Ejemplo n.º 1
0
    def wrapper(message_id, *args, **kwargs):
        # If cookie doesn't exist, or length is 0, redirect to login.
        if request.get_cookie("logged_in_as") is None:
            redirect('/login/')
        elif len(request.get_cookie("logged_in_as")) == 0:
            redirect('/login/')
        # Otherwise
        else:
            msg = {}

            # Attempt to load the message, otherwise save alert and redirect
            try:
                msg = load_message(message_id)
            except OSError:
                save_danger("No such message {}".format(message_id))
                redirect('/')

            # Get the username of the current logged in user.
            user = request.get_cookie("logged_in_as")

            # Redirect if the user didn't send or receive the message
            if not user == msg['to'] and not user == msg['from']:
                redirect('/')

            return func(message_id, *args, **kwargs)
Ejemplo n.º 2
0
def clear_observations():
    '''
    Attempts to remove all saved observation files

    If the files could not be removed (an exception of some sort),
    then a danger alert is saved.

    If the files were removed successfully, a success alert is saved.

    In either case, the user is redirected to /

    Requires users to be logged in

    Returns:    None.
    '''
    # Try to remove all json files from observations directory
    try:
        filelist = glob("observations/*.json")
        for f in filelist:
            os.remove(f)
    # If error, log danger error
    except:
        save_danger("Clear Observations failed")
    # Otherwise log success
    else:
        save_success("Cleared all observations.")
    # Then redirect to main page
    finally:
        redirect("/")
Ejemplo n.º 3
0
def remove_observation(observation_id):
    '''
    Attempts to remove the observation with id observation_id

    If the file could not be removed (OSError), then a danger alert is saved.

    If the file was removed successfully, a success alert is saved.

    In either case, the user is redirected to /

    Requires users to be logged in

    :param: uuid to be removed (no json extention)

    :Returns:    None.
    '''
    # Try to the specified json file from observations directory
    try:
        rmfile = "observations/" + observation_id + '.json'
        os.remove(rmfile)
    # If error, log danger error
    except:
        save_danger('No such observation {}'.format(observation_id))
    # Otherwise log success
    else:
        save_success('Removed {}.'.format(observation_id))
    # Then redirect to main page
    finally:
        redirect("/")
Ejemplo n.º 4
0
def shred_messages():
    """Handler for POST requests to ``/shred/`` path.

    * Attempts to remove all saved message files

        - If any files could not be removed (an exception of some sort),
          then a danger alert is saved.
        - If all files were removed successfully, a success alert is saved.
        - In either case, the user is redirected to ``/``

    * Requires users to be logged in

    :returns: None. This function only redirects users to other
        pages. It has no template to render.

    """
    # For every file in messages directory, remove the message
    for file in glob('messages/*.json'):
        try:
            os.remove(file)
        except:
            # If file can't be removed, save alert with message id
            save_danger("Couldn't shred {}".format(file[9:45]))

    # If there are no messages left, save success message
    if len(glob('messages/*.json')) == 0:
        save_success("Shreded all messages.")

    redirect("/")
Ejemplo n.º 5
0
def delete_message(message_id):
    """Handler for POST requests to ``/delete/<message_id>/`` path.

    * Attempts to remove file with message ID ``message_id``

        - If the file could not be removed (``OSError``), then a danger
          alert is saved.
        - If the file was removed successfully, a success alert is saved.
        - In either case, the user is redirected to ``/``.

    * Requires a user to be authorized to delete the message
    * Requires users to be logged in

    :returns: None. This function only redirects users to other
        pages. It has no template to render.

    """
    # Directory of the file to delete
    dir = os.path.join('messages/', '{}.json'.format(message_id))

    # Attempt to delete it
    try:
        os.remove(dir)
        save_success("Deleted {}.".format(message_id))

    # If it can't be deleted, save danger alert
    except OSError:
        save_danger("No such message {}".format(message_id))

    finally:
        redirect("/")
Ejemplo n.º 6
0
def leave_event(eventId):
    if request.get_cookie('current_user'):
        unregisterFromEvent(eventId, request.get_cookie('current_user'))
        # TODO: Make save_success output the event's name.
        save_success('Sucessfully unregistered from the event.')
        redirect('/events/')
    else:
        save_danger('You have to be signed in to do that!')
        redirect('/events/')
Ejemplo n.º 7
0
def create_event():
    errors = eventValidation(request.forms)
    if errors:
        for err in errors:
            save_danger(err)
        redirect('/events/createEvent/')
    else:
        eventInsertion(request.forms)
        save_success('Event created successfully!')
        redirect('/events/')
Ejemplo n.º 8
0
def validate_signup():
    signupForm = request.forms
    errors = formValidation(signupForm)
    if errors:
        for i in errors:
            save_danger(i)
        redirect('/signup/')
    else:
        formInsertion(signupForm)
        save_success('Account created successfully!')
        redirect('/login/')
Ejemplo n.º 9
0
def change_profile(username):
    if request.get_cookie('current_user'):
        errors = editUserProfile(request.forms, username)
        if errors:
            for err in errors:
                save_danger(err)
                redirect('/users/{}/'.format(username))
        else:
            save_success('Profile changed successfully!')
            redirect('/users/{}/'.format(username))
    else:
        redirect('/users/{}/'.format(username))
Ejemplo n.º 10
0
def validate_login():
    loginForm = request.forms
    errors = checkLogin(loginForm)
    if errors:
        for i in errors:
            save_danger(i)
        redirect('/login/')
    # If user signed in successfully:
    # Grab their username, and sanitize it.
    username = loginForm['username']
    # Create a session variable equal to their username:
    response.set_cookie("current_user", username, path='/')
    # Let them know they've been signed in successfully:
    save_success('Successfully logged in as {}'.format(username))
    # Redirect them back to the home page:
    redirect('/')
Ejemplo n.º 11
0
def process_observation_form():
    '''
    Validates the submitted form

    If the form is has errors, saves the errors as danger alerts
    and redirects the user back to /add/

    Saves a new observation file to disk

    Save a success alert message

    Redirects the user to /

    Requires users to be logged in

    :Returns:    None.
    '''
    # Create a blank dict to store the form in
    form = {}
    # See if forms contains suspect
    try:
        form['suspect'] = request.forms['suspect']
    except:
        pass
    # See if forms contains location
    try:
        form['location'] = request.forms['location']
    except:
        pass
    # See if forms contains time
    try:
        form['time'] = request.forms['time']
    except:
        pass
    # Find possible errors from form
    errors = validate_observation_form(form)
    # Save errors and redirect
    if errors:
        for alerts in errors:
            save_danger(alerts)
        redirect('/add/')
    # Add reporter field to form
    form['reporter'] = request.get_cookie('logged_in_as')
    # Save form, save success alert, and redirect
    save_observation(form)
    save_success("New observation added!")
    redirect("/")
Ejemplo n.º 12
0
def process_compose_message_form():
    """Handler for POST requests to ``/compose/`` path.

    * Processes the message form

        1. Validates the submitted form

            - **If the form is has any errors**, saves the errors as
              danger alerts and redirects the user back to ``/compose/``
            - Otherwise (no errors) proceed to step 2.

        2. Saves message data to a new file on disk

        3. Save a success alert message

        4. Redirects the user to ``/``

    * Requires users to be logged in

    :returns: None. This function only redirects users to other
        pages. It has no template to render.

    """
    # Validate the form, get errors if there are any.
    errors = validate_message_form(request.forms)

    # Save errors and redirect
    if errors:
        save_danger(*errors)
        redirect('/compose/')

    # Otherwise get the necessary info in the dictionary
    dict = {}
    dict['to'] = request.forms['to']
    dict['from'] = request.get_cookie("logged_in_as")
    dict['subject'] = request.forms['subject']
    dict['body'] = request.forms['body']
    dict['time'] = datetime.now().strftime("%Y-%m-%d %H:%M:%S")

    # Send the message (creates a .json file in messages/)
    send_message(dict)

    save_success("Message sent!")
    redirect("/")
Ejemplo n.º 13
0
def process_login_form():
    """Handler for POST requests to ``/login/`` path.

    * Processes the login form

        1. Validates the submitted form

            * If the form is has errors, saves the errors as
              danger alerts and redirects the user back to ``/login/``

        2. Checks that the user's username/password combo is good

            * Usernames are case insensitive

        3. Redirects the user

            - If their credentials were good, set their
              ``logged_in_as`` cookie to their username, save a
              success alert, and redirect them to ``/``
            - If their credentials were bad, save a danger alert, and
              redirect them to ``/login/``

    :returns: None. This function only redirects users to other
        pages. It has no template to render.

    """
    errors = validate_login_form(request.forms)
    if errors:
        save_danger(*errors)
        redirect('/login/')

    username = request.forms['username'].lower()
    password = request.forms['password']

    # TODO some kind of actual authentication
    if check_password(username, password):
        response.set_cookie("logged_in_as", username, path='/')
        save_success("Successfully logged in as {}.".format(username))
        redirect("/")
    else:
        save_danger("Incorrect username/password information.")
        redirect("/login/")