Exemplo n.º 1
0
def test_get_close_db(app):
    # Check unique db instance within app context
    with app.app_context():
        db = get_db()
        assert db is get_db()

    # Check db catches incorrect SQL commands
    with pytest.raises(sqlite3.ProgrammingError) as e:
        db.execute('SELECT 1')

    # Check db is closed after context
    assert 'closed' in str(e.value)
Exemplo n.º 2
0
def load_logged_in_user():
    user_id = session.get('user_id')

    if user_id is None:
        g.user = None
    else:
        g.user = db_tools.get_user_from_id(get_db(), user_id)
Exemplo n.º 3
0
def login():
    if request.method == 'POST':
        username = request.form['username']
        password = request.form['password']

        error = None

        if not username:
            error = 'Username is required.'
        elif not password:
            error = 'Password is required.'
        else:
            user = db_tools.get_user(get_db(), username, password)
            if user is None:
                error = 'Incorrect username or password.'

        if error is None:
            session.clear()
            session['user_id'] = user['id']
            session['username'] = username
            session['topic'] = None
            return redirect(url_for('lobby.index'))

        flash(error)

    return render_template('auth/login.html.jinja')
Exemplo n.º 4
0
 def insert_message(self, topic, message_db, message_public):
     # Insert message into database
     db_tools.insert_message(get_db(), **message_db)
     # Insert message into local cache
     if topic not in self.room_messages:
         self.room_messages[topic] = deque(maxlen=MAX_MESSAGES_PER_ROOM)
     self.room_messages[topic].appendleft(message_public)
Exemplo n.º 5
0
def submit_message(data):
    errors = []

    ### Parse incoming message
    data_db = {
        'channel_id': None,
        'author_id': None,
        'body': None,
        'created': None
    }
    data_public = {'username': None, 'body': None, 'created': None}

    ## Message: Body
    if 'message' not in data:
        errors.append("Data contains no 'message' attribute.")
    elif not data['message']:
        errors.append("Empty data['message'].")
    else:
        data_db['body'] = data_public['body'] = data['message']

    ## Message: Author
    data_db['author_id'] = session.get('user_id')
    if data_db['author_id'] is None:
        errors.append('No author_id.')
    data_public['username'] = session.get('username')
    if data_public['username'] is None:
        errors.append('No username in session.')

    ## Message: Topic
    topic = session.get('topic')
    if topic is None:
        errors.append('No topic in session.')
    else:
        db = get_db()
        data_db['channel_id'] = db_tools.get_channel_id(db, topic)
        if data_db['channel_id'] is None:
            errors.append('No channel_id.')

    ## Message: Created
    data_db['created'] = datetime.datetime.now()
    data_public['created'] = data_db['created'].strftime('%Y-%m-%d')

    # Insert message into database
    if not errors:
        room_messages.insert_message(topic, data_db, data_public)
        # Emit message
        emit('announce message', {
            'success': True,
            'message': data_public
        },
             broadcast=True)
    else:
        emit('announce message', {'success': False, 'errors': errors})
Exemplo n.º 6
0
def index(topic):
    db = get_db()
    # Check if topic exists
    mgs, error = room_messages.get_messages(topic)
    if error is not None:
        abort(404, error)

    # session
    session['topic'] = topic
    g.topic = topic

    return render_template('rooms/room.html.jinja', topic=topic)
Exemplo n.º 7
0
def app():
    """Calls the factory and passes test_config to configure app and db
    for testing instead of using local dev configuration"""

    # Create and open temporary file, returning file object and path
    db_fd, db_path = tempfile.mkstemp()

    # Create app with test mode and db path overridden
    app = create_app({
        'TESTING': True,
        'DATABASE': db_path,
    })

    # Initialize tables and test data
    with app.app_context():
        init_db()
        get_db().executescript(_data_sql)

    yield app

    # After test is over, close and remove temp file
    os.close(db_fd)
    os.unlink(db_path)
Exemplo n.º 8
0
def test_register(client, app):
    """Test register view access and successful new user registration in db"""
    # Should render successfully on GET
    assert client.get('/auth/register').status_code == 200

    # POST with valid data
    response = client.post('/auth/register',
                           data={
                               'username': '******',
                               'password': '******'
                           })
    # Should be redirectted to login URL
    assert response.headers['Location'] == 'http://localhost/auth/login'

    # New user should be on database
    with app.app_context():
        assert get_db().execute("SELECT * FROM users WHERE username = '******'",
                                ).fetchone() is not None
Exemplo n.º 9
0
def create():
    if request.method == 'POST':
        topic = request.form['topic']
        error = None
        db = get_db()

        if not topic:
            error = 'Topic is required.'
        elif len(topic) > 24:
            error = 'Topic length most be shorter than 25 characters.'
        elif db_tools.has_channel(db, topic):
            error = 'Channel already exists.'

        if error is not None:
            flash(error)
        else:
            db_tools.insert_channel(db, topic)
            return redirect(url_for('lobby.index'))

    return render_template('lobby/create.html.jinja')
Exemplo n.º 10
0
def register():
    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_tools.has_user(db, username):
            error = f'User {username} is already registered.'

        if error is None:
            db_tools.insert_user(db, username, password)
            return redirect(url_for('auth.login'))

        flash(error)

    return render_template('auth/register.html.jinja')
Exemplo n.º 11
0
    def get_messages(self, topic) -> ('messages', 'error'):
        # Retrieve from cache if available
        if topic in self.room_messages:
            return list(self.room_messages[topic]), None

        # Else retrieve from database if topic has been created
        db = get_db()
        if db_tools.has_channel(db, topic):
            self.room_messages[topic] = deque(maxlen=MAX_MESSAGES_PER_ROOM)
            self.room_messages[topic].extend(
                db_tools.get_all_messages(db,
                                          topic,
                                          limit=MAX_MESSAGES_PER_ROOM,
                                          as_dicts=True))
            return list(self.room_messages[topic]), None

        # Else return with error message
        if len(topic) > 10:
            # Shorten topic name for visibility
            topic = topic[:10] + '...'
        return None, f"Channel for topic {topic} doesn't exist."
Exemplo n.º 12
0
def index():
    channels = db_tools.get_channels_all(get_db())
    return render_template('lobby/index.html.jinja', channels=channels)