Esempio n. 1
0
    def create_user_and_return_id_and_token(self,
                                            roles=[],
                                            suspended=None,
                                            is_internal_user=None,
                                            enabled=None):
        # create a user to login with
        user = factories.UserFactory(password='******')
        user.roles = roles

        if suspended is not None:
            user.suspended = suspended

        if is_internal_user is not None:
            user.is_internal_user = is_internal_user

        if enabled is not None:
            user.enabled = enabled

        db_session_users.add(user)
        db_session_users.flush()
        db_session_users.refresh(user)

        # create a token to use for authorization for all api calls for the user created above
        seconds_until_expiration = 60 * 60 * 24 * 14
        expiration_datetime = dt.datetime.utcnow() + dt.timedelta(
            seconds=seconds_until_expiration)
        return user, jwt.encode(
            {
                'user_id': user.id,
                'exp': expiration_datetime
            }, SECRET_JWT)
Esempio n. 2
0
    def setUp(self):
        self.user, self.token = self.create_user_and_return_id_and_token()

        # create a second user/token so the user updates tests are independent of all else
        self.new_user, self.new_user_token = self.create_user_and_return_id_and_token(
        )
        self.admin_user, self.admin_user_token = self.create_user_and_return_id_and_token(
            roles=['admin'])
        self.qa_user, self.qa_user_token = self.create_user_and_return_id_and_token(
            roles=['qa'])
        self.suspended_user, self.suspended_user_token = self.create_user_and_return_id_and_token(
            suspended=True)
        self.internal_user, self.internal_user_token = self.create_user_and_return_id_and_token(
            is_internal_user=True)
        self.contributor_user, self.contributor_user_token = self.create_user_and_return_id_and_token(
            roles=['contributor'])
        self.unenabled_user, self.unenabled_user_token = self.create_user_and_return_id_and_token(
            enabled=False)

        api_key = ApiKey({'enabled': True})
        api_key.gen_token()
        db_session_users.add(api_key)
        db_session_users.commit()
        db_session_users.refresh(api_key)
        self.api_key = api_key
        # for the sake of testing populate plans table
        add_plans()

        # n.b. this should be removed when mainstream news category is launched
        os.environ["MAINSTREAM_NEWS_ENABLED"] = "true"
Esempio n. 3
0
    def test_pop_judgment_with_empty_queue(self):
        # hack: change the status of everything on the queue to something that won't be popped to
        # simulate an empty queue scenario
        for tj in db_session_users.query(TopicJudgment).all():
            tj.status = 'skipped'
            db_session_users.add(tj)
        db_session_users.commit()

        response = self.client.get("/topic_judgments/pop", headers={'Authorization': self.token})
        self.assert200(response)
        for key in ['id', 'status', 'judgment', 'document', 'user', 'topic_name']:
            self.assertNotIn(key, response.json)

        self.assertIn('queue', response.json)
        self.assertEqual(response.json['queue'], 'empty')
Esempio n. 4
0
    def test_success_link_to_email_account(self):
        email = "*****@*****.**"
        db_session_users.add(
            User({
                'email': email,
                'password': '******',
                'enabled': False
            }))
        db_session_users.commit()
        initial_user = db_session_users.query(User).filter_by(
            email=email).first()
        with patch("requests.post") as rpost:
            mock_response = rpost.return_value
            mock_response.status_code = 200
            mock_response.json.return_value = {"access_token": "doesntmatter"}
            with patch("requests.get") as rget:
                mock_response = rget.return_value
                mock_response.status_code = 200
                mock_response.json.return_value = {
                    "given_name": "doesntmatter",
                    "family_name": "doesntmatter",
                    "id": "doesntmatter",
                    "email": email
                }
                req_body = {
                    'code': 'doesntmatter',
                    "redirect_uri": "doesntmatter",
                    'termsAgreed': 'true'
                }
                resp = self.client.post("/auth_google_token", data=req_body)

        updated_user = db_session_users.query(User).filter_by(
            email=email).first()
        self.assert200(resp)
        self.assertIn("jwt_token", resp.data)
        self.assertIn('confirmed_date', updated_user.properties)
        self.assertIsInstance(updated_user.properties['confirmed_date'],
                              basestring)
        self.assertEqual(True, updated_user.enabled)
        self.assertEqual(True, len(updated_user.google_id) > 0)
        self.assertIn('secondary_signup_dates', updated_user.properties)
        self.assertIn('google',
                      updated_user.properties['secondary_signup_dates'])
        self.assertIsInstance(
            updated_user.properties['secondary_signup_dates']['google'],
            basestring)
Esempio n. 5
0
    def test_pop_judgment_with_zz_bad_doc(self):
        # hack: change the status back for everything to queued and set all but one doc to an invalid doc id
        original_tj = db_session_users.query(TopicJudgment).first()
        bad_tj = TopicJudgment(original_tj.__dict__)
        bad_tj.doc_id = 1000000
        bad_tj.status = 'queued'
        bad_tj.user_id = self.new_user.id
        db_session_users.add(bad_tj)
        db_session_users.commit()

        response = self.client.get("/topic_judgments/pop", headers={'Authorization': self.new_user_token})
        self.assert200(response)\

        #n.b. the previous test left this in the state where everything else is queued
        for key in ['id', 'status', 'judgment', 'document', 'user', 'topic_name']:
            self.assertNotIn(key, response.json)

        self.assertIn('queue', response.json)
        self.assertEqual(response.json['queue'], 'empty')
Esempio n. 6
0
    def test_reset_disabled_user(self):
        user = factories.UserFactory.build(
            first_name=None,
            last_name=None,
        )
        user.enabled = False
        user.gen_reset_token()
        db_session_users.add(user)
        db_session_users.flush()
        db_session_users.refresh(user)

        req_body = {
            'email': user.email,
        }

        resp = self.client.post(
            "/reset",
            data=json.dumps(req_body),
        )
        self.assert200(resp)

        updated_user = db_session_users.query(User).filter_by(email=user.email).first()
        self.assertEqual(user.reset_token, updated_user.reset_token)
Esempio n. 7
0
    def test_reset(self):
        user = factories.UserFactory.build(
            first_name=None,
            last_name=None,
        )
        user.enabled = True
        user.update_password('foo')
        user.properties = {"activation_time": 'foo'}
        db_session_users.add(user)
        db_session_users.flush()
        db_session_users.refresh(user)

        req_body = {
            'email': user.email,
            'password': '******',
        }

        resp = self.client.post(
            "/login",
            data=json.dumps(req_body),
        )

        self.assert200(resp)

        req_body = {
            'email': user.email,
        }

        resp = self.client.post(
            "/reset",
            data=json.dumps(req_body),
        )

        self.assert200(resp)

        # original password still works
        req_body = {
            'email': user.email,
            'password': '******',
        }

        resp = self.client.post(
            "/login",
            data=json.dumps(req_body),
        )

        self.assert200(resp)

        # now actually set a new password
        req_body = {
            'email': user.email,
            'new_password': '******',
            'token': user.reset_token,
        }

        resp = self.client.post(
            "/activate",
            data=json.dumps(req_body),
        )

        self.assert200(resp)
        db_session_users.refresh(user)
        self.assertEqual(user.properties['activation_time'], 'foo')

        # original password doesn't work
        req_body = {
            'email': user.email,
            'password': '******',
        }

        resp = self.client.post(
            "/login",
            data=json.dumps(req_body),
        )

        self.assert401(resp)

        # but the new one does!
        req_body = {
            'email': user.email,
            'password': '******',
        }

        resp = self.client.post(
            "/login",
            data=json.dumps(req_body),
        )

        self.assert200(resp)
    def test_login(self):
        user = factories.UserFactory.build(
            first_name=None,
            last_name=None,
        )
        user.enabled = False

        db_session_users.add(user)
        db_session_users.flush()
        db_session_users.refresh(user)

        # test with a disabled account
        req_body = {
            'email': user.email,
            'password': '******',
        }

        resp = self.client.post(
            "/login",
            data=json.dumps(req_body),
        )

        # test that proper error message is sent back, in the case a user is not from a campaign
        # but has signed-up with open registration so the msg must contain the term `verified`
        user_part_of_campaign = db_session_users.query(
            MarketingCampaignUsers).filter_by(id=user.id).first()
        if user_part_of_campaign or "invited_by" not in user.properties:
            self.assertRegexpMatches(resp.json['error'], r'verified')

        # invite a random user
        req_body = json.dumps({'email': '*****@*****.**'})
        resp = self.client.post(
            "/invite",
            headers={'Authorization': self.admin_user_token},
            data=req_body)

        self.assert200(resp)

        new_user = db_session_users.query(User).filter_by(
            email='*****@*****.**').first()
        self.assertFalse(new_user.enabled)

        # then have the user login before becoming enabled
        req_body = {
            'email': '*****@*****.**',
            'password': '******',
        }
        resp = self.client.post(
            "/login",
            data=json.dumps(req_body),
        )

        # test that proper error message is sent out, in the case a user is neither from a campaign
        # nor has signed-up with open registration, but has been invited so the msg must contain the term `enabled`
        self.assertRegexpMatches(resp.json['error'], r'enabled')

        # enable but don't set password
        user.enabled = True
        db_session_users.add(user)
        db_session_users.flush()
        db_session_users.refresh(user)

        req_body = {
            'email': user.email,
            'password': '',
        }

        resp = self.client.post(
            "/login",
            data=json.dumps(req_body),
        )

        self.assert400(resp)

        # set a password and login
        user.update_password('foo')
        db_session_users.add(user)
        db_session_users.flush()
        db_session_users.refresh(user)

        req_body = {
            'email': user.email,
            'password': '******',
        }

        resp = self.client.post(
            "/login",
            data=json.dumps(req_body),
        )

        self.assert200(resp)

        # make sure bad password is rejected
        req_body = {
            'email': user.email,
            'password': '******',
        }

        resp = self.client.post(
            "/login",
            data=json.dumps(req_body),
        )

        self.assert401(resp)

        # now suspend the user and make sure it fails
        user.suspended = True
        db_session_users.add(user)
        db_session_users.flush()
        db_session_users.refresh(user)

        req_body = {
            'email': user.email,
            'password': '******',
        }

        resp = self.client.post(
            "/login",
            data=json.dumps(req_body),
        )

        self.assert401(resp)
Esempio n. 9
0
SearchVersion = 1

## NB: tweak by hand for now
## koala-0 = javelina
## koala-1 = acronym boost (boost=8.0)

# create a token to use for authorization for all api calls
user = db_session_users.query(User).filter_by(id=1).scalar()
seconds_until_expiration = 60 * 60 * 24 * 14
expiration_datetime = dt.datetime.utcnow() + dt.timedelta(seconds=seconds_until_expiration)
token = jwt.encode({'user_id': user.id, 'exp': expiration_datetime}, SECRET_JWT)

for q in db_session_users.query(SearchRegressionQuery).all():
    url = "http://localhost:5000/documents?query={}".format(q.query)
    response = requests.get(url, headers={'Authorization': token})
    docs  = response.json()['documents']
    doc_ids = [ d['id'] for d in docs ]
    scores  = [ d['score'] for d in docs ]
    results = { 'documents': docs }
    assessment_params = {
        'query_id': q.id,
        'build':    BuildName,
        'version':  SearchVersion,
        'scores':   scores,
        'results':  results,
        'doc_ids':  doc_ids

    }
    db_session_users.add(SearchAssessmentResult(assessment_params))
db_session_users.commit()
def build_query_set():
    for line in open(this_folder + '/fixtures/relevance_queries.tsv'):
        query = line.strip().split("\t")[1]
        if not db_session_users.query(SearchRegressionQuery).filter_by(query=query).scalar():
            db_session_users.add(SearchRegressionQuery({ 'query': query}))
    db_session_users.commit()