Beispiel #1
0
def register():
    """Register a new user.

    Validates that the username is not already taken. Hashes the
    password for security.
    """
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None

        if not username:
            error = 'Username is required.'
        elif not password:
            error = 'Password is required.'
        elif db.execute('SELECT id FROM user WHERE username = ?',
                        (username, )).fetchone() is not None:
            error = 'User {0} is already registered.'.format(username)

        if error is None:
            # the name is available, store it in the database and go to
            # the login page
            db.execute('INSERT INTO user (username, password) VALUES (?, ?)',
                       (username, generate_password_hash(password)))
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')
Beispiel #2
0
    def get(self):
        db = get_db()
        result = db.execute('SELECT filename FROM note').fetchall()

        filenames = [entry[0] for entry in result]

        return {'filenames': filenames}
Beispiel #3
0
    def post(self):
        args = parser.parse_args()
        changed_words = args['changed_words']

        db = get_db()
        db.execute('INSERT INTO activity (words, int_time)'
                   '  VALUES (?, ?)', (changed_words, int(time.time())))

        db.commit()
Beispiel #4
0
def load_logged_in_user():
    """If a user id is stored in the session, load the user object from
    the database into ``g.user``."""
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        g.user = get_db().execute('SELECT * FROM user WHERE id = ?',
                                  (user_id, )).fetchone()
Beispiel #5
0
    def get(self, filename):
        db = get_db()
        content = db.execute(
            'SELECT content'
            '  FROM note'
            '  WHERE filename = ?', (filename, )).fetchone()

        if content:
            return {'content': content[0]}
        else:
            return {'content': ''}
Beispiel #6
0
def delete(id):
    """Delete a note.

    Ensures that the note exists and that the logged in user is the
    author of the note.
    """
    get_note(id)
    db = get_db()
    db.execute('DELETE FROM note WHERE id = ?', (id, ))
    db.commit()
    return redirect(url_for('notes.index'))
Beispiel #7
0
def index():
    """Show all the notes, most recent first."""
    db = get_db()
    notes = []
    if g.user:
        notes = [
            i for i in db.execute(
                'SELECT p.id, title, body, created, author_id, username'
                ' FROM note p JOIN user u ON p.author_id = u.id'
                ' ORDER BY created DESC').fetchall()
            if i['author_id'] == g.user['id']
        ]
    return render_template('notes/index.html', notes=notes)
Beispiel #8
0
    def get(self):
        db = get_db()
        records = db.execute('SELECT words, int_time'
                             '  FROM activity'
                             '  ORDER BY'
                             '    int_time DESC').fetchall()

        if not records:
            return {'data': ''}

        # Words
        words_activity = [record[0] for record in records]
        words_activity.reverse()

        # Standardise times
        times = [record[1] for record in records]
        min_time = min(times)
        time_activity = [value - min_time for value in times]
        time_activity.reverse()

        # spl = interp1d(time_activity, words_activity, kind='cubic')
        # xnew = np.linspace(min(time_activity), max(time_activity), 200)
        # words_smooth = spl(xnew)

        fig = plt.figure(1)
        fig.patch.set_facecolor("#eeeeee")
        line, = plt.plot(time_activity, words_activity, ls='-')
        line.set_color("#00adb5")
        axes = plt.gca()
        axes.set_xlabel('Time (Sec)', color="#303841")
        axes.set_ylabel('Activity (Words)', color="#303841")
        axes.patch.set_facecolor("#eeeeee")
        axes.set_xlim([0, max(time_activity)])
        axes.set_ylim([0, max(words_activity)])

        temp_file = BytesIO()

        plt.savefig(temp_file, format='png', facecolor=fig.get_facecolor())
        b64_data = b64encode(temp_file.getvalue())\
            .decode('utf-8')\
            .replace('\n', '')

        return {'data': b64_data}
Beispiel #9
0
    def post(self, filename):
        args = parser.parse_args()
        content = args["content"]

        db = get_db()

        exists = db.execute('SELECT 1 FROM note WHERE filename = ?',
                            (filename, )).fetchone()

        if exists:
            print('updating')
            db.execute('UPDATE note SET content = ?'
                       '  WHERE filename = ?', (content, filename))
        else:
            print('inserting')
            db.execute(
                'INSERT INTO note (content, filename)'
                '  VALUES (?, ?)', (content, filename))

        db.commit()
Beispiel #10
0
def create():
    """Create a new note for the current user."""
    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute(
                'INSERT INTO note (title, body, author_id)'
                ' VALUES (?, ?, ?)', (title, body, g.user['id']))
            db.commit()
            return redirect(url_for('notes.index'))

    return render_template('notes/create.html')
Beispiel #11
0
def update(id):
    """Update a note if the current user is the author."""
    note = get_note(id)

    if request.method == 'POST':
        title = request.form['title']
        body = request.form['body']
        error = None

        if not title:
            error = 'Title is required.'

        if error is not None:
            flash(error)
        else:
            db = get_db()
            db.execute('UPDATE note SET title = ?, body = ? WHERE id = ?',
                       (title, body, id))
            db.commit()
            return redirect(url_for('notes.index'))

    return render_template('notes/update.html', note=note)
Beispiel #12
0
def login():
    """Log in a registered user by adding the user id to the session."""
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']
        db = get_db()
        error = None
        user = db.execute('SELECT * FROM user WHERE username = ?',
                          (username, )).fetchone()

        if user is None:
            error = 'Incorrect username.'
        elif not check_password_hash(user['password'], password):
            error = 'Incorrect password.'

        if error is None:
            # store the user id in a new session and return to the index
            session.clear()
            session['user_id'] = user['id']
            return redirect(url_for('index'))

        flash(error)

    return render_template('auth/login.html')
Beispiel #13
0
def get_note(id, check_author=True):
    """Get a note and its author by id.

    Checks that the id exists and optionally that the current user is
    the author.

    :param id: id of note to get
    :param check_author: require the current user to be the author
    :return: the note with author information
    :raise 404: if a note with the given id doesn't exist
    :raise 403: if the current user isn't the author
    """
    note = get_db().execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM note p JOIN user u ON p.author_id = u.id'
        ' WHERE p.id = ?', (id, )).fetchone()

    if note is None:
        abort(404, "Note id {0} doesn't exist.".format(id))

    if check_author and note['author_id'] != g.user['id']:
        abort(403)

    return note
Beispiel #14
0
 def delete(self, filename):
     db = get_db()
     db.execute('DELETE FROM note WHERE filename = ?', (filename, ))
     db.commit()