Exemple #1
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``.
    This will be executed everytime a route (app-instance) is called upon!
    """
    user_id = session.get('user_id')
    if user_id is None:
        g.user = None
    else:
        # logged-in user's profile:
        g.user = get_db().execute('SELECT * FROM user WHERE id = ?',
                                  (user_id, )).fetchone()

        # logged-in user's samples' details:
        g.samples = get_db().execute(
            'SELECT s.id, author_id, samplename, fabricated, location, previously, description'
            ' FROM sample s JOIN user u ON s.author_id = u.id'  # join tables to link (id in user) and (author_id in post) to get username
            ' WHERE u.id = ?'
            ' ORDER BY registered DESC',
            (user_id, )).fetchall()
        g.samples = [dict(s) for s in g.samples]

        # logged-in user's co-authored samples' details:
        g.cosamples = get_db().execute(
            'SELECT s.id, author_id, samplename, fabricated, location, previously, description'
            ' FROM sample s JOIN user u ON s.author_id = u.id'  # join tables to link (id in user) and (author_id in post) to get username
            ' WHERE s.co_authors LIKE ?'
            ' ORDER BY registered DESC',
            ('%%%s%%' % g.user['username'], )).fetchall()
        g.cosamples = [dict(x) for x in g.cosamples]

        # ALL approved users' clearances:
        g.userlist = get_db().execute(
            'SELECT u.id, username, measurement, instrument, analysis'
            ' FROM user u WHERE u.status = ?'
            ' ORDER BY id DESC', ('approved', )).fetchall()
        g.userlist = [dict(x) for x in g.userlist]
        # print("USER CREDENTIALS: %s" %g.userlist)

        # Certain clearances required for queue-list access:
        if g.user['instrument'] and g.user['measurement']:
            # Queue list:
            g.qumlist = get_db().execute(
                'SELECT u.username FROM qum q JOIN user u ON q.people_id = u.id ORDER BY q.id ASC'
            ).fetchall()
            g.qumlist = [dict(x) for x in g.qumlist]
            g.qumlist = [x['username'] for x in g.qumlist]
            # Only first in line is allowed to run the measurement:
            try:
                session['run_clearance'] = bool(
                    g.qumlist[0] == g.user['username'])
            except (IndexError):
                session['run_clearance'] = False
Exemple #2
0
def usersamples_access():
    '''Create people session (cookie) here
    '''
    sname = request.args.get('sname')
    db = get_db()
    try:
        sample_cv = db.execute(
            'SELECT s.id, author_id, samplename, fabricated, location, previously, description, registered, co_authors, history'
            ' FROM sample s JOIN user u ON s.author_id = u.id'
            ' WHERE s.samplename = ?', (sname, )).fetchone()
        sample_cv = dict(sample_cv)  # convert sqlite3.row into dictionary

        sample_owner = db.execute(
            'SELECT u.id, username'
            ' FROM sample s JOIN user u ON s.author_id = u.id'
            ' WHERE s.samplename = ?', (sname, )).fetchone()
        sample_owner = dict(
            sample_owner)  # convert sqlite3.row into dictionary

        session['people'] = sample_owner['username']
        saved = bool(sname in lisample(session['people']))  # saved?

        message = "Accessing Sample %s owned by %s" % (sname,
                                                       session['people'])
    except:
        session['people'] = []
        sample_cv = []
        message = "Consult ABC"
    # print('sample cv: %s' %sample_cv)
    return jsonify(sample_cv=sample_cv, message=message, saved=saved)
Exemple #3
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.'
        elif user['status'].upper() != 'APPROVED':
            error = 'Awaiting Approval...'

        if error is None:
            # store the user id in a new session and return to the index
            session.clear()
            session['user_id'] = user['id']
            session['user_name'] = user['username']
            print("Logged-in Successfully!")
            return redirect(url_for('index'))

        print(error)
        flash(error)

    return render_template('auth/login.html')
Exemple #4
0
def usersamples_update():
    sname = request.args.get('sname')
    loc = request.args.get('loc')
    dob = request.args.get('dob')
    description = request.args.get('description')
    coauthors = request.args.get('coauthors')
    prev = request.args.get('prev')
    history = request.args.get('history')
    ownerpassword = request.args.get('ownerpassword')
    db = get_db()
    try:
        people = db.execute('SELECT password FROM user WHERE username = ?',
                            (session['people'], )).fetchone()
        if check_password_hash(people['password'], ownerpassword):
            db.execute(
                'UPDATE sample SET location = ?, fabricated = ?, description = ?, co_authors = ?, previously = ?, history = ? WHERE samplename = ?',
                (
                    loc,
                    dob,
                    description,
                    coauthors,
                    prev,
                    history,
                    sname,
                ))
            db.commit()
            message = "Sample %s has been successfully updated!" % (sname)
        else:
            message = 'PASSWORD NOT VALID'
    except:
        message = "Check sample parameters"
    print(message)
    return jsonify(message=message)
Exemple #5
0
def index():
    """Show all the posts, most recent first."""
    db = get_db()
    posts = db.execute('SELECT p.id, title, body, created, author_id, username'
                       ' FROM post p JOIN user u ON p.author_id = u.id'
                       ' ORDER BY created DESC').fetchall()
    return render_template('blog/index.html', posts=posts)
Exemple #6
0
def usersamples_update():
    sname = request.args.get('sname')
    loc = request.args.get('loc')
    dob = request.args.get('dob')
    description = request.args.get('description')
    coauthors = request.args.get('coauthors')
    prev = request.args.get('prev')
    history = request.args.get('history')
    db = get_db()
    try:
        db.execute(
            'UPDATE sample SET location = ?, fabricated = ?, description = ?, co_authors = ?, previously = ?, history = ? WHERE samplename = ?',
            (
                loc,
                dob,
                description,
                coauthors,
                prev,
                history,
                sname,
            ))
        db.commit()
        message = "Sample %s has been successfully updated!" % (sname)
    except:
        message = "Check sample parameters"
    return jsonify(message=message)
Exemple #7
0
def get_post(id, check_author=True):
    """Get a post and its author by id.

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

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

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

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

    return post
Exemple #8
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']
        userstatus = 'pending'
        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, status) VALUES (?, ?, ?)',
                (username, generate_password_hash(password), userstatus))
            db.commit()
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html')
Exemple #9
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()
Exemple #10
0
def all_measurequm_out():
    try:
        db = get_db()
        db.execute('DELETE FROM qum WHERE people_id = ?', (g.user['id'], ))
        db.commit()
        message = "Queued-out successfully"
    except:
        message = "You may have queued-out already"
    return jsonify(message=message)
Exemple #11
0
def all_measurequm_in():
    try:
        db = get_db()
        db.execute('INSERT INTO qum (people_id) VALUES (?)', (g.user['id'], ))
        db.commit()
        message = "Queued-in successfully"
    except:
        message = "You may have queued-in already"
    return jsonify(message=message)
Exemple #12
0
def delete(id):
    """Delete a post.

    Ensures that the post exists and that the logged in user is the
    author of the post.
    """
    get_post(id)
    db = get_db()
    db.execute('DELETE FROM post WHERE id = ?', (id,))
    db.commit()
    return redirect(url_for('blog.index'))
Exemple #13
0
def char_cwsweep_resetdata():
    ownerpassword = request.args.get('ownerpassword')
    truncateafter = int(request.args.get('truncateafter'))

    db = get_db()
    people = db.execute('SELECT password FROM user WHERE username = ?',
                        (session['people'], )).fetchone()

    if check_password_hash(people['password'], ownerpassword):
        message = M_cwsweep[session['user_name']].resetdata(truncateafter)
    else:
        message = 'PASSWORD NOT VALID'

    return jsonify(message=message)
Exemple #14
0
def posts():
    """Show all the posts, most recent first."""
    db = get_db()
    posts = db.execute(
        'SELECT p.id, title, body, created, author_id, username'
        ' FROM post p JOIN user u ON p.author_id = u.id' # join tables to link (id in user) and (author_id in post) to get username
        ' ORDER BY modified DESC' # ordered by modified
    ).fetchall()
    # JSON-Serialization:
    posts = [dict(p) for p in posts] # if (g.user['id'] == p['author_id'])] # convert sqlite3.row into list of dictionaries

    if g.user is None:
        guserid = g.user
    else:
        guserid = g.user['id']

    return jsonify(posts=posts,guserid=guserid)
Exemple #15
0
def create():
    """Create a new post 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 post (title, body, author_id)'
                ' VALUES (?, ?, ?)', (title, body, g.user['id']))
            db.commit()
            return redirect(url_for('blog.index'))

    return render_template('blog/create.html')
Exemple #16
0
def update(id):
    """Update a post if the current user is the author."""
    post = get_post(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 post SET title = ?, body = ? WHERE id = ?',
                       (title, body, id))
            db.commit()
            return redirect(url_for('blog.index'))

    return render_template('blog/update.html', post=post)
Exemple #17
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.'
        elif user['status'].upper() != 'APPROVED':
            error = 'Awaiting Approval...'

        if error is None:
            # store the user's credentials in a new SESSION (Cookies) and return to the index
            session.clear()
            session['user_id'] = user['id']
            session['user_name'] = user['username']
            session['user_status'] = user['status']
            session['user_measurement'] = user['measurement']
            session['user_instrument'] = user['instrument']
            session['user_analysis'] = user['analysis']
            # measurement related:
            session['c_fresp_structure'] = []
            session['run_clearance'] = False
            session['int_clearance'] = False
            session['bdr_clearance'] = False
            session['people'] = None
            print("%s has logged-in Successfully!" % session['user_name'])
            return redirect(url_for('index'))

        print(error)
        flash(error)

    return render_template('auth/login.html')
Exemple #18
0
def usersamples_register():
    sname = request.args.get('sname')
    dob = request.args.get('dob')
    loc = request.args.get('loc')
    prev = request.args.get('prev')
    description = request.args.get('description')
    db = get_db()
    try:
        db.execute(
            'INSERT INTO sample (author_id, samplename, fabricated, location, previously, description)'
            ' VALUES (?, ?, ?, ?, ?, ?)', (
                g.user['id'],
                sname,
                dob,
                loc,
                prev,
                description,
            ))
        db.commit()
        message = "Sample %s added to the database!" % (sname)
    except:
        message = "Check sample registration"
    return jsonify(message=message)