Beispiel #1
0
    def test_main(self, mock_post: mock.MagicMock) -> None:
        """Overall test."""

        _db = pymongo.MongoClient('mongodb://my-db/db').db
        _db.user.drop()
        _db.user.insert_one({
            '_id':
            mongomock.ObjectId('5daf2298484ae6c93351b822'),
            'profile': {
                'name': 'Pascal',
                'lastName': 'Corpet',
                'email': '*****@*****.**',
                'locale': 'en',
            },
            'registeredAt':
            datetime.datetime(2018, 1, 22, 10, 0, 0).isoformat() + 'Z',
            'projects': [{
                'title': 'Project Title',
            }],
        })

        mail_nps.main(self._now, '1')

        sent_messages = mailjetmock.get_all_sent_messages()
        self.assertEqual(['*****@*****.**'],
                         [m.recipient['Email'] for m in sent_messages])
        self.assertEqual(100819, sent_messages[0].properties['TemplateID'])
        template_vars = sent_messages[0].properties['Variables']
        nps_form_urlstring = template_vars.pop('npsFormUrl')
        self.assertEqual(
            {
                'baseUrl': 'http://localhost:3000',
                'firstName': 'Pascal',
            }, template_vars)
        nps_form_url = parse.urlparse(nps_form_urlstring)
        self.assertEqual(
            'http://localhost:3000/api/nps',
            parse.urlunparse(nps_form_url[:4] + ('', ) + nps_form_url[5:]))
        nps_form_args = parse.parse_qs(nps_form_url.query)
        self.assertEqual({'user', 'token', 'redirect'}, nps_form_args.keys())
        self.assertEqual(['5daf2298484ae6c93351b822'], nps_form_args['user'])
        auth.check_token('5daf2298484ae6c93351b822',
                         nps_form_args['token'][0],
                         role='nps')
        self.assertEqual(['http://localhost:3000/retours?hl=en'],
                         nps_form_args['redirect'])
        mock_post.assert_called_once_with(
            'https://slack.example.com/webhook',
            json={
                'text':
                "Report for NPS blast: I've sent 1 emails (with 0 errors)."
            },
        )

        modified_user = user_pb2.User()
        proto.parse_from_mongo(_db.user.find_one(), modified_user)
        self.assertEqual(
            [sent_messages[0].message_id],
            [m.mailjet_message_id for m in modified_user.emails_sent])
        self.assertEqual('nps', modified_user.emails_sent[0].campaign_id)
Beispiel #2
0
    def test_generate_tokens_facebook(self) -> None:
        """Check the /api/user/.../generate-auth-tokens for a Facebook user."""

        user_id, auth_token = self.create_facebook_user_with_token(
            '*****@*****.**')
        response = self.app.get(
            f'/api/user/{user_id}/generate-auth-tokens',
            headers={'Authorization': 'Bearer ' + auth_token})
        tokens = self.json_from_response(response)
        self.assertEqual(
            {
                'auth',
                'authUrl',
                'employmentStatus',
                'employmentStatusUrl',
                'nps',
                'npsUrl',
                'settings',
                'settingsUrl',
                'unsubscribe',
                'unsubscribeUrl',
                'user',
            }, tokens.keys())
        auth.check_token(user_id, tokens['unsubscribe'], role='unsubscribe')
        auth.check_token(user_id,
                         tokens['employmentStatus'],
                         role='employment-status')
        auth.check_token(user_id, tokens['nps'], role='nps')
        auth.check_token(user_id, tokens['settings'], role='settings')
        auth.check_token(user_id, tokens['auth'], role='')
        self.assertEqual(user_id, tokens['user'])
    def test_main(self, mock_mail, mock_report_mail):
        """Overall test."""

        self._db.user.insert_one({
            '_id':
            'my-own-user-id',
            'profile': {
                'name': 'Pascal',
                'lastName': 'Corpet',
                'email': '*****@*****.**',
            },
            'registeredAt':
            datetime.datetime(2018, 1, 22, 10, 0, 0).isoformat() + 'Z',
            'projects': [{
                'title': 'Project Title',
            }],
        })
        mock_mail.send_template.return_value.status_code = 200
        mock_mail.send_template.return_value.json.return_value = {
            'Sent': [{
                'MessageID': 123456,
            }]
        }
        mock_report_mail.send_template_to_admins.return_value.status_code = 200

        mail_nps.main(self._db.user, 'http://*****:*****@bayes.org', profile.email)
        nps_form_urlstring = template_vars.pop('npsFormUrl')
        self.assertEqual(
            {
                'baseUrl': 'http://localhost:3000',
                'firstName': 'Pascal',
            }, template_vars)
        nps_form_url = parse.urlparse(nps_form_urlstring)
        self.assertEqual(
            'http://localhost:3000/api/nps',
            parse.urlunparse(nps_form_url[:4] + ('', ) + nps_form_url[5:]))
        nps_form_args = parse.parse_qs(nps_form_url.query)
        self.assertEqual({'user', 'token', 'redirect'}, nps_form_args.keys())
        self.assertEqual(['my-own-user-id'], nps_form_args['user'])
        auth.check_token('my-own-user-id',
                         nps_form_args['token'][0],
                         role='nps')
        self.assertEqual(['http://localhost:3000/retours'],
                         nps_form_args['redirect'])
        self.assertTrue(mock_report_mail.send_template_to_admins.called)

        modified_user = user_pb2.User()
        proto.parse_from_mongo(self._db.user.find_one(), modified_user)
        self.assertEqual(123456,
                         modified_user.emails_sent[0].mailjet_message_id)
        self.assertEqual('nps', modified_user.emails_sent[0].campaign_id)
Beispiel #4
0
def give_feedback(feedback):
    """Retrieve information about jobs whithin a job group."""

    if feedback.user_id:
        auth_token = flask.request.headers.get('Authorization',
                                               '').replace('Bearer ', '')
        if not auth_token:
            flask.abort(401, 'Token manquant')
        try:
            auth.check_token(feedback.user_id, auth_token, role='auth')
        except ValueError:
            flask.abort(403, 'Unauthorized token')
    _give_feedback(feedback)
    return ''
Beispiel #5
0
def delete_user(user_data):
    """Delete a user and their authentication information."""

    auth_token = flask.request.headers.get('Authorization',
                                           '').replace('Bearer ', '')
    if user_data.user_id:
        try:
            auth.check_token(user_data.user_id, auth_token, role='auth')
        except ValueError:
            flask.abort(403, 'Wrong authentication token.')
        filter_user = {'_id': _safe_object_id(user_data.user_id)}
    elif user_data.profile.email:
        try:
            auth.check_token(user_data.profile.email,
                             auth_token,
                             role='unsubscribe')
        except ValueError:
            flask.abort(403, 'Accès refusé')
        filter_user = _USER_DB.user.find_one(
            {'profile.email': user_data.profile.email}, {'_id': 1})
    else:
        flask.abort(400, 'Impossible de supprimer un utilisateur sans son ID.')

    if not filter_user:
        return user_pb2.UserId()

    # Remove authentication informations.
    _USER_DB.user_auth.delete_one(filter_user)

    user_proto = _get_user_data(filter_user['_id'])
    try:
        privacy.redact_proto(user_proto)
    except TypeError:
        logging.exception('Cannot delete account %s', str(filter_user['_id']))
        flask.abort(500, 'Erreur serveur, impossible de supprimer le compte.')
    user_proto.deleted_at.FromDatetime(now.get())
    user_proto.ClearField('user_id')
    _USER_DB.user.replace_one(filter_user,
                              json_format.MessageToDict(user_proto))

    return user_pb2.UserId(user_id=str(filter_user['_id']))
Beispiel #6
0
    def test_create_logged_url(self) -> None:
        """Test the create logged url function."""

        user_id = '02499e64387edfcc2ab7a948'
        base_url = f'https://www.bob-emploi.fr/project/0/wow-baker?userId={user_id}'
        regex = re.compile(rf'^{re.escape(base_url)}&authToken=(\d+\.[a-f0-9]+)$')
        logged_url = campaign.create_logged_url(user_id, '/project/0/wow-baker')
        self.assertRegex(logged_url, regex)

        match_token = regex.match(logged_url)
        assert match_token
        token = match_token.group(1)
        self.assertTrue(auth.check_token(user_id, token, role='auth'))
Beispiel #7
0
    def test_generate_tokens(self):
        """Check the /api/user/.../generate-auth-tokens."""

        user_id, auth_token = self.create_user_with_token(email='*****@*****.**')
        response = self.app.get(
            '/api/user/{}/generate-auth-tokens'.format(user_id),
            headers={'Authorization': 'Bearer ' + auth_token})
        tokens = self.json_from_response(response)
        self.assertEqual(
            {'auth', 'employment-status', 'nps', 'unsubscribe', 'user'}, tokens.keys())
        auth.check_token('*****@*****.**', tokens['unsubscribe'], role='unsubscribe')
        auth.check_token(user_id, tokens['employment-status'], role='employment-status')
        auth.check_token(user_id, tokens['nps'], role='nps')
        auth.check_token(user_id, tokens['auth'], role='')
        self.assertEqual(user_id, tokens['user'])
Beispiel #8
0
    def test_create_logged_url(self):
        """Test the create logged url function."""

        user_id = '02499e64387edfcc2ab7a948'
        regex = re.compile(r'^{}&authToken=(\d+\.[a-f0-9]+)$'.format(
            re.escape(
                'https://www.bob-emploi.fr/project/0/avancer/wow-baker?user={}'
                .format(user_id))))
        logged_url = campaign.create_logged_url(
            user_id, '/project/0/avancer/wow-baker')
        self.assertRegex(logged_url, regex)

        token = regex.match(logged_url).group(1)
        self.assertTrue(auth.check_token(user_id, token, role='auth'))
Beispiel #9
0
    def test_check_token_wrong_role(self) -> None:
        """check_token fails if wrong role."""

        login_token = auth.create_token('*****@*****.**', 'login')
        with self.assertRaises(ValueError):
            auth.check_token('*****@*****.**', login_token, 'unsubscribe')
Beispiel #10
0
    def test_check_token_empty(self) -> None:
        """Check that an empty token fails."""

        with self.assertRaises(ValueError):
            auth.check_token('*****@*****.**', '', 'login')
Beispiel #11
0
    def test_check_token(self) -> None:
        """Basic usage of check_token (round trip with create_token)."""

        login_token = auth.create_token('*****@*****.**', 'login')
        auth.check_token('*****@*****.**', login_token, 'login')
Beispiel #12
0
    def test_generate_tokens(self) -> None:
        """Check the /api/user/.../generate-auth-tokens."""

        user_id, auth_token = self.create_user_with_token(
            email='*****@*****.**')
        response = self.app.get(
            f'/api/user/{user_id}/generate-auth-tokens',
            headers={'Authorization': 'Bearer ' + auth_token})
        tokens = self.json_from_response(response)
        self.assertEqual(
            {
                'auth',
                'authUrl',
                'employmentStatus',
                'employmentStatusUrl',
                'nps',
                'npsUrl',
                'reset',
                'resetUrl',
                'settings',
                'settingsUrl',
                'unsubscribe',
                'unsubscribeUrl',
                'user',
            }, tokens.keys())
        auth.check_token(user_id, tokens['unsubscribe'], role='unsubscribe')
        auth.check_token(user_id,
                         tokens['employmentStatus'],
                         role='employment-status')
        auth.check_token(user_id, tokens['nps'], role='nps')
        auth.check_token(user_id, tokens['settings'], role='settings')
        auth.check_token(user_id, tokens['auth'], role='')
        self.assertEqual({
            'authToken': tokens['auth'],
            'userId': user_id,
        }, dict(parse.parse_qsl(parse.urlparse(tokens['authUrl']).query)))
        self.assertEqual(
            {
                'token': tokens['employmentStatus'],
                'user': user_id,
            },
            dict(
                parse.parse_qsl(
                    parse.urlparse(tokens['employmentStatusUrl']).query)))
        self.assertEqual({
            'token': tokens['nps'],
            'user': user_id,
        }, dict(parse.parse_qsl(parse.urlparse(tokens['npsUrl']).query)))
        self.assertEqual(
            {
                'auth': tokens['settings'],
                'coachingEmailFrequency': 'EMAIL_MAXIMUM',
                'user': user_id,
            },
            dict(parse.parse_qsl(parse.urlparse(tokens['settingsUrl']).query)))
        self.assertEqual({
            'auth': tokens['unsubscribe'],
            'user': user_id,
        }, dict(parse.parse_qsl(
            parse.urlparse(tokens['unsubscribeUrl']).query)))
        # Try reset token as auth token.
        response = self.app.post(
            '/api/user/authenticate',
            data=f'{{"email":"*****@*****.**","userId":"{user_id}",'
            f'"authToken":"{tokens["reset"]}","hashedPassword":"******"}}')
        self.assertEqual(200, response.status_code)
        self.assertEqual(
            {
                'email': '*****@*****.**',
                'resetToken': tokens['reset'],
            }, dict(parse.parse_qsl(parse.urlparse(tokens['resetUrl']).query)))
        self.assertEqual(user_id, tokens['user'])