Beispiel #1
0
def test_save_playbook(client):
    without_login = client.post('/api/playbook/save')
    wrong_method = client.get('/api/playbook/save')
    authenticate(client)
    change_pb = client.post('/api/playbook/get', data={
        'key': 1,
    }).json
    change_pb['name'] = 'Modified initial setup'
    change_pb['description'] = 'Modified description'
    save_pb = client.post('/api/playbook/save', data=change_pb).json
    check_pb = client.post('/api/playbook/get', data={
        'key': 1,
    }).json
    wrong_id = client.post('/api/playbook/save', data={
        'key': 0,
        'name': 'Not Good',
        'description': 'This is a test of a non valid id'
    }).json
    logout(client)
    assert without_login.status_code == 302
    assert wrong_method.status_code == 405
    assert save_pb['messageMode'] == 0
    assert wrong_id['messageMode'] == 1
    assert check_pb['name'] == 'Modified initial setup'
    assert check_pb['description'] == 'Modified description'
    assert isinstance(check_pb['tasks'], list)
def test_used_reset_token(client, get_message):
    with capture_reset_password_requests() as requests:
        client.post(
            '/reset',
            data=dict(
                email='*****@*****.**'),
            follow_redirects=True)

    token = requests[0]['token']

    # use the token
    response = client.post('/reset/' + token, data={
        'password': '******',
        'password_confirm': 'newpassword'
    }, follow_redirects=True)

    assert get_message('PASSWORD_RESET') in response.data

    logout(client)

    # attempt to use it a second time
    response2 = client.post('/reset/' + token, data={
        'password': '******',
        'password_confirm': 'otherpassword'
    }, follow_redirects=True)

    msg = get_message('INVALID_RESET_PASSWORD_TOKEN')
    assert msg in response2.data
Beispiel #3
0
def test_get_playbooks(client):
    without_login = client.get('/api/playbook/all')
    authenticate(client)
    playbooks = client.get('/api/playbook/all').json
    logout(client)
    assert without_login.status_code == 302
    assert isinstance(playbooks['playbooks'], list)
Beispiel #4
0
def test_change_password(client):
    # TODO: Fix the change password repetition code
    without_login = client.post('/change',
                                data={"password": "******",
                                      "new_password": "******",
                                      "new_password_confirm": "new_password"})

    authenticate(client)
    new_password = client.post(
        '/change',
        data={
            "password": "******",
            "new_password": "******",
            "new_password_confirm": "new_password",
        }
    )
    password = client.post(
        '/change',
        data={
            "password": "******",
            "new_password": "******",
            "new_password_confirm": "password",
        }
    )
    logout(client)
    assert without_login.status_code == 302
    print new_password.data
    assert '/#/settings/user' in new_password.location
    assert password.status_code == 302
    assert '/#/settings/user' in password.location
Beispiel #5
0
def test_get_inventory(client):
    without_login = client.get('/api/inventory/all')
    authenticate(client)
    room = client.get('/api/inventory/all').json
    logout(client)
    assert without_login.status_code == 302
    assert isinstance(room['rooms'], list)
Beispiel #6
0
def test_get_all(client):
    without_login = client.get('/api/user/all')
    authenticate(client)
    user_login = client.get('/api/user/all')
    logout(client)
    users = user_login.json
    assert without_login.status_code == 302
    assert 2 == len(users['users'])
def test_trackable_flag(app, client, get_message):
    recorded = []

    @login_instructions_sent.connect_via(app)
    def on_instructions_sent(app, user, login_token):
        assert isinstance(app, Flask)
        assert isinstance(user, UserMixin)
        assert isinstance(login_token, string_types)
        recorded.append(user)

    # Test disabled account
    response = client.post("/login", data=dict(email="*****@*****.**"), follow_redirects=True)
    assert get_message("DISABLED_ACCOUNT") in response.data

    # Test login with json and valid email
    data = '{"email": "*****@*****.**", "password": "******"}'
    response = client.post("/login", data=data, headers={"Content-Type": "application/json"})
    assert response.status_code == 200
    assert len(recorded) == 1

    # Test login with json and invalid email
    data = '{"email": "*****@*****.**", "password": "******"}'
    response = client.post("/login", data=data, headers={"Content-Type": "application/json"})
    assert b"errors" in response.data

    # Test sends email and shows appropriate response
    with capture_passwordless_login_requests() as requests:
        with app.mail.record_messages() as outbox:
            response = client.post("/login", data=dict(email="*****@*****.**"), follow_redirects=True)

    assert len(recorded) == 2
    assert len(requests) == 1
    assert len(outbox) == 1
    assert "user" in requests[0]
    assert "login_token" in requests[0]

    user = requests[0]["user"]
    assert get_message("LOGIN_EMAIL_SENT", email=user.email) in response.data

    token = requests[0]["login_token"]
    response = client.get("/login/" + token, follow_redirects=True)
    assert get_message("PASSWORDLESS_LOGIN_SUCCESSFUL") in response.data

    # Test already authenticated
    response = client.get("/login/" + token, follow_redirects=True)
    assert get_message("PASSWORDLESS_LOGIN_SUCCESSFUL") not in response.data

    logout(client)

    # Test invalid token
    response = client.get("/login/bogus", follow_redirects=True)
    assert get_message("INVALID_LOGIN_TOKEN") in response.data

    # Test login request with invalid email
    response = client.post("/login", data=dict(email="*****@*****.**"))
    assert get_message("USER_DOES_NOT_EXIST") in response.data
Beispiel #8
0
def test_roles_accepted(client):
    for user in ("*****@*****.**", "*****@*****.**"):
        authenticate(client, user)
        response = client.get("/admin_or_editor")
        assert b'Admin or Editor Page' in response.data
        logout(client)

    authenticate(client, "*****@*****.**")
    response = client.get("/admin_or_editor", follow_redirects=True)
    assert b'Home Page' in response.data
Beispiel #9
0
def test_categories(client):
    without_login = client.get('/api/task/categories')
    authenticate(client)

    categories = client.get('/api/task/categories').json

    logout(client)
    assert without_login.status_code == 302
    assert isinstance(categories, dict)
    assert isinstance(categories['categories'], list)
Beispiel #10
0
def test_category(client):
    without_login = client.post('/api/task/category')
    authenticate(client)

    category = client.post('/api/task/category',
                           data={'name': 'cloud'}).json
    not_valid_form = client.post('/api/task/category').json
    logout(client)
    assert without_login.status_code == 302
    assert isinstance(category['modules'], list)
    assert category['category_name'] == 'cloud'
    assert isinstance(not_valid_form, dict)
def test_trackable_flag(app, client, get_message):
    recorded = []

    @login_instructions_sent.connect_via(app)
    def on_instructions_sent(app, user, login_token):
        recorded.append(user)

    # Test disabled account
    response = client.post('/login', data=dict(email='*****@*****.**'), follow_redirects=True)
    assert get_message('DISABLED_ACCOUNT') in response.data

    # Test login with json and valid email
    data = '{"email": "*****@*****.**", "password": "******"}'
    response = client.post('/login', data=data, headers={'Content-Type': 'application/json'})
    assert response.status_code == 200
    assert len(recorded) == 1

    # Test login with json and invalid email
    data = '{"email": "*****@*****.**", "password": "******"}'
    response = client.post('/login', data=data, headers={'Content-Type': 'application/json'})
    assert b'errors' in response.data

    # Test sends email and shows appropriate response
    with capture_passwordless_login_requests() as requests:
        with app.mail.record_messages() as outbox:
            response = client.post('/login', data=dict(email='*****@*****.**'), follow_redirects=True)

    assert len(recorded) == 2
    assert len(requests) == 1
    assert len(outbox) == 1
    assert 'user' in requests[0]
    assert 'login_token' in requests[0]

    user = requests[0]['user']
    assert get_message('LOGIN_EMAIL_SENT', email=user.email) in response.data

    token = requests[0]['login_token']
    response = client.get('/login/' + token, follow_redirects=True)
    assert get_message('PASSWORDLESS_LOGIN_SUCCESSFUL') in response.data

    # Test already authenticated
    response = client.get('/login/' + token, follow_redirects=True)
    assert get_message('PASSWORDLESS_LOGIN_SUCCESSFUL') not in response.data

    logout(client)

    # Test invalid token
    response = client.get('/login/bogus', follow_redirects=True)
    assert get_message('INVALID_LOGIN_TOKEN') in response.data

    # Test login request with invalid email
    response = client.post('/login', data=dict(email='*****@*****.**'))
    assert get_message('USER_DOES_NOT_EXIST') in response.data
Beispiel #12
0
def test_get_playbook(client):
    wrong_method = client.get('/api/playbook/get')
    without_login = client.post('/api/playbook/get')
    authenticate(client)
    check_pb = client.post('/api/playbook/get', data={
        'key': 1,
    }).json
    logout(client)
    assert without_login.status_code == 302
    assert wrong_method.status_code == 405
    assert check_pb['name'] == 'Initial setup'
    assert check_pb['description'] == 'Hardening of the operative system'
    assert isinstance(check_pb['tasks'], list)
def test_trackable_flag(app, client):
    e = '*****@*****.**'
    authenticate(client, email=e)
    logout(client)
    authenticate(client, email=e, headers={'X-Forwarded-For': '127.0.0.1'})

    with app.app_context():
        user = app.security.datastore.find_user(email=e)
        assert user.last_login_at is not None
        assert user.current_login_at is not None
        assert user.last_login_ip == 'untrackable'
        assert user.current_login_ip == '127.0.0.1'
        assert user.login_count == 2
Beispiel #14
0
def test_get_user(client):
    user = {
        "admin": True,
        "email": "*****@*****.**",
        "key": 1,
        "username": "******"
    }
    without_login = client.get('/api/user/get')
    authenticate(client)
    user_login = client.get('/api/user/get')
    logout(client)
    assert without_login.status_code == 302
    assert user == user_login.json
Beispiel #15
0
def test_delete_rooms(client):
    without_login = client.post('/api/inventory/delete')
    authenticate(client)
    delete = client.post('/api/inventory/delete', data={
        'key': 1
    }).json
    fail = client.post('/api/inventory/delete', data={
        'key': 1
    }).json

    logout(client)
    assert without_login.status_code == 302
    assert delete['messageMode'] == 0
    assert fail['messageMode'] == 1
def test_trackable_with_multiple_ips_in_headers(app, client):
    e = '*****@*****.**'
    authenticate(client, email=e)
    logout(client)
    authenticate(client, email=e, headers={
        'X-Forwarded-For': '99.99.99.99, 88.88.88.88'})

    with app.app_context():
        user = app.security.datastore.find_user(email=e)
        assert user.last_login_at is not None
        assert user.current_login_at is not None
        assert user.last_login_ip == 'untrackable'
        assert user.current_login_ip == '88.88.88.88'
        assert user.login_count == 2
Beispiel #17
0
def test_delete_task(client):
    without_login = client.post('/api/task/delete')
    authenticate(client)

    delete = client.post('/api/task/delete', data={
        'key': 1
    }).json
    wrong_id = client.post('/api/task/delete', data={
        'key': 0
    }).json
    delete_playbook(client)
    logout(client)
    assert without_login.status_code == 302
    assert delete['messageMode'] == 0
    assert wrong_id['messageMode'] == 1
Beispiel #18
0
def viewlogout():
    var = style("webmaster")
    template = env.get_template("web-res-login.html")
    user = session.get('username')

    try:
        logout()
    except Exception as e:
        app.logger.error('Error during logout of: {0} (Error code: {1})'.format(user, e) )
        var['msg'] = "Errore Interno.<br>Ripetere il login e tentare nuovamente il logout.<br>Se il problema persiste, contatta immediatamente il webmaster."
        return template.render(var)
        
    var['success'] = True
    var['msg'] = 'Logout completato con successo'
    app.logger.info("User '{0}' logged out successfully".format(user) )
    return template.render(var)
def test_registerable_flag(client, app, get_message):
    recorded = []

    # Test the register view
    response = client.get('/register')
    assert b"<h1>Register</h1>" in response.data

    # Test registering is successful, sends email, and fires signal
    @user_registered.connect_via(app)
    def on_user_registerd(app, user, confirm_token):
        recorded.append(user)

    data = dict(email='*****@*****.**', password='******', password_confirm='password')
    with app.mail.record_messages() as outbox:
        response = client.post('/register', data=data, follow_redirects=True)

    assert len(recorded) == 1
    assert len(outbox) == 1
    assert b'Post Register' in response.data

    logout(client)

    # Test user can login after registering
    response = authenticate(client, email='*****@*****.**', password='******')
    assert response.status_code == 302

    logout(client)

    # Test registering with an existing email
    data = dict(email='*****@*****.**', password='******', password_confirm='password')
    response = client.post('/register', data=data, follow_redirects=True)
    assert get_message('EMAIL_ALREADY_ASSOCIATED', email='*****@*****.**') in response.data

    # Test registering with JSON
    data = '{ "email": "*****@*****.**", "password": "******"}'
    response = client.post('/register', data=data, headers={'Content-Type': 'application/json'})
    assert response.headers['content-type'] == 'application/json'
    assert response.jdata['meta']['code'] == 200

    logout(client)

    # Test registering with invalid JSON
    data = '{ "email": "bogus", "password": "******"}'
    response = client.post('/register', data=data, headers={'Content-Type': 'application/json'})
    assert response.headers['content-type'] == 'application/json'
    assert response.jdata['meta']['code'] == 400

    logout(client)

    # Test ?next param
    data = dict(email='*****@*****.**',
                password='******',
                password_confirm='password')

    response = client.post('/register?next=/page1', data=data, follow_redirects=True)
    assert b'Page 1' in response.data
Beispiel #20
0
def test_add_user(client):
    data = {
        "username": "******",
        "email": "*****@*****.**",
        "password": "******"
    }
    without_login = client.post('/api/user/add', data=data)
    authenticate(client)
    wrong_method = client.get('/api/user/add?username=a&[email protected]')
    save = client.post('/api/user/add', data=data)
    mistake = client.post('/api/user/add', data={"username": "******",
                                                 "password": "******"})
    logout(client)
    assert without_login.status_code == 302
    assert wrong_method.status_code == 405
    assert {'message': 'saved'} == save.json
    assert {'message': 'failed'} == mistake.json
Beispiel #21
0
def test_add_playbook(client):
    without_login = client.post('/api/playbook/new')
    wrong_method = client.get('/api/playbook/new')
    authenticate(client)
    save = client.post('/api/playbook/new', data={
        'name': 'Initial setup',
        'description': 'Hardening of the operative system'
    }).json
    wrong = client.post('/api/playbook/new', data={
        'description': 'Hardening of the operative system'
    }).json
    logout(client)
    assert without_login.status_code == 302
    assert wrong_method.status_code == 405
    assert save['messageMode'] == 0
    assert save['messageText'] == 'Playbook saved'
    assert wrong['messageMode'] == 1
def test_confirmation_different_user_when_logged_in(client, get_message):
    e1 = '*****@*****.**'
    e2 = '*****@*****.**'

    with capture_registrations() as registrations:
        for e in e1, e2:
            client.post('/register', data=dict(email=e, password='******'))
            logout(client)

    token1 = registrations[0]['confirm_token']
    token2 = registrations[1]['confirm_token']

    client.get('/confirm/' + token1, follow_redirects=True)
    logout(client)
    authenticate(client, email=e1)

    response = client.get('/confirm/' + token2, follow_redirects=True)
    assert get_message('EMAIL_CONFIRMED') in response.data
    assert b'Hello [email protected]' in response.data
Beispiel #23
0
def test_delete_playbook(client):
    without_login = client.post('/api/playbook/delete')
    wrong_method = client.get('/api/playbook/delete')
    authenticate(client)
    delete_pb = client.post('/api/playbook/delete', data={
        'key': 1,
    }).json
    check_pb = client.post('/api/playbook/get', data={
        'key': 1,
    }).json
    not_exist_pb = client.post('/api/playbook/delete', data={
        'key': 0,
    }).json

    logout(client)
    assert without_login.status_code == 302
    assert wrong_method.status_code == 405
    assert delete_pb['messageMode'] == 0
    assert check_pb['messageMode'] == 1
    assert not_exist_pb['messageMode'] == 1
Beispiel #24
0
def test_change_user(client):
    username = '******'
    wrong_method = client.get('/api/user/modify?username=a&[email protected]')
    without_login = client.post('/api/user/modify')
    authenticate(client)
    user_login = client.get('/api/user/get').json
    user_login['username'] = username
    user_login['password'] = '******'
    client.post('/api/user/modify', data=user_login)
    user_login['password'] = '******'
    wrong_password = client.post('/api/user/modify', data=user_login).json
    user_login.pop('password')
    form_not_valid = client.post('/api/user/modify', data=user_login).json
    user_login = client.get('/api/user/get').json
    logout(client)
    assert without_login.status_code == 302
    assert wrong_method.status_code == 405
    assert user_login['username'] == username
    assert wrong_password['messageText'] == 'Wrong password'
    assert form_not_valid['messageText'] == 'Failed to save changes'
Beispiel #25
0
def test_add_task(client):
    without_login = client.post('/api/task/add')
    authenticate(client)
    add_playbook(client)
    # Review playooks key
    save = client.post('/api/task/add', data={
        'key': 2,
        'task': 'Update package list',
        'module': 'apt',
        'configuration-0-option': 'update_cache',
        'configuration-0-value': 'yes',
        'configuration-1-option': 'upgrade',
        'configuration-1-value': 'yes',
    }).json
    form_incomplete = client.post('/api/task/add', data={
        'task': 'Update package list',
    }).json
    logout(client)
    assert without_login.status_code == 302
    assert save['messageMode'] == 0
    assert form_incomplete['messageMode'] == 1
Beispiel #26
0
def test_add_room(client):
    without_login = client.post('/api/inventory/new')
    authenticate(client)
    save = client.post('/api/inventory/new', data={
        'key': 0,
        'name': 'sala-1',
        'network': '192.168.0.1',
        'gateway': '192.168.0.1',
        'netmask': 24,
        'machines': 10,
        'user': '******',
        'private_key': 'id_rsa',
    }).json
    fail = client.post('/api/inventory/new', data={
        'name': 'sala-1',
        'network': '192.168.0.1',
        'machines': 10
    }).json
    logout(client)
    assert without_login.status_code == 302
    assert save['messageMode'] == 0
    assert fail['messageMode'] == 1
Beispiel #27
0
def test_change_admin(client):
    wrong_method = client.get('/api/user/admin?key=2')
    without_login = client.post('/api/user/admin')
    authenticate(client)
    users = client.get('/api/user/all').json
    user_id = None
    for each in users['users']:
        if not each['admin']:
            user_id = each['key']
            break
    to_admin = client.post('/api/user/admin', data={'key': user_id})
    to_user = client.post('/api/user/admin', data={'key': user_id})
    mistake = client.post('/api/user/admin', data={'key': 0})
    invalid = client.post('/api/user/admin', data={'akey': 0})
    logout(client)
    assert without_login.status_code == 302
    assert wrong_method.status_code == 405
    assert invalid.status_code == 200
    assert {'message': 'saved'} == to_admin.json
    assert {'message': 'saved'} == to_user.json
    assert {'message': 'user not found'} == mistake.json
    assert {'message': 'failed'} == invalid.json
Beispiel #28
0
def test_delete_user(client):
    wrong_method = client.get('/api/user/delete?key=2')
    without_login = client.post('/api/user/delete')
    authenticate(client)
    users = client.get('/api/user/all').json
    user_id = None
    for each in users['users']:
        if not each['admin']:
            user_id = each['key']
            break

    delete = client.post('/api/user/delete', data={'key': user_id})
    invalid = client.post('/api/user/delete', data={'keyx': user_id})
    mistake = client.post('/api/user/delete', data={'key': 0})
    logout(client)
    assert without_login.status_code == 302
    assert wrong_method.status_code == 405
    assert delete.status_code == 200
    assert mistake.status_code == 200
    assert invalid.status_code == 200
    assert {'message': 'deleted'} == delete.json
    assert {'message': 'user not found'} == mistake.json
    assert {'message': 'failed'} == invalid.json
def test_view_configuration(client):
    response = client.get('/custom_login')
    assert b"<h1>Login</h1>" in response.data

    response = authenticate(client, endpoint='/custom_login')
    assert 'location' in response.headers
    assert response.headers['Location'] == 'http://localhost/post_login'

    response = logout(client, endpoint='/custom_logout')
    assert 'location' in response.headers
    assert response.headers['Location'] == 'http://localhost/post_logout'

    response = client.get('/http', headers={
        'Authorization': 'Basic %s' % base64.b64encode(b"[email protected]:bogus")
    })
    assert b'<h1>Unauthorized</h1>' in response.data
    assert 'WWW-Authenticate' in response.headers
    assert 'Basic realm="Custom Realm"' == response.headers['WWW-Authenticate']
Beispiel #30
0
    def train_env_model_early_stopping(self, num_epochs=200, passes=20):
        """
            Train environment model with replay buffer
        """
        best_loss, best_loss_idx, model_dict = None, None, None
        train_dataset = TensorDataset(*self.read_trajs_from_buffer(
            self.memory_traj_train, len(self.memory_traj_train)))
        test_dataset = TensorDataset(*self.read_trajs_from_buffer(
            self.memory_traj_test, len(self.memory_traj_test)))
        train_loader = DataLoader(dataset=train_dataset,
                                  batch_size=self.batch_size,
                                  shuffle=True,
                                  num_workers=0)
        test_loader = DataLoader(dataset=test_dataset,
                                 batch_size=self.batch_size,
                                 shuffle=False,
                                 num_workers=0)
        test_mses = []
        t = time.time()

        def run_epoch(loader, train=True):
            if train:
                self.model.train()
            else:
                self.model.eval()
            total_mse_loss, total_dt_loss = 0, 0
            num_iters = 0
            for i, (states, actions, time_steps, lengths) in enumerate(loader):
                max_length = lengths.max()
                states = states[:, :max_length + 1, :].to(
                    self.device)  # [B, T+1, D_state]
                actions = actions[:, :max_length, :].to(
                    self.device)  # [B, T, D_action]
                time_steps = time_steps[:, :max_length + 1].to(
                    self.device)  # [B, T+1]
                losses_dict = self.model.compute_loss(states,
                                                      actions,
                                                      time_steps,
                                                      lengths.to(self.device),
                                                      train=train)
                loss = losses_dict['total']
                total_mse_loss += losses_dict['mse'].item()
                total_dt_loss += losses_dict['dt'].item()
                num_iters += 1

                # optimize
                if train:
                    self.optimizer.zero_grad()
                    loss.backward()
                    self.optimizer.step()
            return {
                'mse': total_mse_loss / num_iters,
                'dt': total_dt_loss / num_iters
            }, num_iters

        for e in range(num_epochs):
            train_loss_dict, num_iters = run_epoch(train_loader, train=True)
            with torch.no_grad():
                test_loss_dict, _ = run_epoch(test_loader, train=False)
            test_mses.append(test_loss_dict['mse'])
            if best_loss is None or test_mses[-1] < best_loss:
                best_loss = test_mses[-1]
                best_loss_idx = e
                model_dict = self.model.state_dict()
                torch.save(
                    {
                        'model_state_dict': model_dict,
                        'model_test_loss': test_mses,
                        'model_best_test_loss': best_loss
                    }, self.ckpt_path)
            log = "Epoch %d | training MSE = %.6f | test MSE = %.6f | training dt loss = %.6f |" \
                  " test dt loss = %.6f" % (e + 1, train_loss_dict['mse'], test_loss_dict['mse'],
                                            train_loss_dict['dt'], test_loss_dict['dt'])
            if 'kl' in train_loss_dict:
                log += " | training kl = %.6f" % train_loss_dict['kl']
            log += " | time = %.6f s" % (time.time() - t)
            utils.logout(self.logger, log)
            t = time.time()

            if e - best_loss_idx >= passes:
                break

        utils.logout(self.logger,
                     'Finish training model, best test MSE: %.6f' % best_loss)
        self.model.load_state_dict(model_dict)
def test_invalid_request(caplog, oidc_settings, oidc_client, simple_user, app):
    redirect_uri = oidc_client.redirect_uris.split()[0]
    if oidc_client.authorization_flow == oidc_client.FLOW_AUTHORIZATION_CODE:
        fragment = False
        response_type = 'code'
    elif oidc_client.authorization_flow == oidc_client.FLOW_IMPLICIT:
        fragment = True
        response_type = 'id_token token'
    else:
        raise NotImplementedError

    # client_id
    authorize_url = make_url('oidc-authorize', params={})

    response = app.get(authorize_url, status=400)
    assert 'missing parameter \'client_id\'' in response.content

    # redirect_uri
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
    })

    response = app.get(authorize_url, status=400)
    assert 'missing parameter \'redirect_uri\'' in response.content

    # invalid client_id
    authorize_url = make_url('oidc-authorize', params={
        'client_id': 'xxx',
        'redirect_uri': redirect_uri,
    })

    response = app.get(authorize_url, status=400)
    assert 'unknown client_id' in response.content

    # missing response_type
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
    })

    response = app.get(authorize_url)
    assert_oidc_error(response, 'invalid_request', 'missing parameter \'response_type\'',
                      fragment=fragment)
    logrecord = [rec for rec in caplog.records if rec.funcName == 'authorization_error'][0]
    assert logrecord.levelname == 'WARNING'
    assert logrecord.redirect_uri == 'https://example.com/callback'
    assert 'missing parameter \'response_type\'' in logrecord.message

    # missing scope
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': 'code',
    })

    response = app.get(authorize_url)
    assert_oidc_error(response, 'invalid_request', 'missing parameter \'scope\'', fragment=fragment)

    # invalid max_age
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': 'code',
        'scope': 'openid',
        'max_age': 'xxx',
    })
    response = app.get(authorize_url)
    assert_oidc_error(response, 'invalid_request', 'max_age is not', fragment=fragment)
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': 'code',
        'scope': 'openid',
        'max_age': '-1',
    })
    response = app.get(authorize_url)
    assert_oidc_error(response, 'invalid_request', 'max_age is not', fragment=fragment)

    # invalid redirect_uri
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': 'xxx',
        'response_type': 'code',
        'scope': 'openid',
    })

    response = app.get(authorize_url)
    assert_oidc_error(response, 'invalid_request', 'unauthorized redirect_uri', fragment=fragment)

    # unsupported response_type
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': 'xxx',
        'scope': 'openid',
    })

    response = app.get(authorize_url)
    if oidc_client.authorization_flow == oidc_client.FLOW_AUTHORIZATION_CODE:
        assert_oidc_error(response, 'unsupported_response_type', 'only code is supported')
    elif oidc_client.authorization_flow == oidc_client.FLOW_IMPLICIT:
        assert_oidc_error(response, 'unsupported_response_type',
                          'only "id_token token" or "id_token" are supported', fragment=fragment)

    # openid scope is missing
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': response_type,
        'scope': 'profile',
    })

    response = app.get(authorize_url)
    assert_oidc_error(response, 'invalid_request', 'openid scope is missing', fragment=fragment)

    # use of an unknown scope
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': response_type,
        'scope': 'openid email profile zob',
    })

    response = app.get(authorize_url)
    assert_oidc_error(response, 'invalid_scope', fragment=fragment)

    # restriction on scopes
    oidc_settings.A2_IDP_OIDC_SCOPES = ['openid']
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': response_type,
        'scope': 'openid email',
    })

    response = app.get(authorize_url)
    assert_oidc_error(response, 'invalid_scope', fragment=fragment)
    del oidc_settings.A2_IDP_OIDC_SCOPES

    # cancel
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': response_type,
        'scope': 'openid email profile',
        'cancel': '1',
    })

    response = app.get(authorize_url)
    assert_oidc_error(response, 'access_denied', error_description='user did not authenticate',
                      fragment=fragment)

    # prompt=none
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': response_type,
        'scope': 'openid email profile',
        'prompt': 'none',
    })

    response = app.get(authorize_url)
    assert_oidc_error(response, 'login_required', error_description='prompt is none',
                      fragment=fragment)

    utils.login(app, simple_user)

    # prompt=none max_age=0
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': response_type,
        'scope': 'openid email profile',
        'max_age': '0',
        'prompt': 'none',
    })

    response = app.get(authorize_url)
    assert_oidc_error(response, 'login_required', error_description='prompt is none',
                      fragment=fragment)

    # max_age=0
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': response_type,
        'scope': 'openid email profile',
        'max_age': '0',
    })
    response = app.get(authorize_url)
    assert urlparse.urlparse(response['Location']).path == reverse('auth_login')

    # prompt=login
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': response_type,
        'scope': 'openid email profile',
        'prompt': 'login',
    })
    response = app.get(authorize_url)
    assert urlparse.urlparse(response['Location']).path == reverse('auth_login')

    # user refuse authorization
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': response_type,
        'scope': 'openid email profile',
        'prompt': 'none',
    })
    response = app.get(authorize_url)
    if oidc_client.authorization_mode != oidc_client.AUTHORIZATION_MODE_NONE:
        assert_oidc_error(response, 'consent_required', error_description='prompt is none',
                          fragment=fragment)

    # user refuse authorization
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': response_type,
        'scope': 'openid email profile',
    })
    response = app.get(authorize_url)
    if oidc_client.authorization_mode != oidc_client.AUTHORIZATION_MODE_NONE:
        response = response.form.submit('refuse')
        assert_oidc_error(response, 'access_denied', error_description='user denied access',
                          fragment=fragment)

    # authorization exists
    authorize = OIDCAuthorization.objects.create(
        client=oidc_client, user=simple_user, scopes='openid profile email',
        expired=now() + datetime.timedelta(days=2))
    response = app.get(authorize_url)
    if oidc_client.authorization_flow == oidc_client.FLOW_AUTHORIZATION_CODE:
        assert_authorization_response(response, code=None, fragment=fragment)
    elif oidc_client.authorization_flow == oidc_client.FLOW_IMPLICIT:
        assert_authorization_response(response, access_token=None, id_token=None, expires_in=None,
                                      token_type=None, fragment=fragment)

    # client ask for explicit authorization
    authorize_url = make_url('oidc-authorize', params={
        'client_id': oidc_client.client_id,
        'redirect_uri': redirect_uri,
        'response_type': response_type,
        'scope': 'openid email profile',
        'prompt': 'consent',
    })
    response = app.get(authorize_url)
    assert 'a2-oidc-authorization-form' in response.content
    # check all authorization have been deleted, it's our policy
    assert OIDCAuthorization.objects.count() == 0
    if oidc_client.authorization_mode == oidc_client.AUTHORIZATION_MODE_NONE:
        # authorization mode is none, but explicit consent is asked, we validate it
        response = response.form.submit('accept')

    # authorization has expired
    OIDCCode.objects.all().delete()
    authorize.expired = now() - datetime.timedelta(days=2)
    authorize.save()
    response = app.get(authorize_url)
    assert 'a2-oidc-authorization-form' in response.content
    authorize.expired = now() + datetime.timedelta(days=2)
    authorize.scopes = 'openid profile'
    authorize.save()
    assert OIDCAuthorization.objects.count() == 1
    response = response.form.submit('accept')
    assert OIDCAuthorization.objects.count() == 1
    # old authorizations have been deleted
    assert OIDCAuthorization.objects.get().pk != authorize.pk

    # check expired codes
    if oidc_client.authorization_flow == oidc_client.FLOW_AUTHORIZATION_CODE:
        assert OIDCCode.objects.count() == 1
        code = OIDCCode.objects.get()
        assert code.is_valid()
        # make code expire
        code.expired = now() - datetime.timedelta(seconds=120)
        assert not code.is_valid()
        code.save()
        location = urlparse.urlparse(response['Location'])
        query = urlparse.parse_qs(location.query)
        assert set(query.keys()) == set(['code'])
        assert query['code'] == [code.uuid]
        code = query['code'][0]
        token_url = make_url('oidc-token')
        response = app.post(token_url, params={
            'grant_type': 'authorization_code',
            'code': code,
            'redirect_uri': oidc_client.redirect_uris.split()[0],
        }, headers=client_authentication_headers(oidc_client), status=400)
        assert 'error' in response.json
        assert response.json['error'] == 'invalid_request'
        assert response.json['desc'] == 'code has expired or user is disconnected'

    # invalid logout
    logout_url = make_url('oidc-logout', params={
        'post_logout_redirect_uri': 'https://whatever.com/',
    })
    response = app.get(logout_url)
    assert '_auth_user_id' in app.session
    assert 'Location' in response.headers

    # check code expiration after logout
    if oidc_client.authorization_flow == oidc_client.FLOW_AUTHORIZATION_CODE:
        code = OIDCCode.objects.get()
        code.expired = now() + datetime.timedelta(seconds=120)
        code.save()
        assert code.is_valid()
        utils.logout(app)
        code = OIDCCode.objects.get()
        assert not code.is_valid()
        response = app.post(token_url, params={
            'grant_type': 'authorization_code',
            'code': code.uuid,
            'redirect_uri': oidc_client.redirect_uris.split()[0],
        }, headers=client_authentication_headers(oidc_client), status=400)
        assert 'error' in response.json
        assert response.json['error'] == 'invalid_request'
        assert response.json['desc'] == 'code has expired or user is disconnected'
def test_trackable_flag(app, client, get_message):
    recorded = []

    @login_instructions_sent.connect_via(app)
    def on_instructions_sent(app, user, login_token):
        assert isinstance(app, Flask)
        assert isinstance(user, UserMixin)
        assert isinstance(login_token, string_types)
        recorded.append(user)

    # Test disabled account
    response = client.post(
        "/login", data=dict(email="*****@*****.**"), follow_redirects=True
    )
    assert get_message("DISABLED_ACCOUNT") in response.data

    # Test login with json and valid email
    data = dict(email="*****@*****.**", password="******")
    response = client.post(
        "/login", json=data, headers={"Content-Type": "application/json"}
    )
    assert response.status_code == 200
    assert len(recorded) == 1

    # Test login with json and invalid email
    data = dict(email="*****@*****.**", password="******")
    response = client.post(
        "/login", json=data, headers={"Content-Type": "application/json"}
    )
    assert b"errors" in response.data

    # Test sends email and shows appropriate response
    with capture_passwordless_login_requests() as requests:
        with app.mail.record_messages() as outbox:
            response = client.post(
                "/login", data=dict(email="*****@*****.**"), follow_redirects=True
            )

    assert len(recorded) == 2
    assert len(requests) == 1
    assert len(outbox) == 1
    assert "user" in requests[0]
    assert "login_token" in requests[0]

    user = requests[0]["user"]
    assert get_message("LOGIN_EMAIL_SENT", email=user.email) in response.data

    token = requests[0]["login_token"]
    response = client.get("/login/" + token, follow_redirects=True)
    assert get_message("PASSWORDLESS_LOGIN_SUCCESSFUL") in response.data

    # Test already authenticated
    response = client.get("/login/" + token, follow_redirects=True)
    assert get_message("PASSWORDLESS_LOGIN_SUCCESSFUL") not in response.data

    logout(client)

    # Test invalid token
    response = client.get("/login/bogus", follow_redirects=True)
    assert get_message("INVALID_LOGIN_TOKEN") in response.data

    # Test login request with invalid email
    response = client.post("/login", data=dict(email="*****@*****.**"))
    assert get_message("USER_DOES_NOT_EXIST") in response.data
def test_registerable_flag(client, app, get_message):
    recorded = []

    # Test the register view
    response = client.get('/register')
    assert b"<h1>Register</h1>" in response.data

    # Test registering is successful, sends email, and fires signal
    @user_registered.connect_via(app)
    def on_user_registerd(app, user, confirm_token):
        assert isinstance(app, Flask)
        assert isinstance(user, UserMixin)
        assert confirm_token is None
        recorded.append(user)

    data = dict(email='*****@*****.**',
                password='******',
                password_confirm='password',
                next='')
    with app.mail.record_messages() as outbox:
        response = client.post('/register', data=data, follow_redirects=True)

    assert len(recorded) == 1
    assert len(outbox) == 1
    assert b'Post Register' in response.data

    logout(client)

    # Test user can login after registering
    response = authenticate(client, email='*****@*****.**', password='******')
    assert response.status_code == 302

    logout(client)

    # Test registering with an existing email
    data = dict(email='*****@*****.**',
                password='******',
                password_confirm='password',
                next='')
    response = client.post('/register', data=data, follow_redirects=True)
    assert get_message('EMAIL_ALREADY_ASSOCIATED',
                       email='*****@*****.**') in response.data

    # Test registering with an existing email but case insensitive
    data = dict(email='*****@*****.**',
                password='******',
                password_confirm='password',
                next='')
    response = client.post('/register', data=data, follow_redirects=True)
    assert get_message('EMAIL_ALREADY_ASSOCIATED',
                       email='*****@*****.**') in response.data

    logout(client)

    # Test ?next param
    data = dict(email='*****@*****.**',
                password='******',
                password_confirm='password',
                next='')

    response = client.post('/register?next=/page1',
                           data=data,
                           follow_redirects=True)
    assert b'Page 1' in response.data
Beispiel #34
0
    simulator = SwimmerSimulator()
elif args.env == 'hopper':
    simulator = HopperSimulator()
else:
    raise NotImplementedError
simulator.seed(args.seed)

ckpt_path = 'models/{}_{}_{}.ckpt'.format(args.model, args.env, exp_id)
if args.log:
    log_path = 'logs/log_{}_{}_{}.log'.format(args.model, args.env, exp_id)
    logger = utils.get_logger(logpath=log_path,
                              filepath=os.path.abspath(__file__))
else:
    logger = None
utils.logout(
    logger, 'Experiment: {}, Model: {}, Environment: {}, Seed: {}'.format(
        exp_id, args.model, repr(simulator), args.seed))
utils.logout(
    logger,
    'gamma: {}, latent_dim: {}, lr: {}, batch_size: {}, eps_decay: {}, max steps: {}, latent_policy: {}, '
    'obs_normal: {}'.format(args.gamma, args.latent_dim, args.lr,
                            args.batch_size, args.eps_decay, args.max_steps,
                            args.latent_policy, args.obs_normal))
utils.logout(logger, 'CUDA is available: {}'.format(torch.cuda.is_available()))
utils.logout(logger, '*' * 50)

oderl = MBRL(simulator,
             gamma=args.gamma,
             mem_size=args.mem_size,
             latent_dim=args.latent_dim,
             batch_size=args.batch_size,
def test_recoverable_json(app, client, get_message):
    recorded_resets = []
    recorded_instructions_sent = []

    @password_reset.connect_via(app)
    def on_password_reset(app, user):
        recorded_resets.append(user)

    @reset_password_instructions_sent.connect_via(app)
    def on_instructions_sent(app, user, token):
        recorded_instructions_sent.append(user)

    with capture_flashes() as flashes:
        # Test reset password creates a token and sends email
        with capture_reset_password_requests() as requests:
            with app.mail.record_messages() as outbox:
                response = client.post(
                    "/reset",
                    json=dict(email="*****@*****.**"),
                    headers={"Content-Type": "application/json"},
                )
                assert response.headers["Content-Type"] == "application/json"

        assert len(recorded_instructions_sent) == 1
        assert len(outbox) == 1
        assert response.status_code == 200
        token = requests[0]["token"]

        # Test invalid email
        response = client.post(
            "/reset",
            json=dict(email="*****@*****.**"),
            headers={"Content-Type": "application/json"},
        )
        assert response.status_code == 400
        assert response.json["response"]["errors"]["email"][0].encode(
            "utf-8") == get_message("USER_DOES_NOT_EXIST")

        # Test submitting a new password but leave out 'confirm'
        response = client.post(
            "/reset/" + token,
            data='{"password": "******"}',
            headers={"Content-Type": "application/json"},
        )
        assert response.status_code == 400
        assert response.json["response"]["errors"]["password_confirm"][
            0].encode("utf-8") == get_message("PASSWORD_NOT_PROVIDED")

        # Test submitting a new password
        response = client.post(
            "/reset/" + token + "?include_auth_token",
            json=dict(password="******",
                      password_confirm="awesome sunset"),
            headers={"Content-Type": "application/json"},
        )
        assert all(k in response.json["response"]["user"]
                   for k in ["id", "authentication_token"])
        assert len(recorded_resets) == 1

        # reset automatically logs user in
        logout(client)

        # Test logging in with the new password
        response = client.post(
            "/login?include_auth_token",
            json=dict(email="*****@*****.**", password="******"),
            headers={"Content-Type": "application/json"},
        )
        assert all(k in response.json["response"]["user"]
                   for k in ["id", "authentication_token"])

        logout(client)

        # Use token again - should fail since already have set new password.
        response = client.post(
            "/reset/" + token,
            json=dict(password="******", password_confirm="newpassword"),
            headers={"Content-Type": "application/json"},
        )
        assert response.status_code == 400
        assert len(recorded_resets) == 1

        # Test invalid token
        response = client.post(
            "/reset/bogus",
            json=dict(password="******", password_confirm="newpassword"),
            headers={"Content-Type": "application/json"},
        )
        assert response.json["response"]["error"].encode(
            "utf-8") == get_message("INVALID_RESET_PASSWORD_TOKEN")
    assert len(flashes) == 0
Beispiel #36
0
def test_context_processors(client, app):
    @app.security.context_processor
    def default_ctx_processor():
        return {"global": "global"}

    @app.security.forgot_password_context_processor
    def forgot_password():
        return {"foo": "bar"}

    response = client.get("/reset")
    assert b"global" in response.data
    assert b"bar" in response.data

    @app.security.login_context_processor
    def login():
        return {"foo": "bar"}

    response = client.get("/login")
    assert b"global" in response.data
    assert b"bar" in response.data

    @app.security.verify_context_processor
    def verify():
        return {"foo": "bar"}

    authenticate(client)
    response = client.get("/verify")
    assert b"CUSTOM VERIFY USER" in response.data
    assert b"global" in response.data
    assert b"bar" in response.data
    logout(client)

    @app.security.register_context_processor
    def register():
        return {"foo": "bar"}

    response = client.get("/register")
    assert b"global" in response.data
    assert b"bar" in response.data

    @app.security.reset_password_context_processor
    def reset_password():
        return {"foo": "bar"}

    response = client.get("/reset")
    assert b"global" in response.data
    assert b"bar" in response.data

    @app.security.change_password_context_processor
    def change_password():
        return {"foo": "bar"}

    authenticate(client)
    response = client.get("/change")
    assert b"global" in response.data
    assert b"bar" in response.data

    @app.security.send_confirmation_context_processor
    def send_confirmation():
        return {"foo": "bar"}

    response = client.get("/confirm")
    assert b"global" in response.data
    assert b"bar" in response.data

    @app.security.mail_context_processor
    def mail():
        return {"foo": "bar"}

    client.get("/logout")

    with app.mail.record_messages() as outbox:
        client.post("/reset", data=dict(email="*****@*****.**"))

    email = outbox[0]
    assert "global" in email.html
    assert "bar" in email.html
Beispiel #37
0
def logout():
    return utils.logout()
def test_trackable_flag(app, client, get_message):
    recorded = []

    @login_instructions_sent.connect_via(app)
    def on_instructions_sent(app, user, login_token):
        recorded.append(user)

    # Test disabled account
    response = client.post('/login',
                           data=dict(email='*****@*****.**'),
                           follow_redirects=True)
    assert get_message('DISABLED_ACCOUNT') in response.data

    # Test login with json and valid email
    data = '{"email": "*****@*****.**", "password": "******"}'
    response = client.post('/login',
                           data=data,
                           headers={'Content-Type': 'application/json'})
    assert response.status_code == 200
    assert len(recorded) == 1

    # Test login with json and invalid email
    data = '{"email": "*****@*****.**", "password": "******"}'
    response = client.post('/login',
                           data=data,
                           headers={'Content-Type': 'application/json'})
    assert b'errors' in response.data

    # Test sends email and shows appropriate response
    with capture_passwordless_login_requests() as requests:
        with app.mail.record_messages() as outbox:
            response = client.post('/login',
                                   data=dict(email='*****@*****.**'),
                                   follow_redirects=True)

    assert len(recorded) == 2
    assert len(requests) == 1
    assert len(outbox) == 1
    assert 'user' in requests[0]
    assert 'login_token' in requests[0]

    user = requests[0]['user']
    assert get_message('LOGIN_EMAIL_SENT', email=user.email) in response.data

    token = requests[0]['login_token']
    response = client.get('/login/' + token, follow_redirects=True)
    assert get_message('PASSWORDLESS_LOGIN_SUCCESSFUL') in response.data

    # Test already authenticated
    response = client.get('/login/' + token, follow_redirects=True)
    assert get_message('PASSWORDLESS_LOGIN_SUCCESSFUL') not in response.data

    logout(client)

    # Test invalid token
    response = client.get('/login/bogus', follow_redirects=True)
    assert get_message('INVALID_LOGIN_TOKEN') in response.data

    # Test login request with invalid email
    response = client.post('/login', data=dict(email='*****@*****.**'))
    assert get_message('USER_DOES_NOT_EXIST') in response.data
Beispiel #39
0
def test_recoverable_flag(app, client, get_message):
    recorded_resets = []
    recorded_instructions_sent = []

    @password_reset.connect_via(app)
    def on_password_reset(app, user):
        recorded_resets.append(user)

    @reset_password_instructions_sent.connect_via(app)
    def on_instructions_sent(app, user, token):
        recorded_instructions_sent.append(user)

    # Test the reset view
    response = client.get('/reset')
    assert b'<h1>Send password reset instructions</h1>' in response.data

    # Test submitting email to reset password creates a token and sends email
    with capture_reset_password_requests() as requests:
        with app.mail.record_messages() as outbox:
            response = client.post('/reset',
                                   data=dict(email='*****@*****.**'),
                                   follow_redirects=True)

    assert len(recorded_instructions_sent) == 1
    assert len(outbox) == 1
    assert response.status_code == 200
    assert get_message('PASSWORD_RESET_REQUEST',
                       email='*****@*****.**') in response.data
    token = requests[0]['token']

    # Test view for reset token
    response = client.get('/reset/' + token)
    assert b'<h1>Reset password</h1>' in response.data

    # Test submitting a new password
    response = client.post('/reset/' + token,
                           data={
                               'password': '******',
                               'password_confirm': 'newpassword'
                           },
                           follow_redirects=True)

    assert get_message('PASSWORD_RESET') in response.data
    assert len(recorded_resets) == 1

    logout(client)

    # Test logging in with the new password
    response = authenticate(client,
                            '*****@*****.**',
                            'newpassword',
                            follow_redirects=True)
    assert b'Hello [email protected]' in response.data

    logout(client)

    # Test submitting JSON
    response = client.post('/reset',
                           data='{"email": "*****@*****.**"}',
                           headers={'Content-Type': 'application/json'})
    assert response.headers['Content-Type'] == 'application/json'
    assert 'user' not in response.jdata['response']

    logout(client)

    # Test invalid email
    response = client.post('/reset',
                           data=dict(email='*****@*****.**'),
                           follow_redirects=True)
    assert get_message('USER_DOES_NOT_EXIST') in response.data

    logout(client)

    # Test invalid token
    response = client.post('/reset/bogus',
                           data={
                               'password': '******',
                               'password_confirm': 'newpassword'
                           },
                           follow_redirects=True)
    assert get_message('INVALID_RESET_PASSWORD_TOKEN') in response.data

    # Test mangled token
    token = (
        "WyIxNjQ2MzYiLCIxMzQ1YzBlZmVhM2VhZjYwODgwMDhhZGU2YzU0MzZjMiJd.BZEw_Q.lQyo3npdPZtcJ"
        "_sNHVHP103syjM&url_id=fbb89a8328e58c181ea7d064c2987874bc54a23d")
    response = client.post('/reset/' + token,
                           data={
                               'password': '******',
                               'password_confirm': 'newpassword'
                           },
                           follow_redirects=True)
    assert get_message('INVALID_RESET_PASSWORD_TOKEN') in response.data
Beispiel #40
0
    global THOR
    try:
        THOR = ai2thor.controller.Controller(scene="FloorPlan30")
        logout("AI2Thor about to start.", "s")
        logout("AI2Thor started.", "s")
    except Exception as e:
        logout("Not able to launch AI2Thor. See below...", "f")
        logout(e, "f")
        exit()


def shutdown_thor():
    global THOR
    THOR.stop()


if __name__ == '__main__':
    setup_thor()
    thor_dataset = Thor("thor", thor_config)
    thor_dataset.scrape()
    thor_dataset.save()
    # uncomment line below to write to txt files in addition to the pickle file
    #thor_dataset.write()
    shutdown_thor()
    logout(
        "Number of unique triples: " +
        str(len(thor_dataset.get_unique_triples())), "i")
    logout("Number of triples: " + str(len(thor_dataset.get_triples())), "i")
    logout("Number of entities: " + str(len(thor_dataset.get_ents())), "i")
    logout("Number of relations: " + str(len(thor_dataset.get_rels())), "i")
def logout(token: str):
    token_exists = utils.verify_token(token = token)
    if not token_exists:
        raise HTTPException(status_code = 400, detail = 'Token is not available')
    return utils.logout(token)
Beispiel #42
0
def test1(request):
    logout(request)
    return HttpResponse('ok')
Beispiel #43
0
def test_registerable_flag(client, app, get_message):
    recorded = []

    # Test the register view
    response = client.get("/register")
    assert b"<h1>Register</h1>" in response.data

    # Test registering is successful, sends email, and fires signal
    @user_registered.connect_via(app)
    def on_user_registerd(app, user, confirm_token):
        assert isinstance(app, Flask)
        assert isinstance(user, UserMixin)
        assert confirm_token is None
        recorded.append(user)

    data = dict(
        email="*****@*****.**", password="******", password_confirm="password", next=""
    )
    with app.mail.record_messages() as outbox:
        response = client.post("/register", data=data, follow_redirects=True)

    assert len(recorded) == 1
    assert len(outbox) == 1
    assert b"Post Register" in response.data

    logout(client)

    # Test user can login after registering
    response = authenticate(client, email="*****@*****.**", password="******")
    assert response.status_code == 302

    logout(client)

    # Test registering with an existing email
    data = dict(
        email="*****@*****.**", password="******", password_confirm="password", next=""
    )
    response = client.post("/register", data=data, follow_redirects=True)
    assert get_message("EMAIL_ALREADY_ASSOCIATED", email="*****@*****.**") in response.data

    # Test registering with an existing email but case insensitive
    data = dict(
        email="*****@*****.**", password="******", password_confirm="password", next=""
    )
    response = client.post("/register", data=data, follow_redirects=True)
    assert get_message("EMAIL_ALREADY_ASSOCIATED", email="*****@*****.**") in response.data

    # Test registering with JSON
    data = '{ "email": "*****@*****.**", "password": "******"}'
    response = client.post(
        "/register", data=data, headers={"Content-Type": "application/json"}
    )
    assert response.headers["content-type"] == "application/json"
    assert response.jdata["meta"]["code"] == 200

    logout(client)

    # Test registering with invalid JSON
    data = '{ "email": "bogus", "password": "******"}'
    response = client.post(
        "/register", data=data, headers={"Content-Type": "application/json"}
    )
    assert response.headers["content-type"] == "application/json"
    assert response.jdata["meta"]["code"] == 400

    logout(client)

    # Test ?next param
    data = dict(
        email="*****@*****.**", password="******", password_confirm="password", next=""
    )

    response = client.post("/register?next=/page1", data=data, follow_redirects=True)
    assert b"Page 1" in response.data
Beispiel #44
0
    def mbmf_rollout(self,
                     mode,
                     env_steps,
                     max_steps,
                     total_episodes,
                     total_env_steps,
                     cur_epoch,
                     store_trans=True,
                     store_traj=False,
                     planning_horizon=None,
                     val_ratio=0):
        t = time.time()
        cur_steps = 0
        rewards, steps = [], []
        utils.logout(self.logger,
                     '*' * 10 + ' {} rollout '.format(mode.upper()) + '*' * 10)
        while cur_steps < env_steps:
            actual_steps = min(max_steps, env_steps - cur_steps)
            if 'mb' in mode:
                reward, step = self.mpc_planning(
                    actual_steps,
                    store_trans=store_trans,
                    store_traj=store_traj,
                    val_ratio=val_ratio,
                    cut_length=planning_horizon,
                    rand=False,
                    planning_horizon=planning_horizon,
                    combine_mf=bool(mode == 'mbmf'))
            elif mode == 'mf':
                reward, step = self.run_policy(actual_steps,
                                               store_trans=store_trans,
                                               store_traj=store_traj,
                                               optimize_mf=True,
                                               val_ratio=val_ratio,
                                               cut_length=planning_horizon)
            elif mode == 'random':
                reward, step = self.run_policy(actual_steps,
                                               store_trans=store_trans,
                                               store_traj=store_traj,
                                               optimize_mf=False,
                                               eps=1,
                                               val_ratio=val_ratio,
                                               cut_length=planning_horizon)
            else:
                raise ValueError('only MBMF, MB, MF or Random.')
            cur_steps += step
            total_env_steps += step
            total_episodes += 1
            rewards.append(reward)
            steps.append(total_env_steps)
            log = "Episode {} | total env steps = {} | env steps = {} | reward = {:.6f}".format(
                total_episodes, total_env_steps, step, reward)
            utils.logout(self.logger, log)

        utils.logout(self.logger, '*' * 10 + ' Policy evaluation ' + '*' * 10)
        eval_reward = 0
        for _ in range(5):
            eval_reward += self.run_policy(max_steps=max_steps,
                                           store_trans=False,
                                           store_traj=False,
                                           optimize_mf=False)[0]
        log = "{} Epoch {} | total env steps = {} | avg reward over last epoch = {:.6f} | eval reward = {:.6f}" \
              " | time = {:.6f} s".format(mode.upper(), cur_epoch, total_env_steps, sum(rewards) / len(rewards),
                                          eval_reward / 5, time.time() - t)
        utils.logout(self.logger, log)

        return rewards, steps, total_episodes, total_env_steps, eval_reward
def test_recoverable_flag(app, client, get_message):
    recorded_resets = []
    recorded_instructions_sent = []

    @password_reset.connect_via(app)
    def on_password_reset(app, user):
        recorded_resets.append(user)

    @reset_password_instructions_sent.connect_via(app)
    def on_instructions_sent(app, user, token):
        assert isinstance(app, Flask)
        assert isinstance(user, UserMixin)
        assert isinstance(token, string_types)
        recorded_instructions_sent.append(user)

    # Test the reset view
    response = client.get("/reset")
    assert b"<h1>Send password reset instructions</h1>" in response.data

    # Test submitting email to reset password creates a token and sends email
    with capture_reset_password_requests() as requests:
        with app.mail.record_messages() as outbox:
            response = client.post("/reset",
                                   data=dict(email="*****@*****.**"),
                                   follow_redirects=True)

    assert len(recorded_instructions_sent) == 1
    assert len(outbox) == 1
    assert response.status_code == 200
    assert get_message("PASSWORD_RESET_REQUEST",
                       email="*****@*****.**") in response.data
    token = requests[0]["token"]

    # Test view for reset token
    response = client.get("/reset/" + token)
    assert b"<h1>Reset password</h1>" in response.data

    # Test submitting a new password but leave out confirm
    response = client.post("/reset/" + token,
                           data={"password": "******"},
                           follow_redirects=True)
    assert get_message("PASSWORD_NOT_PROVIDED") in response.data
    assert len(recorded_resets) == 0

    # Test submitting a new password
    response = client.post(
        "/reset/" + token,
        data={
            "password": "******",
            "password_confirm": "awesome sunset"
        },
        follow_redirects=True,
    )

    assert get_message("PASSWORD_RESET") in response.data
    assert len(recorded_resets) == 1

    logout(client)

    # Test logging in with the new password
    response = authenticate(client,
                            "*****@*****.**",
                            "awesome sunset",
                            follow_redirects=True)
    assert b"Welcome [email protected]" in response.data

    logout(client)

    # Test invalid email
    response = client.post("/reset",
                           data=dict(email="*****@*****.**"),
                           follow_redirects=True)
    assert get_message("USER_DOES_NOT_EXIST") in response.data

    logout(client)

    # Test invalid token
    response = client.post(
        "/reset/bogus",
        data={
            "password": "******",
            "password_confirm": "awesome sunset"
        },
        follow_redirects=True,
    )
    assert get_message("INVALID_RESET_PASSWORD_TOKEN") in response.data

    # Test mangled token
    token = ("WyIxNjQ2MzYiLCIxMzQ1YzBlZmVhM2VhZjYwODgwMDhhZGU2YzU0MzZjMiJd."
             "BZEw_Q.lQyo3npdPZtcJ_sNHVHP103syjM"
             "&url_id=fbb89a8328e58c181ea7d064c2987874bc54a23d")
    response = client.post(
        "/reset/" + token,
        data={
            "password": "******",
            "password_confirm": "newpassword"
        },
        follow_redirects=True,
    )
    assert get_message("INVALID_RESET_PASSWORD_TOKEN") in response.data
def test_opt_in(app, client):
    """
    Test entire lifecycle of user not having 2FA - setting it up, then deciding
    to turn it back off
    All using forms based API
    """

    signalled_identity = []

    @identity_changed.connect_via(app)
    def on_identity_changed(app, identity):
        signalled_identity.append(identity.id)

    response = authenticate(client, "*****@*****.**")
    session = get_session(response)
    assert "tf_state" not in session
    # Jill is 4th user to be added in utils.py
    assert signalled_identity[0] == 4
    del signalled_identity[:]

    # opt-in for SMS 2FA - but we haven't re-verified password
    sms_sender = SmsSenderFactory.createSender("test")
    data = dict(setup="sms", phone="+442083661177")
    response = client.post("/tf-setup", data=data, follow_redirects=True)
    message = b"You currently do not have permissions to access this page"
    assert message in response.data

    # Confirm password - then opt-in
    password = "******"
    response = client.post(
        "/tf-confirm", data=dict(password=password), follow_redirects=True
    )
    data = dict(setup="sms", phone="+442083661177")
    response = client.post("/tf-setup", data=data, follow_redirects=True)
    assert b"To Which Phone Number Should We Send Code To" in response.data
    assert sms_sender.get_count() == 1
    code = sms_sender.messages[0].split()[-1]

    # Validate token - this should complete 2FA setup
    response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True)
    assert b"You successfully changed" in response.data

    # Upon completion, session cookie shouldnt have any two factor stuff in it.
    session = get_session(response)
    assert not tf_in_session(session)

    # Log out
    logout(client)
    assert not signalled_identity[0]
    del signalled_identity[:]

    # Login now should require 2FA with sms
    sms_sender = SmsSenderFactory.createSender("test")
    response = authenticate(client, "*****@*****.**")
    session = get_session(response)
    assert session["tf_state"] == "ready"
    assert len(signalled_identity) == 0

    assert sms_sender.get_count() == 1
    code = sms_sender.messages[0].split()[-1]
    response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True)
    assert b"Your token has been confirmed" in response.data
    # Verify now logged in
    assert signalled_identity[0] == 4
    del signalled_identity[:]

    # Now opt back out.
    # as before must reconfirm password first
    response = client.get("/tf-setup", data=data, follow_redirects=True)
    message = b"You currently do not have permissions to access this page"
    assert message in response.data

    password = "******"
    client.post("/tf-confirm", data=dict(password=password), follow_redirects=True)
    data = dict(setup="disable")
    response = client.post("/tf-setup", data=data, follow_redirects=True)
    assert b"You successfully disabled two factor authorization." in response.data

    # Log out
    logout(client)
    assert not signalled_identity[0]
    del signalled_identity[:]

    # Should be able to log in with just user/pass
    response = authenticate(client, "*****@*****.**")
    session = get_session(response)
    assert "tf_state" not in session
    # Jill is 4th user to be added in utils.py
    assert signalled_identity[0] == 4
def test_registerable_flag(client, app, get_message):
    recorded = []

    # Test the register view
    response = client.get('/register')
    assert b"<h1>Register</h1>" in response.data

    # Test registering is successful, sends email, and fires signal
    @user_registered.connect_via(app)
    def on_user_registerd(app, user, confirm_token):
        recorded.append(user)

    data = dict(email='*****@*****.**',
                password='******',
                password_confirm='password')
    with app.mail.record_messages() as outbox:
        response = client.post('/register', data=data, follow_redirects=True)

    assert len(recorded) == 1
    assert len(outbox) == 1
    assert b'Post Register' in response.data

    logout(client)

    # Test user can login after registering
    response = authenticate(client, email='*****@*****.**', password='******')
    assert response.status_code == 302

    logout(client)

    # Test registering with an existing email
    data = dict(email='*****@*****.**',
                password='******',
                password_confirm='password')
    response = client.post('/register', data=data, follow_redirects=True)
    assert get_message('EMAIL_ALREADY_ASSOCIATED',
                       email='*****@*****.**') in response.data

    # Test registering with JSON
    data = '{ "email": "*****@*****.**", "password": "******"}'
    response = client.post('/register',
                           data=data,
                           headers={'Content-Type': 'application/json'})
    assert response.headers['content-type'] == 'application/json'
    assert response.jdata['meta']['code'] == 200

    logout(client)

    # Test registering with invalid JSON
    data = '{ "email": "bogus", "password": "******"}'
    response = client.post('/register',
                           data=data,
                           headers={'Content-Type': 'application/json'})
    assert response.headers['content-type'] == 'application/json'
    assert response.jdata['meta']['code'] == 400

    logout(client)

    # Test ?next param
    data = dict(email='*****@*****.**',
                password='******',
                password_confirm='password')

    response = client.post('/register?next=/page1',
                           data=data,
                           follow_redirects=True)
    assert b'Page 1' in response.data
def test_totp_secret_generation(app, client):
    """
    Test the totp secret generation upon changing method to make sure
    it stays the same after the process is completed
    """

    # Properly log in jill for this test
    signalled_identity = []

    @identity_changed.connect_via(app)
    def on_identity_changed(app, identity):
        signalled_identity.append(identity.id)

    response = authenticate(client, "*****@*****.**")
    session = get_session(response)
    assert "tf_state" not in session
    # Jill is 4th user to be added in utils.py
    assert signalled_identity[0] == 4
    del signalled_identity[:]

    # Confirm password
    sms_sender = SmsSenderFactory.createSender("test")
    password = "******"
    response = client.post(
        "/tf-confirm", data=dict(password=password), follow_redirects=True
    )
    # Select sms method but do not send a phone number just yet (regenerates secret)
    data = dict(setup="sms")
    response = client.post("/tf-setup", data=data, follow_redirects=True)
    assert b"To Which Phone Number Should We Send Code To" in response.data

    # Retrieve the currently generated totp secret for later comparison
    session = get_session(response)
    if "tf_totp_secret" in session:
        generated_secret = session["tf_totp_secret"]
    else:
        with app.app_context():
            user = app.security.datastore.find_user(email="*****@*****.**")
            generated_secret = user.tf_totp_secret
    assert "enckey" in generated_secret

    # Send a new phone number in the second step, method remains unchanged
    data = dict(setup="sms", phone="+442083661188")
    response = client.post("/tf-setup", data=data, follow_redirects=True)
    assert sms_sender.get_count() == 1
    code = sms_sender.messages[0].split()[-1]

    # Validate token - this should complete 2FA setup
    response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True)
    assert b"You successfully changed" in response.data

    # Retrieve the final totp secret and make sure it matches the previous one
    with app.app_context():
        user = app.security.datastore.find_user(email="*****@*****.**")
        assert generated_secret == user.tf_totp_secret

    # Finally opt back out and check that tf_totp_secret is None
    response = client.get("/tf-setup", data=data, follow_redirects=True)
    message = b"You currently do not have permissions to access this page"
    assert message in response.data

    password = "******"
    client.post("/tf-confirm", data=dict(password=password), follow_redirects=True)
    data = dict(setup="disable")
    response = client.post("/tf-setup", data=data, follow_redirects=True)
    assert b"You successfully disabled two factor authorization." in response.data
    with app.app_context():
        user = app.security.datastore.find_user(email="*****@*****.**")
        assert user.tf_totp_secret is None

    # Log out
    logout(client)
    assert not signalled_identity[0]
    del signalled_identity[:]
Beispiel #49
0
def test_logout(client):
    authenticate(client)
    response = logout(client, follow_redirects=True)
    assert b"Home Page" in response.data
def test_two_factor_flag(app, client):
    # trying to verify code without going through two-factor
    # first login function
    wrong_code = b"000000"
    response = client.post(
        "/tf-validate", data=dict(code=wrong_code), follow_redirects=True
    )

    message = b"You currently do not have permissions to access this page"
    assert message in response.data

    # Test login using invalid email
    data = dict(email="*****@*****.**", password="******")
    response = client.post("/login", data=data, follow_redirects=True)
    assert b"Specified user does not exist" in response.data
    response = client.post(
        "/login",
        json=data,
        headers={"Content-Type": "application/json"},
        follow_redirects=True,
    )
    assert b"Specified user does not exist" in response.data

    # Test login using valid email and invalid password
    data = dict(email="*****@*****.**", password="******")
    response = client.post("/login", data=data, follow_redirects=True)
    assert b"Invalid password" in response.data
    response = client.post(
        "/login",
        json=data,
        headers={"Content-Type": "application/json"},
        follow_redirects=True,
    )
    assert b"Invalid password" in response.data

    # Test two-factor authentication first login
    data = dict(email="*****@*****.**", password="******")
    response = client.post("/login", data=data, follow_redirects=True)
    message = b"Two-factor authentication adds an extra layer of security"
    assert message in response.data
    response = client.post(
        "/tf-setup", data=dict(setup="not_a_method"), follow_redirects=True
    )
    assert b"Marked method is not valid" in response.data
    session = get_session(response)
    assert session["tf_state"] == "setup_from_login"

    # try non-existing setup on setup page (using json)
    data = dict(setup="not_a_method")
    response = client.post(
        "/tf-setup",
        json=data,
        headers={"Content-Type": "application/json"},
        follow_redirects=True,
    )
    assert response.status_code == 400
    assert (
        response.json["response"]["errors"]["setup"][0] == "Marked method is not valid"
    )

    data = dict(setup="email")
    response = client.post(
        "/tf-setup",
        json=data,
        headers={"Content-Type": "application/json"},
        follow_redirects=True,
    )

    # Test for sms in process of valid login
    sms_sender = SmsSenderFactory.createSender("test")
    data = dict(email="*****@*****.**", password="******")
    response = client.post(
        "/login",
        json=data,
        headers={"Content-Type": "application/json"},
        follow_redirects=True,
    )
    assert b'"code": 200' in response.data
    assert sms_sender.get_count() == 1
    session = get_session(response)
    assert session["tf_state"] == "ready"

    code = sms_sender.messages[0].split()[-1]
    # submit bad token to two_factor_token_validation
    response = client.post("/tf-validate", data=dict(code=wrong_code))
    assert b"Invalid Token" in response.data

    # sumbit right token and show appropriate response
    response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True)
    assert b"Your token has been confirmed" in response.data

    # Upon completion, session cookie shouldnt have any two factor stuff in it.
    assert not tf_in_session(get_session(response))

    # try confirming password with a wrong one
    response = client.post("/tf-confirm", data=dict(password=""), follow_redirects=True)
    assert b"Password not provided" in response.data

    # try confirming password with a wrong one + json
    data = dict(password="******")
    response = client.post(
        "/tf-confirm",
        json=data,
        headers={"Content-Type": "application/json"},
        follow_redirects=True,
    )

    assert response.json["meta"]["code"] == 400

    # Test change two_factor password confirmation view to mail
    password = "******"
    response = client.post(
        "/tf-confirm", data=dict(password=password), follow_redirects=True
    )

    assert b"You successfully confirmed password" in response.data
    message = b"Two-factor authentication adds an extra layer of security"
    assert message in response.data

    # change method (from sms to mail)
    setup_data = dict(setup="email")
    testMail = TestMail()
    app.extensions["mail"] = testMail
    response = client.post("/tf-setup", data=setup_data, follow_redirects=True)
    msg = b"To complete logging in, please enter the code sent to your mail"
    assert msg in response.data

    # Fetch token validate form
    response = client.get("/tf-validate")
    assert response.status_code == 200
    assert b'name="code"' in response.data

    code = testMail.msg.body.split()[-1]
    # sumbit right token and show appropriate response
    response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True)
    assert b"You successfully changed your two-factor method" in response.data

    # Test change two_factor password confirmation view to google authenticator
    password = "******"
    response = client.post(
        "/tf-confirm", data=dict(password=password), follow_redirects=True
    )
    assert b"You successfully confirmed password" in response.data
    message = b"Two-factor authentication adds an extra layer of security"
    assert message in response.data

    # Setup authenticator
    setup_data = dict(setup="authenticator")
    response = client.post("/tf-setup", data=setup_data, follow_redirects=True)
    assert b"Open your authenticator app on your device" in response.data

    # Now request code. We can't test the qrcode easily - but we can get the totp_secret
    # that goes into the qrcode and make sure that works
    mtf = Mock(wraps=app.security._totp_factory)
    app.security.totp_factory(mtf)
    qrcode_page_response = client.get(
        "/tf-qrcode", data=setup_data, follow_redirects=True
    )
    assert mtf.get_totp_uri.call_count == 1
    (username, totp_secret), _ = mtf.get_totp_uri.call_args
    assert username == "*****@*****.**"
    assert b"svg" in qrcode_page_response.data

    # Generate token from passed totp_secret and confirm setup
    code = app.security._totp_factory.generate_totp_password(totp_secret)
    response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True)
    assert b"You successfully changed your two-factor method" in response.data

    logout(client)

    # Test login with remember_token
    assert "remember_token" not in [c.name for c in client.cookie_jar]
    data = dict(email="*****@*****.**", password="******", remember=True)
    response = client.post(
        "/login",
        json=data,
        headers={"Content-Type": "application/json"},
        follow_redirects=True,
    )

    # Generate token from passed totp_secret
    code = app.security._totp_factory.generate_totp_password(totp_secret)
    response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True)
    assert b"Your token has been confirmed" in response.data

    # Verify that the remember token is properly set
    found = False
    for cookie in client.cookie_jar:
        if cookie.name == "remember_token":
            found = True
            assert cookie.path == "/"
    assert found

    response = logout(client)
    # Verify that logout clears session info
    assert not tf_in_session(get_session(response))

    # Test two-factor authentication first login
    data = dict(email="*****@*****.**", password="******")
    response = client.post("/login", data=data, follow_redirects=True)
    message = b"Two-factor authentication adds an extra layer of security"
    assert message in response.data

    # check availability of qrcode page when this option is not picked
    qrcode_page_response = client.get("/two_factor_qrcode/", follow_redirects=False)
    assert qrcode_page_response.status_code == 404

    # check availability of qrcode page when this option is picked
    setup_data = dict(setup="authenticator")
    response = client.post("/tf-setup", data=setup_data, follow_redirects=True)
    assert b"Open your authenticator app on your device" in response.data

    qrcode_page_response = client.get(
        "/tf-qrcode", data=setup_data, follow_redirects=True
    )
    print(qrcode_page_response)
    assert b"svg" in qrcode_page_response.data

    # check appearence of setup page when sms picked and phone number entered
    sms_sender = SmsSenderFactory.createSender("test")
    data = dict(setup="sms", phone="+442083661177")
    response = client.post("/tf-setup", data=data, follow_redirects=True)
    assert b"To Which Phone Number Should We Send Code To" in response.data
    assert sms_sender.get_count() == 1
    code = sms_sender.messages[0].split()[-1]

    response = client.post("/tf-validate", data=dict(code=code), follow_redirects=True)
    assert b"Your token has been confirmed" in response.data
    assert not tf_in_session(get_session(response))

    logout(client)

    # check when two_factor_rescue function should not appear
    rescue_data_json = dict(help_setup="lost_device")
    response = client.post(
        "/tf-rescue",
        json=rescue_data_json,
        headers={"Content-Type": "application/json"},
    )
    assert b'"code": 400' in response.data

    # check when two_factor_rescue function should appear
    data = dict(email="*****@*****.**", password="******")
    response = client.post("/login", data=data, follow_redirects=True)
    assert b"Please enter your authentication code" in response.data
    rescue_data = dict(help_setup="lost_device")
    response = client.post("/tf-rescue", data=rescue_data, follow_redirects=True)
    message = b"The code for authentication was sent to your email address"
    assert message in response.data
    rescue_data = dict(help_setup="no_mail_access")
    response = client.post("/tf-rescue", data=rescue_data, follow_redirects=True)
    message = b"A mail was sent to us in order" + b" to reset your application account"
    assert message in response.data
def test_confirmable_flag(app, client, sqlalchemy_datastore, get_message):
    recorded_confirms = []
    recorded_instructions_sent = []

    @user_confirmed.connect_via(app)
    def on_confirmed(app, user):
        recorded_confirms.append(user)

    @confirm_instructions_sent.connect_via(app)
    def on_instructions_sent(app, user):
        recorded_instructions_sent.append(user)

    # Test login before confirmation
    email = '*****@*****.**'

    with capture_registrations() as registrations:
        response = client.post('/register',
                               data=dict(email=email, password='******'))

    assert response.status_code == 302

    response = authenticate(client, email=email)
    assert get_message('CONFIRMATION_REQUIRED') in response.data

    # Test invalid token
    response = client.get('/confirm/bogus', follow_redirects=True)
    assert get_message('INVALID_CONFIRMATION_TOKEN') in response.data

    # Test JSON
    response = client.post('/confirm',
                           data='{"email": "*****@*****.**"}',
                           headers={'Content-Type': 'application/json'})
    assert response.status_code == 200
    assert response.headers['Content-Type'] == 'application/json'
    assert 'user' in response.jdata['response']
    assert len(recorded_instructions_sent) == 1

    # Test ask for instructions with invalid email
    response = client.post('/confirm', data=dict(email='*****@*****.**'))
    assert get_message('USER_DOES_NOT_EXIST') in response.data

    # Test resend instructions
    response = client.post('/confirm', data=dict(email=email))
    assert get_message('CONFIRMATION_REQUEST', email=email) in response.data
    assert len(recorded_instructions_sent) == 2

    # Test confirm
    token = registrations[0]['confirm_token']
    response = client.get('/confirm/' + token, follow_redirects=True)
    assert get_message('EMAIL_CONFIRMED') in response.data
    assert len(recorded_confirms) == 1

    # Test already confirmed
    response = client.get('/confirm/' + token, follow_redirects=True)
    assert get_message('ALREADY_CONFIRMED') in response.data

    # Test already confirmed when asking for confirmation instructions
    logout(client)

    response = client.get('/confirm')
    assert response.status_code == 200

    response = client.post('/confirm', data=dict(email=email))
    assert get_message('ALREADY_CONFIRMED') in response.data

    # Test user was deleted before confirmation
    with capture_registrations() as registrations:
        client.post('/register',
                    data=dict(email='*****@*****.**', password='******'))

    user = registrations[0]['user']
    token = registrations[0]['confirm_token']

    with app.app_context():
        sqlalchemy_datastore.delete(user)
        sqlalchemy_datastore.commit()

    response = client.get('/confirm/' + token, follow_redirects=True)
    assert get_message('INVALID_CONFIRMATION_TOKEN') in response.data
def test_confirmable_flag(app, client, sqlalchemy_datastore, get_message):
    recorded_confirms = []
    recorded_instructions_sent = []

    @user_confirmed.connect_via(app)
    def on_confirmed(app, user):
        assert isinstance(app, Flask)
        assert isinstance(user, UserMixin)
        recorded_confirms.append(user)

    @confirm_instructions_sent.connect_via(app)
    def on_instructions_sent(app, user, token):
        assert isinstance(app, Flask)
        assert isinstance(user, UserMixin)
        assert isinstance(token, string_types)
        recorded_instructions_sent.append(user)

    # Test login before confirmation
    email = "*****@*****.**"

    with capture_registrations() as registrations:
        data = dict(email=email, password="******", next="")
        response = client.post("/register", data=data)

    assert response.status_code == 302

    response = authenticate(client, email=email)
    assert get_message("CONFIRMATION_REQUIRED") in response.data

    # Test invalid token
    response = client.get("/confirm/bogus", follow_redirects=True)
    assert get_message("INVALID_CONFIRMATION_TOKEN") in response.data

    # Test JSON
    response = client.post(
        "/confirm",
        data='{"email": "*****@*****.**"}',
        headers={"Content-Type": "application/json"},
    )
    assert response.status_code == 200
    assert response.headers["Content-Type"] == "application/json"
    assert "user" in response.jdata["response"]
    assert len(recorded_instructions_sent) == 1

    # Test ask for instructions with invalid email
    response = client.post("/confirm", data=dict(email="*****@*****.**"))
    assert get_message("USER_DOES_NOT_EXIST") in response.data

    # Test resend instructions
    response = client.post("/confirm", data=dict(email=email))
    assert get_message("CONFIRMATION_REQUEST", email=email) in response.data
    assert len(recorded_instructions_sent) == 2

    # Test confirm
    token = registrations[0]["confirm_token"]
    response = client.get("/confirm/" + token, follow_redirects=True)
    assert get_message("EMAIL_CONFIRMED") in response.data
    assert len(recorded_confirms) == 1

    # Test already confirmed
    response = client.get("/confirm/" + token, follow_redirects=True)
    assert get_message("ALREADY_CONFIRMED") in response.data
    assert len(recorded_instructions_sent) == 2

    # Test already confirmed and expired token
    app.config["SECURITY_CONFIRM_EMAIL_WITHIN"] = "-1 days"
    with app.app_context():
        user = registrations[0]["user"]
        expired_token = generate_confirmation_token(user)
    response = client.get("/confirm/" + expired_token, follow_redirects=True)
    assert get_message("ALREADY_CONFIRMED") in response.data
    assert len(recorded_instructions_sent) == 2

    # Test already confirmed when asking for confirmation instructions
    logout(client)

    response = client.get("/confirm")
    assert response.status_code == 200

    response = client.post("/confirm", data=dict(email=email))
    assert get_message("ALREADY_CONFIRMED") in response.data

    # Test user was deleted before confirmation
    with capture_registrations() as registrations:
        data = dict(email="*****@*****.**", password="******", next="")
        client.post("/register", data=data)

    user = registrations[0]["user"]
    token = registrations[0]["confirm_token"]

    with app.app_context():
        sqlalchemy_datastore.delete(user)
        sqlalchemy_datastore.commit()

    response = client.get("/confirm/" + token, follow_redirects=True)
    assert get_message("INVALID_CONFIRMATION_TOKEN") in response.data
def test_simple_login(app, client, get_message):
    auths = []

    @user_authenticated.connect_via(app)
    def authned(myapp, user, **extra_args):
        auths.append((user.email, extra_args["authn_via"]))

    # Test missing choice
    data = dict(identity="*****@*****.**")
    response = client.post("/us-send-code", data=data, follow_redirects=True)
    assert get_message("US_METHOD_NOT_AVAILABLE") in response.data

    # Test login using invalid email
    data = dict(identity="*****@*****.**", chosen_method="email")
    response = client.post("/us-send-code", data=data, follow_redirects=True)
    assert get_message("US_SPECIFY_IDENTITY") in response.data

    # test disabled account
    data = dict(identity="*****@*****.**", chosen_method="email")
    response = client.post("/us-send-code", data=data, follow_redirects=True)
    assert b"Code has been sent" not in response.data
    assert get_message("DISABLED_ACCOUNT") in response.data

    with capture_send_code_requests() as requests:
        with app.mail.record_messages() as outbox:
            response = client.post(
                "/us-send-code",
                data=dict(identity="*****@*****.**", chosen_method="email"),
                follow_redirects=True,
            )
            assert response.status_code == 200
            assert b"Sign In" in response.data
    assert len(requests) == 1
    assert len(outbox) == 1

    # try bad code
    response = client.post(
        "/us-signin",
        data=dict(identity="*****@*****.**", passcode="blahblah"),
        follow_redirects=True,
    )
    assert get_message("INVALID_PASSWORD") in response.data

    # Correct code
    assert "remember_token" not in [c.name for c in client.cookie_jar]
    assert "session" not in [c.name for c in client.cookie_jar]
    response = client.post(
        "/us-signin",
        data=dict(identity="*****@*****.**", passcode=requests[0]["token"]),
        follow_redirects=False,
    )
    assert "remember_token" not in [c.name for c in client.cookie_jar]
    assert "email" in auths[0][1]

    response = client.get("/profile", follow_redirects=False)
    assert response.status_code == 200

    logout(client)
    response = client.get("/profile", follow_redirects=False)
    assert "/login?next=%2Fprofile" in response.location

    # login via SMS
    sms_sender = SmsSenderFactory.createSender("test")
    set_phone(app)
    response = client.post(
        "/us-send-code",
        data=dict(identity="*****@*****.**", chosen_method="sms"),
        follow_redirects=True,
    )
    assert response.status_code == 200
    assert b"Sign In" in response.data

    code = sms_sender.messages[0].split()[-1].strip(".")
    response = client.post(
        "/us-signin",
        data=dict(identity="*****@*****.**", passcode=code, remember=True),
        follow_redirects=True,
    )
    assert response.status_code == 200
    assert "remember_token" in [c.name for c in client.cookie_jar]
    assert "sms" in auths[1][1]

    response = client.get("/profile", follow_redirects=False)
    assert response.status_code == 200

    logout(client)
    assert "remember_token" not in [c.name for c in client.cookie_jar]
Beispiel #54
0
def front_logout(request):
    logout(request)
    return HttpResponse(u'退出成功')
Beispiel #55
0
def test_logout(client):
    authenticate(client)
    response = logout(client, follow_redirects=True)
    assert b'Home Page' in response.data
def test_simple_login_json(app, client_nc, get_message):
    auths = []

    @user_authenticated.connect_via(app)
    def authned(myapp, user, **extra_args):
        auths.append((user.email, extra_args["authn_via"]))

    headers = {
        "Accept": "application/json",
        "Content-Type": "application/json"
    }

    with capture_flashes() as flashes:

        response = client_nc.get("/us-signin", headers=headers)
        assert (response.json["response"]["methods"] ==
                app.config["SECURITY_US_ENABLED_METHODS"])
        assert (response.json["response"]["identity_attributes"] ==
                app.config["SECURITY_USER_IDENTITY_ATTRIBUTES"])

        with capture_send_code_requests() as requests:
            with app.mail.record_messages() as outbox:
                response = client_nc.post(
                    "/us-send-code",
                    json=dict(identity="*****@*****.**", chosen_method="email"),
                    headers=headers,
                    follow_redirects=True,
                )
                assert response.status_code == 200
                assert "csrf_token" in response.json["response"]
                assert "user" not in response.json["response"]
        assert len(requests) == 1
        assert len(outbox) == 1

        # try bad code
        response = client_nc.post(
            "/us-signin",
            json=dict(identity="*****@*****.**", passcode="blahblah"),
            headers=headers,
            follow_redirects=True,
        )
        assert response.status_code == 400
        assert response.json["response"]["errors"]["passcode"][0].encode(
            "utf-8") == get_message("INVALID_PASSWORD")

        # Login successfully with code
        response = client_nc.post(
            "/us-signin?include_auth_token",
            json=dict(identity="*****@*****.**", passcode=requests[0]["token"]),
            headers=headers,
            follow_redirects=True,
        )
        assert response.status_code == 200
        assert "authentication_token" in response.json["response"]["user"]
        assert "email" in auths[0][1]

        logout(client_nc)
        response = client_nc.get("/profile",
                                 headers=headers,
                                 follow_redirects=False)
        assert response.status_code == 401

        # login via SMS
        sms_sender = SmsSenderFactory.createSender("test")
        set_phone(app)
        response = client_nc.post(
            "/us-send-code",
            json=dict(identity="*****@*****.**", chosen_method="sms"),
            headers=headers,
            follow_redirects=True,
        )
        assert response.status_code == 200

        code = sms_sender.messages[0].split()[-1].strip(".")
        response = client_nc.post(
            "/us-signin?include_auth_token",
            json=dict(identity="*****@*****.**", passcode=code),
            headers=headers,
            follow_redirects=True,
        )
        assert response.status_code == 200
        assert "authentication_token" in response.json["response"]["user"]
    assert len(flashes) == 0