コード例 #1
0
 def test_add_duplicate_username(self):
     add_user('test', '*****@*****.**', 'test')
     duplicate_user = User(username='******',
                           email='*****@*****.**',
                           password='******')
     db.session.add(duplicate_user)
     self.assertRaises(IntegrityError, db.session.commit)
 def test_add_user_inactive(self):
     add_user('test', '*****@*****.**', 'test')
     # update user
     user = User.query.filter_by(email='*****@*****.**').first()
     user.active = False
     db.session.commit()
     with self.client:
         resp_login = self.client.post('/auth/login',
                                       data=json.dumps({
                                           'email': '*****@*****.**',
                                           'password': '******'
                                       }),
                                       content_type='application/json')
         token = json.loads(resp_login.data.decode())['auth_token']
         response = self.client.post(
             '/users',
             data=json.dumps({
                 'username': '******',
                 'email': '*****@*****.**',
                 'password': '******'
             }),
             content_type='application/json',
             headers={'Authorization': f'Bearer {token}'})
         data = json.loads(response.data.decode())
         self.assertTrue(data['status'] == 'fail')
         self.assertTrue(data['message'] == 'Provide a valid auth token.')
         self.assertEqual(response.status_code, 401)
コード例 #3
0
    def test_auth_passwords_token_hash_are_random(self):
        """Ensure password recovery token hashes are random"""
        user = add_user()

        with self.client:
            response = self.client.post(
                f'/{self.version}/auth/password_recovery',
                data=json.dumps(dict(
                    email=user.email
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json')]
            )
            data = json.loads(response.data.decode())
            self.assertEqual(data['message'], 'Password recovery email sent.')
            self.assertEqual(response.status_code, 200)

        user_2 = add_user()

        with self.client:
            response = self.client.post(
                f'/{self.version}/auth/password_recovery',
                data=json.dumps(dict(
                    email=user_2.email
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json')]
            )
            data = json.loads(response.data.decode())
            self.assertEqual(data['message'], 'Password recovery email sent.')
            self.assertEqual(response.status_code, 200)

        self.assertTrue(user.token_hash != user_2.token_hash)
        self.assertTrue(user.token_hash is not None)
        self.assertTrue(user.token_hash != "")
 def test_add_user_not_admin(self):
     add_user('test', '*****@*****.**', 'test')
     with self.client:
         # user login
         resp_login = self.client.post('/auth/login',
                                       data=json.dumps({
                                           'email': '*****@*****.**',
                                           'password': '******'
                                       }),
                                       content_type='application/json')
         token = json.loads(resp_login.data.decode())['auth_token']
         response = self.client.post(
             '/users',
             data=json.dumps({
                 'username': '******',
                 'email': '*****@*****.**',
                 'password': '******'
             }),
             content_type='application/json',
             headers={'Authorization': f'Bearer {token}'})
         data = json.loads(response.data.decode())
         self.assertTrue(data['status'] == 'fail')
         self.assertTrue(
             data['message'] == 'You do not have permission to do that.')
         self.assertEqual(response.status_code, 401)
コード例 #5
0
 def test_add_user_duplicate_user(self):
     """Ensure error is thrown if the email already exists."""
     add_user('test', '*****@*****.**', 'test', roles=UserRole.BACKEND_ADMIN)
     with self.client:
         resp_login = self.client.post(
             '/v1/auth/login',
             data=json.dumps(dict(email='*****@*****.**', password='******')),
             content_type='application/json',
             headers=[('Accept', 'application/json')])
         self.client.post(
             '/v1/users',
             data=json.dumps(
                 dict(username='******',
                      email='*****@*****.**',
                      password='******')),
             content_type='application/json',
             headers=[('Accept', 'application/json'),
                      (Constants.HttpHeaders.AUTHORIZATION, 'Bearer ' +
                       json.loads(resp_login.data.decode())['auth_token'])])
         response = self.client.post(
             '/v1/users',
             data=json.dumps(
                 dict(username='******',
                      email='*****@*****.**',
                      password='******')),
             content_type='application/json',
             headers=[('Accept', 'application/json'),
                      (Constants.HttpHeaders.AUTHORIZATION, 'Bearer ' +
                       json.loads(resp_login.data.decode())['auth_token'])])
         data = json.loads(response.data.decode())
         self.assertEqual(response.status_code, 400)
         self.assertIn('Sorry. That email or username already exists.',
                       data['message'])
         self.assertIn('error', data['status'])
コード例 #6
0
 def test_add_user_inactive(self):
     add_user('test', '*****@*****.**', 'test')
     # update user
     user = User.first_by(email='*****@*****.**')
     user.active = False
     db.session.commit()
     with self.client:
         resp_login = self.client.post(
             '/v1/auth/login',
             data=json.dumps(dict(
                 email='*****@*****.**',
                 password='******'
             )),
             content_type='application/json',
             headers=[('Accept', 'application/json')]
         )
         response = self.client.post(
             '/v1/users',
             data=json.dumps(dict(
                 username='******',
                 email='*****@*****.**',
                 password='******'
             )),
             content_type='application/json',
             headers=[('Accept', 'application/json'), (Constants.HttpHeaders.AUTHORIZATION, 'Bearer ' + json.loads(resp_login.data.decode())['auth_token'])]
         )
         data = json.loads(response.data.decode())
         self.assertEqual(data['status'], 'error')
         self.assertEqual(data['message'], 'Something went wrong. Please contact us.')
         self.assertEqual(response.status_code, 401)
コード例 #7
0
 def test_add_user_duplicate_email(self):
     add_user('justatest', '*****@*****.**', 'password')
     duplicate_user = User(username='******',
                           email='*****@*****.**',
                           password='******')
     db.session.add(duplicate_user)
     self.assertRaises(IntegrityError, db.session.commit)
コード例 #8
0
    def test_duplicate_device_registration_with_different_users(self):
        with self.client:
            user1 = add_user('test', '*****@*****.**', 'test', roles=UserRole.USER)
            user2 = add_user('test2', '*****@*****.**', 'test', roles=UserRole.USER)
            device_id = uuid.uuid4().hex
            resp_login = self.client.post(
                '/v1/auth/login',
                data=json.dumps(dict(
                    email='*****@*****.**',
                    password='******'
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json')]
            )
            resp2_login = self.client.post(
                '/v1/auth/login',
                data=json.dumps(dict(
                    email='*****@*****.**',
                    password='******'
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json')]
            )

            pn_token = uuid.uuid4().hex
            self.client.put(
                f'/v1/devices/{device_id}',
                data=json.dumps(dict(
                    device_id=device_id,
                    device_type='apple',
                    pn_token=pn_token
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json'), (Constants.HttpHeaders.AUTHORIZATION, 'Bearer ' + json.loads(resp_login.data.decode())['auth_token'])]
            )
            response = self.client.put(
                f'/v1/devices/{device_id}',
                data=json.dumps(dict(
                    device_id=device_id,
                    device_type='apple',
                    pn_token=pn_token
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json'), (Constants.HttpHeaders.AUTHORIZATION, 'Bearer ' + json.loads(resp2_login.data.decode())['auth_token'])]
            )

            data = json.loads(response.data.decode())
            self.assertEqual(data['status'], 'success')
            self.assertEqual(data['message'], 'Device successfully registered.')
            self.assertEqual(response.content_type, 'application/json')
            self.assertEqual(response.status_code, 200)

            self.assertEqual(len(user1.devices), 0)
            self.assertEqual(len(user2.devices), 1)

            self.assertEqual(user2.devices[0].device_id, device_id)
            self.assertEqual(user2.devices[0].device_type, "apple")
            self.assertTrue(user2.devices[0].active)
            self.assertIsNotNone(user2.devices[0].pn_token)
            self.assertEqual(user2.devices[0].user_id, user2.id)
コード例 #9
0
    def test_login_with_same_device_id(self):
        """Test that device is removed and added to new device logged user."""
        with self.client:
            user1 = add_user('test', '*****@*****.**', 'test', roles=UserRole.USER)
            user2 = add_user('test2', '*****@*****.**', 'test', roles=UserRole.USER)
            device_id = uuid.uuid4().hex
            self.client.post(
                '/v1/auth/login',
                data=json.dumps(dict(
                    email='*****@*****.**',
                    password='******'
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json'), (Constants.HttpHeaders.DEVICE_ID, device_id), (Constants.HttpHeaders.DEVICE_TYPE, "apple")]
            )
            self.assertEqual(len(user1.devices), 1)

            self.client.post(
                '/v1/auth/login',
                data=json.dumps(dict(
                    email='*****@*****.**',
                    password='******'
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json'), (Constants.HttpHeaders.DEVICE_ID, device_id), (Constants.HttpHeaders.DEVICE_TYPE, "apple")]
            )

            self.assertEqual(len(user1.devices), 0)
            self.assertEqual(len(user2.devices), 1)

            self.assertEqual(user2.devices[0].device_id, device_id)
            self.assertEqual(user2.devices[0].device_type, "apple")
            self.assertTrue(user2.devices[0].active)
            self.assertIsNone(user2.devices[0].pn_token)
            self.assertEqual(user2.devices[0].user_id, user2.id)
コード例 #10
0
async def test_add_users(api):
    await clean_test_data(api)
    await asyncio.gather(add_user(api, USER_1), add_user(api, USER_2))
    async with api.server.app['db'].acquire() as conn:
        result = await conn.execute(
            user.select().where(user.c.username == USER_1))
        record = await result.first()
        assert record
コード例 #11
0
 def test_add_user_duplicate_email(self):
     add_user('curtis', '*****@*****.**', 'password1234')
     duplicate_email = User(username='******',
                            email='*****@*****.**',
                            password='******')
     db.session.add(duplicate_email)
     # self.assertRaises(IntegrityError, db.session.commit())
     with self.assertRaises(IntegrityError) as cm:
         db.session.commit()
 def test_main_with_users(self):
     """Ensure the main route behaves correctly when users have been
     added to the database."""
     add_user('michael', '*****@*****.**', 'greaterthaneight')
     add_user('fletcher', '*****@*****.**', 'greaterthaneight')
     with self.client:
         response = self.client.get('/')
         self.assertEqual(response.status_code, 200)
         self.assertIn(b'All Users', response.data)
         self.assertNotIn(b'<p>No users!</p>', response.data)
         self.assertIn(b'michael', response.data)
         self.assertIn(b'fletcher', response.data)
コード例 #13
0
 def test_get_users_html(self):
     """Ensure we can retrieve all users in HTML"""
     add_user('testuser', '*****@*****.**', 'test')
     add_user('testuser2', '*****@*****.**', 'test')
     with self.client:
         response = self.client.get('/users',
                                    headers={'Accept': 'text/html'})
         self.assertEqual(response.status_code, 200)
         self.assertIn(b'<h1>All Users</h1>', response.data)
         self.assertNotIn(b'<p>No users!</p>', response.data)
         self.assertIn(b'<strong>testuser</strong>', response.data)
         self.assertIn(b'<strong>testuser2</strong>', response.data)
コード例 #14
0
ファイル: test_users.py プロジェクト: benranderson/demo
 def test_all_users(self, client, test_db):
     recreate_db()
     add_user("michael", "*****@*****.**")
     add_user("fletcher", "*****@*****.**")
     resp = client.get("/users")
     data = json.loads(resp.data.decode())
     assert resp.status_code == 200
     assert len(data["data"]["users"]) == 2
     assert "michael" in data["data"]["users"][0]["username"]
     assert "*****@*****.**" in data["data"]["users"][0]["email"]
     assert "fletcher" in data["data"]["users"][1]["username"]
     assert "*****@*****.**" in data["data"]["users"][1]["email"]
     assert "success" in data["status"]
コード例 #15
0
def test_policy_public():
    utils.add_domain()
    utils.add_user()
    utils.add_alias(policy=MAILLIST_POLICY_PUBLIC)

    d = {
        'sender': tdata.ext_user,
        'recipient': tdata.alias,
    }
    s = utils.set_smtp_session(**d)
    action = utils.send_policy(s)

    assert action == SMTP_ACTIONS['default']
コード例 #16
0
def test_policy_subdomain():
    utils.add_domain()
    utils.add_user()
    utils.add_alias(policy=MAILLIST_POLICY_SUBDOMAIN)

    d = {
        'sender': tdata.ext_user,
        'recipient': tdata.alias,
    }
    s = utils.set_smtp_session(**d)
    action = utils.send_policy(s)

    assert action == SMTP_ACTIONS['reject_not_authorized']
コード例 #17
0
 def test_user_registration_duplicate_name(self):
     add_user('mans', '*****@*****.**', '4321drowssap')
     with self.client:
         response = self.client.post('/auth/register',
                                     data=json.dumps(
                                         dict(username='******',
                                              email='*****@*****.**',
                                              password='******')),
                                     content_type='application/json')
         data = json.loads(response.data.decode())
         self.assertEqual(response.status_code, 400)
         self.assertTrue(response.content_type == 'application/json')
         self.assertIn('Sorry. That user already exists.', data['message'])
         self.assertIn('fail', data['status'])
コード例 #18
0
 def test_user_registration_duplicate_username(self):
     add_user('test', '*****@*****.**', 'test')
     with self.client:
         response = self.client.post('/v1/auth/register',
                                     data=json.dumps(
                                         dict(username='******',
                                              email='[email protected]',
                                              password='******')),
                                     content_type='application/json',
                                     headers=[('Accept', 'application/json')
                                              ])
         data = json.loads(response.data.decode())
         self.assertEqual(response.status_code, 400)
         self.assertIn('Sorry. That user already exists.', data['message'])
         self.assertIn('error', data['status'])
コード例 #19
0
 def test_registered_user_login(self):
     with self.client:
         add_user('test', '*****@*****.**', 'test')
         response = self.client.post('/auth/login',
                                     data=json.dumps({
                                         'email': '*****@*****.**',
                                         'password': '******'
                                     }),
                                     content_type='application/json')
         data = json.loads(response.data.decode())
         self.assertTrue(data['status'] == 'success')
         self.assertTrue(data['message'] == 'Successfully logged in.')
         self.assertTrue(data['auth_token'])
         self.assertTrue(response.content_type == 'application/json')
         self.assertEqual(response.status_code, 200)
コード例 #20
0
    def test_device_registration(self):
        with self.client:
            user = add_user('test', '*****@*****.**', 'test', roles=UserRole.USER)
            resp_login = self.client.post(
                '/v1/auth/login',
                data=json.dumps(dict(
                    email='*****@*****.**',
                    password='******'
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json')]
            )
            device_id = uuid.uuid4().hex
            pn_token = uuid.uuid4().hex
            response = self.client.put(
                f'/v1/devices/{device_id}',
                data=json.dumps(dict(
                    device_id=device_id,
                    device_type='apple',
                    pn_token=pn_token
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json'), (Constants.HttpHeaders.AUTHORIZATION, 'Bearer ' + json.loads(resp_login.data.decode())['auth_token'])]
            )
            data = json.loads(response.data.decode())
            self.assertEqual(data['status'], 'success')
            self.assertEqual(data['message'], 'Device successfully registered.')
            self.assertEqual(response.content_type, 'application/json')
            self.assertEqual(response.status_code, 200)

            device = Device.first_by(device_id=device_id)
            self.assertEqual(device.pn_token, pn_token)
            self.assertEqual(device.device_type, 'apple')
            self.assertEqual(device.active, True)
            self.assertEqual(device.user_id, user.id)
コード例 #21
0
 def test_add_user(self):
     user = add_user('mans', '*****@*****.**', 'password1234')
     self.assertTrue(user.id)
     self.assertTrue(user.active)
     self.assertTrue(user.created_at)
     self.assertEqual(user.username, 'mans')
     self.assertEqual(user.email, '*****@*****.**')
コード例 #22
0
    def test_password_reset_already_reset(self):
        user = add_user('justatest3', '*****@*****.**', 'password')
        token = user.encode_password_token()

        user = set_user_token_hash(user, token)

        with self.client:
            response = self.client.put(
                '/v1/auth/password',
                data=json.dumps(dict(token=token, password='******')),
                content_type='application/json',
                headers=[('Accept', 'application/json')])
            data = json.loads(response.data.decode())
            self.assertEqual(data['status'], 'success')
            self.assertEqual(data['message'], 'Successfully reset password.')
            self.assertEqual(response.status_code, 200)

        user_password_before = user.password

        with self.client:
            response = self.client.put(
                '/v1/auth/password',
                data=json.dumps(dict(token=token, password='******')),
                content_type='application/json',
                headers=[('Accept', 'application/json')])
            data = json.loads(response.data.decode())
            self.assertEqual(data['status'], 'error')
            self.assertEqual(data['message'],
                             'Invalid reset. Please try again.')
            self.assertEqual(response.status_code, 404)
            #  check db password has not changed
            self.assertEqual(user_password_before, user.password)
コード例 #23
0
 def test_set_admin_user_to_organization(self):  # pylint: disable=invalid-name
     """Ensure user can be added to organization."""
     organization = add_organization('Test Organization', '*****@*****.**')
     user = add_user('justatest', '*****@*****.**', 'test')
     organization.add_admin(user)
     db.session.commit()
     self.assertIn(user, organization.admin_users)
コード例 #24
0
 def test_add_user_to_organization(self):
     """Ensure user can be added to organization."""
     organization = add_organization('Test Organization', '*****@*****.**')
     user = add_user('justatest', '*****@*****.**', 'test')
     organization.users.append(user)
     db.session.commit()
     self.assertIn(user, organization.users)
コード例 #25
0
    def test_auth_password_change_incorrect_password(self):
        """Ensure password change doesn't work with incorrect password"""
        password = self.data_generator.password()
        user = add_user(password=password)
        with self.client:
            resp_login = self.client.post(
                f'/{self.version}/auth/login',
                data=json.dumps(dict(
                    email=user.email,
                    password=password
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json')]
            )

            response = self.client.put(
                f'/{self.version}/auth/password_change',
                data=json.dumps(dict(
                    current_password=self.data_generator.password(),
                    new_password=self.data_generator.password()
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json'),
                         (Constants.HttpHeaders.AUTHORIZATION,
                          'Bearer ' + json.loads(resp_login.data.decode())['auth_token'])]
            )
            self.assertEqual(response.status_code, 400)
            data = json.loads(response.data.decode())
            self.assertEqual(data['message'], 'Validation Error')
            self.assertEqual(data['errors'][0]['field'], 'current_password')
            self.assertEqual(data['errors'][0]['message'], 'Invalid current password. Please try again.')
コード例 #26
0
    def test_email_verification(self):

        email = '*****@*****.**'
        user = add_user('justatest1', email, 'password')

        with self.client:
            resp_login = self.client.post(
                '/v1/auth/login',
                data=json.dumps(dict(
                    email=email,
                    password='******'
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json')]
            )
        #
        #
        #
        # user = add_user('justatest3', '*****@*****.**', 'password')
        #
        # with self.client:
            response = self.client.put(
                '/v1/email_verification',
                data=json.dumps(dict(
                    email=email
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json'), (Constants.HttpHeaders.AUTHORIZATION, 'Bearer ' + json.loads(resp_login.data.decode())['auth_token'])]
            )
            self.assertEqual(response.status_code, 200)
            data = json.loads(response.data.decode())
            self.assertEqual(data['status'], 'success')
            self.assertEqual(data['message'], 'Successfully sent email with email verification.')
コード例 #27
0
    def test_password_change_invalid_password(self):
        email = '*****@*****.**'
        old_password = '******'
        user = add_user('justatest1', email, old_password)

        with self.client:
            resp_login = self.client.post(
                '/v1/auth/login',
                data=json.dumps(dict(
                    email=email,
                    password=old_password
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json')]
            )

            response = self.client.put(
                '/v1/auth/password_change',
                data=json.dumps(dict(
                    old_password='******' + old_password,
                    new_password='******'
                )),
                content_type='application/json',
                headers=[('Accept', 'application/json'), (Constants.HttpHeaders.AUTHORIZATION, 'Bearer ' + json.loads(resp_login.data.decode())['auth_token'])]
            )
            self.assertEqual(response.status_code, 400)
            data = json.loads(response.data.decode())
            self.assertEqual(data['status'], 'error')
            self.assertEqual(data['message'], 'Invalid password. Please try again.')
コード例 #28
0
 def test_user_registration_duplicate_username(self):
     add_user('test', '*****@*****.**', 'test')
     with self.client:
         response = self.client.post(
             '/auth/register',
             data=json.dumps({
                 'username': '******',
                 'email': '[email protected]',
                 'password': '******'
             }),
             content_type='application/json',
         )
         data = json.loads(response.data.decode())
         self.assertEqual(response.status_code, 400)
         self.assertIn('Sorry. That user already exists.', data['message'])
         self.assertIn('fail', data['status'])
コード例 #29
0
 def test_expired_auth_token(self):
     """Ensures an expired token is identified as such"""
     user = add_user('test', '*****@*****.**', 'test')
     auth_token = user.encode_auth_token(user.id)
     time.sleep(3)
     self.assertEqual(str(user.decode_auth_token(auth_token)),
                      'Expired token, please login again.')
コード例 #30
0
 def test_registered_user_login(self):
     """Ensure login works for registered user."""
     with self.client:
         add_user('test', '*****@*****.**', 'test')
         response = self.client.post(
             '/api/v1/auth/login',
             data=json.dumps(dict(
                 email='*****@*****.**',
                 password='******'
             )),
             content_type='application/json'
         )
         data = json.loads(response.data.decode())
         self.assertTrue(data['status'] == 'success')
         self.assertTrue(data['data']['auth_token'])
         self.assertTrue(response.content_type == 'application/json')
         self.assertEqual(response.status_code, 200)