Exemplo n.º 1
0
    def decorated_function(*args, **kwargs):
        # What is GEN ? Baby don't duplicate me, don't duplicate me, oh no

        # check if session cookie is present
        cookie = request.cookies.get('auth')
        if not cookie:
            flash('You must log in first to access this page.', 'alert-danger')
            return redirect('/login')

        # check if a valid JWT came in the cookie
        payload = jwt_decode(cookie)
        if not payload:
            flash('You must log in first to access this page.', 'alert-danger')
            return redirect('/login')

        # check if the named session exists
        session = Session.select(payload['session'])
        if not session:
            flash('You must log in first to access this page.', 'alert-danger')
            return redirect('/login')

        # check if the session has expired
        if session.expiry <= dt.datetime.now():
            flash('Session expired, please log in again.', 'alert-danger')
            Session.delete(session.id)
            return redirect('/login')

        # check if the named session exists
        user = User.select(session.username)
        if not user.admin:
            flash('This resource is currently unavailable.', 'alert-danger')
            return redirect('/inbox')

        return f(*args, **kwargs)
Exemplo n.º 2
0
def inbox():
    user = current_user()

    senders = {}
    if user.messages:
        for msg in user.messages:
            senders[msg.sender_name] = '{}'.format(User.select(
                msg.sender_name))

    return render_template('inbox.html',
                           title='Inbox',
                           user=user,
                           senders=senders)
Exemplo n.º 3
0
def login():
    # handle incoming form
    if request.method == 'POST':
        # retrieve form data
        args = {
            'username': request.form.get('username', type=str),
            'password': request.form.get('password', type=str),
        }

        # get matching user
        user = User.select(args['username'])

        # check for valid data and no user conflicts
        if any(x == None for x in args.values()):
            flash('All fields are required', 'alert-danger')
        elif any(len(x) > Model.TEXT_MAX_LEN for x in args.values()):
            flash(
                'Fields may not exceed {} characters'.format(
                    Model.TEXT_MAX_LEN), 'alert-danger')
        elif not (user and check_pw(args['password'], user.password)):
            flash('Bad credentials', 'alert-danger')
        elif not user.active:
            flash('Account disabled, please contact an administrator',
                  'alert-danger')
        else:
            # generate new session
            expiry = get_current_timestamp()
            session_id = gen_rand_string()
            Session.insert(session_id=session_id,
                           username=user.username,
                           expiry=expiry,
                           ip=request.remote_addr,
                           user_agent=request.user_agent.string)

            # set cookie in response and redirect to inbox
            res = make_response(redirect('/inbox'))
            # TODO secure=True
            res.set_cookie(
                key='auth',
                value=jwt_encode({
                    'session': session_id,
                    'exp': expiry
                }),
                expires=expiry,
                samesite='Strict',
            )
            flash('Successfully logged in', 'alert-success')
            return res

    return render_template('login.html', title='Log in')
Exemplo n.º 4
0
def user_id(username):
    user = current_user()

    if len(username) > Model.TEXT_MAX_LEN:
        flash('Bad username', 'alert-danger')
        return redirect('/admin')

    otheruser = User.select(username)
    if not otheruser:
        flash("User doesn't exist", 'alert-danger')
        return redirect('/admin')

    # handle incoming form
    if request.method == 'POST':
        # retrieve form data
        args = {
            'username': request.form.get('username', type=str),
            'password': request.form.get('password', type=str),
            'active': request.form.get('active', type=bool),
            'admin': request.form.get('admin', type=bool),
        }

        # check if post username matches route
        if args['username'] != username:
            flash('Malformed request', 'alert-danger')
            return redirect('/admin')
        # prevent self corruption
        elif args['username'] == user.username:
            flash("Can't edit yourself !", 'alert-danger')
            return redirect('/admin')

        # create update dict
        update_dict = {
            'active': True if args['active'] else False,
            'admin': True if args['admin'] else False
        }
        if args['password']:
            update_dict['password'] = hash_pw(args['password'])

        # patch user
        User.update(args['username'], update_dict)
        Session.terminate_user(args['username'])

        flash('User successfully updated', 'alert-success')
        return redirect('/admin')

    return render_template('user_id.html',
                           title="Manager user '{}'".format(username),
                           user=user,
                           otheruser=otheruser)
Exemplo n.º 5
0
def user_delete(username):
    user = current_user()

    if len(username) > Model.TEXT_MAX_LEN:
        flash('Bad username', 'alert-danger')
        return redirect('/admin')

    otheruser = User.select(username)
    if not otheruser:
        flash("User doesn't exist", 'alert-danger')
        return redirect('/admin')

    if username == user.username:
        flash("Can't delete yourself !", 'alert-danger')
        return redirect('/admin')

    User.delete(username)
    flash('User successfully deleted', 'alert-success')
    return redirect('/admin')
Exemplo n.º 6
0
def message_id(message_id):
    user = current_user()

    if len(message_id) > Model.TEXT_MAX_LEN:
        flash('Bad message ID', 'alert-danger')
        return redirect('/inbox')

    message = Message.select(message_id)
    if not message:
        flash("Message doesn't exist", 'alert-danger')
        return redirect('/inbox')
    elif message.recipient_name != user.username:
        flash("Can't view messages from other users", 'alert-danger')
        return redirect('/inbox')

    sender = '{}'.format(User.select(message.sender_name))

    return render_template('message_id.html',
                           title=message.title,
                           user=user,
                           message=message,
                           sender=sender)