Exemplo n.º 1
0
    def handle(self, *args, **options):
        if not len(args):
            user = User.objects(username='******').first() or User(
                username='******').save()
            user.group = Group.objects(name='Administrator').first()
            user.set_password('password')
            location = Location.objects(type='district').first() or Location(
                name='Kampala', type='district').save()
            profile = UserProfile.objects(phone='N/A').first() or UserProfile(
                phone='N/A',
                name='Admin',
                location=location,
                email='*****@*****.**').save()
            profile.user = user
            profile.save()
        else:
            user = User.objects(username=args[0]).first() or User(
                username=args[0]).save()
            user.group = Group.objects(name='Administrator').first()
            user.set_password(args[1])
            location = Location.objects(name=args[4]).first() or Location(
                name=args[4], type='district').save()
            profile = UserProfile.objects(
                phone=args[5]).first() or UserProfile(
                    phone=args[5],
                    name=args[3],
                    location=location,
                    email=args[2]).save().save()
            profile.user = user
            profile.save()

        self.stdout.write('Successfully created superuser')
    def test_should_omit_empty_csv_rows(self):

        bulk_mobile_users = [
            {
                "name": "new name",
                "phone": "+256771289018",
                "email": "*****@*****.**",
                "district": "%s" % self.masaka.name,
                "subcounty": "unknownSub",
            },
            {},
            {
                "name": "%s" % self.mobile_user['name'],
                "phone": "%s" % self.mobile_user['phone'],
                "email": None,
                "district": "%s" % self.district.name,
                "subcounty": "%s" % '',
            },
        ]

        response = self.client.post(self.BULK_ENDPOINT,
                                    bulk_mobile_users,
                                    format='json')

        self.assertEqual(1, UserProfile.objects.count())
        masaka_users = UserProfile.objects(name=self.masaka_user['name'])
        self.assertEqual(0, masaka_users.count())
        self.mobile_user['email'] = ""  #empty string is not equal to None
        kampala_users = UserProfile.objects(**self.mobile_user)
        self.assertEqual(1, kampala_users.count())
    def test_updating_profile_with_photo_file(self):
        attr = self.mobile_user_to_post.copy()
        attr['email'] = '*****@*****.**'
        attr['phone'] = '+256775019511'
        attr['user'] = User(username='******', password='******').save()
        profile = UserProfile(**attr)
        user_photo = open(settings.PROJECT_ROOT + '/../dms/tests/test.jpg',
                          'rb')
        profile.photo.put(user_photo, content_type='image/content_type')
        profile.save()

        with open(settings.PROJECT_ROOT + '/../dms/tests/test2.jpg',
                  'rb') as test_image:
            attr['file'] = test_image
            response = self.client.post(
                self.API_ENDPOINT + str(profile.id) + '/', attr)
            self.assertEqual(200, response.status_code)

        retrieved_user = User.objects(username='******').first()
        reloaded_profile = UserProfile.objects(user=retrieved_user).first()
        self.assertEqual(
            reloaded_profile.photo.read(),
            open(settings.PROJECT_ROOT + '/../dms/tests/test2.jpg',
                 'rb').read())
        self.assertEqual(reloaded_profile.photo.content_type, 'image/jpeg')
        self.assertEqual(reloaded_profile.photo_uri(),
                         '/api/v1/photo/' + str(reloaded_profile.id))
Exemplo n.º 4
0
    def setUp(self):
        self.date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000)
        self.date_time = self.date_time.replace(tzinfo=pytz.utc)
        self.district = Location(**dict(name='Kampala', parent=None, type='district')).save()
        self.village = Location(**dict(name='Bukoto', parent=self.district, type='village')).save()
        self.mobile_user = UserProfile(**dict(name='timothy', phone="+256775019449",
                                             location=self.village, email=None)).save()

        self.fire_type = DisasterType(**dict(name="Fire", description="Fire")).save()
        disaster_attributes = dict(name=self.fire_type, locations=[self.district],
                                   description="Big Fire", date="2014-12-01 00:00:00", status="Assessment")
        self.disaster = Disaster(**disaster_attributes).save()

        self.text_format = "NECOC.%s. There is a fire"
        text = self.text_format % self.village.name
        self.expected_message = dict(phone="+256775019449", text=text, time=self.date_time, relayer=234,
                                     run=23243)
        self.message = dict(phone_no="+256775019449", text=text, received_at=self.date_time,
                            relayer_id=234, run_id=23243)

        self.api_user, created = User.objects.get_or_create(**dict(username='******'))
        self.auto_message_response = dict(phone_numbers=[u'+256775019449'], text=settings.AUTO_RESPONSE_MESSAGE)

        self.cao_group, created = Group.objects.get_or_create(name='CAO')
        self.cao_user = User.objects.create(username='******', group=self.cao_group, email='*****@*****.**')
        self.cao_user.set_password('password')
        self.login_url = '/login/'
        self.login_data = {
            'username': '******',
            'password': '******'
        }

        AdminSetting(**dict(name='enable_automatic_response')).save()
        AdminSetting(**dict(name='enable_volunteer_profiles')).save()
    def setUp(self):
        date_time = datetime.datetime(2014, 9, 17, 16, 0, 49, 807000)
        phone_number = "+256775019449"

        self.district = Location(
            **dict(name='Kampala', parent=None, type='district')).save()
        self.village = Location(**dict(
            name='Bukoto', parent=self.district, type='village')).save()
        self.mobile_user = UserProfile(**dict(name='timothy',
                                              phone=phone_number,
                                              location=self.village,
                                              email=None)).save()
        self.mobile_user2 = UserProfile(**dict(
            name='timothy2', phone='12344', location=self.village,
            email=None)).save()

        poll_attr = dict(name="Disaster",
                         question="How many disasters are in your area?",
                         keyword="some_word",
                         target_locations=[str(self.village.id)])

        self.poll = Poll(**poll_attr).save()

        self.poll_response_attr = dict(phone_no=phone_number,
                                       text="NECOCPoll %s whatever" %
                                       self.poll['keyword'],
                                       received_at=date_time,
                                       relayer_id=234,
                                       run_id=23243,
                                       poll=self.poll)

        self.delimiter_line = 'sep=;'
        self.headings = "Respondent;Answer;Location;Responded on"
    def test_should_omit_empty_csv_rows(self):

        bulk_mobile_users = [
            {
                "name":"new name",
                "phone":"+256771289018",
                "email": "*****@*****.**",
                "district": "%s" % self.masaka.name,
                "subcounty": "unknownSub",
             },
            {},
            {
                "name":"%s" % self.mobile_user['name'],
                "phone":"%s" % self.mobile_user['phone'],
                "email": None,
                "district": "%s" % self.district.name,
                "subcounty": "%s" % '',
             },
        ]

        response = self.client.post(self.BULK_ENDPOINT, bulk_mobile_users, format='json')

        self.assertEqual(1, UserProfile.objects.count())
        masaka_users = UserProfile.objects(name=self.masaka_user['name'])
        self.assertEqual(0, masaka_users.count())
        self.mobile_user['email']="" #empty string is not equal to None
        kampala_users = UserProfile.objects(**self.mobile_user)
        self.assertEqual(1, kampala_users.count())
Exemplo n.º 7
0
 def test_should_create_new_user(self):
     mobile_user = dict(name='timothy',
                        phone='+256775019449',
                        location=self.district,
                        email=None)
     UserProfile(**mobile_user).save()
     saved_mobile_user = UserProfile.objects(**mobile_user)
     self.assertEqual(1, saved_mobile_user.count())
Exemplo n.º 8
0
    def test_get_username_from_regular_user(self):
        user_profile_attr = dict(name='timothy',
                                 phone='+256775019449',
                                 location=self.district,
                                 email=None)
        profile = UserProfile(**user_profile_attr).save()

        self.assertEqual('', profile.username())
Exemplo n.º 9
0
    def test_get_user_id(self):
        user = User(username='******', password='******').save()
        user_profile_attr = dict(name='timothy',
                                 phone='+256775019449',
                                 location=self.district,
                                 email=None,
                                 user=user)
        profile = UserProfile(**user_profile_attr).save()

        self.assertEqual(str(user.id), profile.user_id())
Exemplo n.º 10
0
    def test_reset_password_saves_new_password(self, mock_send_email):
        district = Location(**dict(name='Kampala', parent=None, type='district'))
        district.save()
        profile = UserProfile(name='Andrew', email='*****@*****.**', location=district, phone='2570760540326')
        user = UserProfileService(profile).setup_new_user('andrew', str((Group.objects().first()).id))
        old_password = user.password
        profile.user = user

        UserProfileService(profile).reset_password()
        self.assertNotEqual(old_password, profile.user.password)
Exemplo n.º 11
0
    def setUp(self):
        self.login_user()
        self.kampala = Location(name='Kampala', parent=None,
                                type='district').save()
        gulu = Location(
            **(dict(name='Gulu', parent=None, type='district'))).save()
        self.amuru = Location(
            **(dict(name='Amuru', parent=None, type='district'))).save()
        self.ludara_subcounty = Location(
            **(dict(name='LUDARA', parent=self.amuru.id, type='subcounty')
               )).save()
        self.ddmc_group, created = Group.objects.get_or_create(name='DDMC')
        user_attr = dict(name='timothy',
                         phone='+256775019449',
                         location=gulu,
                         email=None)
        UserProfile(**(user_attr)).save()

        self.bukoto = Location(name='Bukoto',
                               parent=self.kampala,
                               type='subcounty').save()
        bukoto_user_attr = dict(name='timothy',
                                phone='+250775019449',
                                location=self.bukoto,
                                email=None)
        UserProfile(**bukoto_user_attr).save()
        bukoto_user_attr2 = bukoto_user_attr.copy()
        bukoto_user_attr2['phone'] = '+4343245552'
        UserProfile(**bukoto_user_attr2).save()

        self.target_locations = [str(self.kampala.id), str(gulu.id)]
        self.poll_to_post = dict(
            name="Disaster",
            question="How many disasters are in your area?",
            keyword="some_word",
            target_locations=self.target_locations)
        self.poll_to_post2 = dict(
            name="Disaster2",
            question="How many disasters are in your area?",
            keyword="some_word2",
            target_locations=[str(self.amuru.id)])
        self.poll_to_post3 = dict(
            name="Disaster3",
            question="How many disasters are in your area?",
            keyword="some_word3",
            target_locations=[str(self.ludara_subcounty.id)])
        self.headers = {
            'Authorization': 'Token ' + API_TOKEN,
            'content-type': 'application/json'
        }
        self.poll_to_send = dict(
            text=
            'How many disasters are in your area? Reply with: POLL some_word',
            phone_numbers=['+256775019449'])
    def test_should_get_a_list_of_users(self):
        user_profile = UserProfile(**self.mobile_user).save()
        response = self.client.get(self.API_ENDPOINT, format='json')

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertEqual(self.mobile_user['name'], response.data[0]['name'])
        self.assertEqual(self.mobile_user['phone'], response.data[0]['phone'])
        self.assertEqual(self.mobile_user['email'], response.data[0]['email'])
        self.assertEqual(user_profile.username(), '')
        self.assertEqual(self.district.name, response.data[0]['location']['name'])
Exemplo n.º 13
0
 def test_should_save_photo_of_user(self):
     user_profile_attr = dict(name='timothy', phone='+256775019449', location=self.district, email=None)
     profile = UserProfile(**user_profile_attr)
     user_photo = open(settings.PROJECT_ROOT + '/../dms/tests/test.jpg', 'rb')
     profile.photo.put(user_photo, content_type='image/content_type')
     profile.save()
     reloaded_profile = UserProfile.objects(id=profile.id).first()
     self.assertEqual(reloaded_profile.photo.read(),
                      open(settings.PROJECT_ROOT + '/../dms/tests/test.jpg', 'rb').read())
     self.assertEqual(reloaded_profile.photo.content_type, 'image/content_type')
     self.assertEqual(reloaded_profile.photo_uri(), '/api/v1/photo/' + str(reloaded_profile.id))
    def test_should_get_a_list_of_users(self):
        user_profile = UserProfile(**self.mobile_user).save()
        response = self.client.get(self.API_ENDPOINT, format='json')

        self.assertEqual(200, response.status_code)
        self.assertEqual(1, len(response.data))
        self.assertEqual(self.mobile_user['name'], response.data[0]['name'])
        self.assertEqual(self.mobile_user['phone'], response.data[0]['phone'])
        self.assertEqual(self.mobile_user['email'], response.data[0]['email'])
        self.assertEqual(user_profile.username(), '')
        self.assertEqual(self.district.name,
                         response.data[0]['location']['name'])
Exemplo n.º 15
0
    def test_should_not_save_a_users_with_the_same_phone_number(self):
        mobile_user_one = dict(name='timothy',
                               phone='+256775019449',
                               location=self.district,
                               email=None)
        mobile_user_two = dict(name='James',
                               phone='+256775019449',
                               location=self.district,
                               email=None)

        UserProfile(**mobile_user_one).save()
        self.assertRaises(NotUniqueError, UserProfile(**mobile_user_two).save)
Exemplo n.º 16
0
 def number_of_participants(self):
     locations = self.target_locations
     users = 0
     for loc in locations:
         locObj = Location.objects(id=loc).first()
         if locObj.parent == None:
             locs = locObj.full_tree()
             for l in locs:
                 users += len(UserProfile.objects(location=l).distinct('phone'))
         else:
             users += len(UserProfile.objects(location=locObj).distinct('phone'))
     return users
Exemplo n.º 17
0
    def test_password_reset_sends_email(self, mock_send_mail, mock_make_password):
        message = "Andrew blabla http://necoc.org.ug [email protected]"
        mock_make_password.return_value = 'blabla'
        district = Location(**dict(name='Kampala', parent=None, type='district'))
        district.save()
        profile = UserProfile(name='Andrew', email='*****@*****.**', location=district, phone='2570760540326')
        user = UserProfileService(profile).setup_new_user('andrew', str((Group.objects().first()).id))
        profile.user = user

        UserProfileService(profile).reset_password()
        mock_send_mail.assert_any_call('NECOC Password Reset',
                                       message,
                                       "*****@*****.**",
                                       ['*****@*****.**'])
Exemplo n.º 18
0
    def setUp(self):
        self.phone_number = "256775019449"

        kampala = Location(**dict(name='Kampala', parent=None, type='district')).save()
        gulu = Location(**dict(name='Gulu', parent=None, type='district')).save()
        self.village = Location(**dict(name='Bukoto', parent=kampala, type='subcounty')).save()
        self.mobile_user = UserProfile(**dict(name='timothy', phone=self.phone_number, location=self.village, email=None)).save()
        self.mobile_user2 = UserProfile(**dict(name='mobile_user2', phone='256775019441', location=self.village, email=None)).save()
        self.mobile_user3 = UserProfile(**dict(name='mobile_user3', phone='256775019442', location=gulu, email=None)).save()
        self.mobile_user4 = UserProfile(**dict(name='mobile_user4', phone='256775019443', location=kampala, email=None)).save()

        self.target_locations = [str(kampala.id), str(gulu.id)]
        self.poll = dict(name="Disaster", question="How many disasters are in your area?", keyword="some word",
                         target_locations=self.target_locations)
Exemplo n.º 19
0
 def number_of_participants(self):
     locations = self.target_locations
     users = 0
     for loc in locations:
         locObj = Location.objects(id=loc).first()
         if locObj.parent == None:
             locs = locObj.full_tree()
             for l in locs:
                 users += len(
                     UserProfile.objects(location=l).distinct('phone'))
         else:
             users += len(
                 UserProfile.objects(location=locObj).distinct('phone'))
     return users
Exemplo n.º 20
0
    def test_allow_user_to_see_their_own(self):
        self.client.logout()
        attr = self.user_profile_attr.copy()
        attr['phone'] = '+2555837295789'
        user = User(username='******', email='*****@*****.**')
        user.group = None
        user.set_password('weak_password')
        attr['user'] = user
        profile = UserProfile(**attr)
        profile.photo.put(open(settings.PROJECT_ROOT + '/../dms/tests/test.jpg', 'rb'), content_type='image/content_type')
        profile.save()
        self.client.login(username='******', password='******')

        response = self.client.get(self.PROFILE_IMAGE_ENDPOINT + str(profile.id) + '/')
        self.assertEquals(response.status_code, 200)
Exemplo n.º 21
0
    def setUp(self):
        self.user = self.login_user()
        self.district = Location(**dict(name='Kampala', type='district', parent=None))
        self.district.save()
        self.disaster_type = DisasterType(**dict(name="Fire", description="Fire"))
        self.disaster_type.save()
        self.disaster_type2 = DisasterType(**dict(name="Flood", description="Flood"))
        self.disaster_type2.save()
        self.disaster_to_post = dict(name=str(self.disaster_type.id), locations=[str(self.district.id)],
                                     description="Big Flood", date="2014-12-01 00:00:00", status="Assessment")
        self.disaster = dict(name=self.disaster_type, locations=[self.district],
                             description="Big Flood", date="2014-12-01 00:00:00", status="Assessment")

        self.mobile_user = UserProfile(**dict(name='timothy', phone="+256775019449",
                                             location=self.district, email=None)).save()
        self.cao_group, created = Group.objects.get_or_create(name='CAO')
    def test_should_update_a_single_user(self):
        attr = self.mobile_user.copy()
        attr['email'] = '*****@*****.**'
        attr['phone'] = '+256775019500'
        attr['user'] = User(username='******', password='******').save()
        profile = UserProfile(**attr).save()
        response = self.client.post(self.API_ENDPOINT + str(profile.id) + '/', self.mobile_user_to_post)

        profile.reload()
        profiles = UserProfile.objects()
        self.assertEqual(1, profiles.count())

        self.assertEqual(200, response.status_code)
        self.assertEqual(self.mobile_user_to_post['name'], profile.name)
        self.assertEqual(self.mobile_user_to_post['phone'], profile.phone)
        self.assertEqual(self.mobile_user_to_post['email'], profile.email)
    def test_should_post_a_mobile_user(self):
        response = self.client.post(self.API_ENDPOINT,
                                    data=self.mobile_user_to_post)
        self.assertEqual(201, response.status_code)

        retrieved_user = UserProfile.objects(name='tim')
        self.assertEqual(1, retrieved_user.count())
    def test_should_get_ordered_list_of_users(self):
        mob_users = [('aa', '+256775019441'), ('zz', '+256775019442'),
                     ('tim', '+256775019443'), ('abu', '+256775019444')]
        for user_name, mob in mob_users:
            new_dict = dict_replace('name', user_name, self.mobile_user)
            new_dict = dict_replace('phone', mob, new_dict)
            UserProfile(**new_dict).save()
            time.sleep(1)
        response = self.client.get(self.API_ENDPOINT, format='json')

        self.assertEqual(200, response.status_code)
        self.assertEqual(len(mob_users), len(response.data))
        self.assertEqual(response.data[0]['name'], 'abu')
        self.assertEqual(response.data[3]['name'], 'aa')

        #post order by name
        response = self.client.get(self.API_ENDPOINT + '?ordering=name',
                                   format='json')
        self.assertEqual(200, response.status_code)
        self.assertEqual(response.data[0]['name'], 'aa')
        self.assertEqual(response.data[1]['name'], 'abu')
        self.assertEqual(response.data[2]['name'], 'tim')
        self.assertEqual(response.data[3]['name'], 'zz')

        #post order by name desc
        response = self.client.get(self.API_ENDPOINT + '?ordering=-name',
                                   format='json')
        self.assertEqual(200, response.status_code)
        self.assertEqual(response.data[0]['name'], 'zz')
        self.assertEqual(response.data[1]['name'], 'tim')
        self.assertEqual(response.data[2]['name'], 'abu')
        self.assertEqual(response.data[3]['name'], 'aa')
Exemplo n.º 25
0
    def test_location_filter_should_return_messages_in_all_children_location_and_in_order(self):
        Disaster.objects.delete() #Remove all disasters to avoid interference with this test
        bukoto_message = RapidProMessage(**self.message).save()
        wakiso = Location(**(dict(name='Wakiso', type='village', parent=self.district))).save()
        other_phone_number = '1234'
        one_hour_later_date = self.date_time + datetime.timedelta(hours=1)
        one_hour_later_date = one_hour_later_date.replace(tzinfo=pytz.utc)
        other_message_options = dict(phone_no=other_phone_number, text=self.text_format % wakiso.name, received_at=one_hour_later_date,
                                     relayer_id=234, run_id=23243)
        user_profile = UserProfile(**dict(name='timothy', phone=other_phone_number, location=wakiso)).save()
        wakiso_message = RapidProMessage(**other_message_options).save()

        response = self.client.get(self.API_ENDPOINT, {"location": self.district.id, "format": "json"})

        wakiso_expected_message = {'phone': other_phone_number, 'time': one_hour_later_date, 'relayer': 234, 'run': 23243,
                                   'text': self.text_format % wakiso.name, 'disaster': None}
        wakiso_expected_message = dict(wakiso_expected_message.items() + {
            'source': user_profile.name,
            'id': str(wakiso_message.id),
            'location': str(wakiso),
            'profile_id': str(user_profile.id),
            'auto_associated': False}.items())

        bukoto_expected_message = dict(self.expected_message.items() + {
            'source': self.mobile_user.name,
            'id': str(bukoto_message.id),
            'disaster': None,
            'location': str(self.village),
            'profile_id': str(self.mobile_user.id),
            'auto_associated': False}.items())

        self.assertEqual(200, response.status_code)
        self.assertEqual(2, len(response.data))
        self.assertEqual(wakiso_expected_message, response.data[0])
        self.assertEqual(bukoto_expected_message, response.data[1])
    def test_should_return_csv_when_csv_endpoint_is_called(self):
        self.mobile_user['email'] = '*****@*****.**'
        UserProfile(**self.mobile_user).save()
        UserProfile(**self.masaka_user).save()
        response = self.client.get(self.CSV_ENDPOINT, format='csv')

        expected_response = "name,phone,email,district,subcounty\r\n" \
                            "timothy,+256775019449,[email protected],%s,%s" % (self.district.name,'')
        expected_response = expected_response + "\r\nMunamasaka,+256775019441,[email protected],%s,%s" % (
            self.masaka.name, self.subcounty.name)

        self.assertEqual(200, response.status_code)
        self.assertEqual(2, len(response.data))
        self.assertTrue(isinstance(response.accepted_renderer, CSVRenderer))
        self.assertEqual(collections.Counter(split_text(expected_response)),
                         collections.Counter(split_text(response.content)))
    def test_should_update_a_single_user(self):
        attr = self.mobile_user.copy()
        attr['email'] = '*****@*****.**'
        attr['phone'] = '+256775019500'
        attr['user'] = User(username='******', password='******').save()
        profile = UserProfile(**attr).save()
        response = self.client.post(self.API_ENDPOINT + str(profile.id) + '/',
                                    self.mobile_user_to_post)

        profile.reload()
        profiles = UserProfile.objects()
        self.assertEqual(1, profiles.count())

        self.assertEqual(200, response.status_code)
        self.assertEqual(self.mobile_user_to_post['name'], profile.name)
        self.assertEqual(self.mobile_user_to_post['phone'], profile.phone)
        self.assertEqual(self.mobile_user_to_post['email'], profile.email)
Exemplo n.º 28
0
 def test_should_handle_existing_profile(self):
     UserProfile(phone='N/A',
                 name='Admin',
                 location=self.kampala,
                 email='*****@*****.**').save()
     FakeCommand().handle()
     self.assertEqual(1, User.objects().count())
     user = User.objects().first()
     user_profile = UserProfile.objects().first()
     self.assertEqual('admin', user.username)
     self.assertTrue(check_password('password', user.password))
     self.assertNotEqual('password', user.password)
     self.assertEqual('*****@*****.**', user_profile.email)
     self.assertEqual(self.kampala, user_profile.location)
     self.assertEqual('N/A', user_profile.phone)
     self.assertEqual('Admin', user_profile.name)
     self.assertEqual('Administrator', user_profile.user.group.name)
Exemplo n.º 29
0
 def test_password_change_notification_sends_email(self, mock_send_mail):
     message = "Andrew http://necoc.org.ug [email protected]"
     profile = UserProfile(name='Andrew', email='*****@*****.**')
     UserProfileService(profile).notify_password_change()
     mock_send_mail.assert_called_with('Your NECOC Account',
                                       message,
                                       "*****@*****.**",
                                       ['*****@*****.**'])
Exemplo n.º 30
0
 def post_save(self, obj, created=True):
     locations = self.get_location(obj)
     phone_numbers = list(UserProfile.objects(location__in=locations).values_list('phone'))
     if obj.ptype == 'yesno':
         text = '%s Reply With: NECOCPoll YES/NO' % obj.question
     else:
         text = '%s Reply With: NECOCPoll %s ...' % (obj.question, obj.keyword)
     send_bulk_sms.delay(obj, phone_numbers, text)
    def test_handling_photo_update_exception(self):
        attr = self.mobile_user_to_post.copy()
        attr['email'] = '*****@*****.**'
        attr['phone'] = '+256775019511'
        attr['user'] = User(username='******', password='******').save()
        profile = UserProfile(**attr)
        user_photo = open(settings.PROJECT_ROOT + '/../dms/tests/test.jpg', 'rb')
        profile.photo.put(user_photo, content_type='image/content_type')
        profile.save()

        with open(settings.PROJECT_ROOT + '/../dms/tests/test2.jpg', 'rb') as test_image:
            attr['file'] = test_image
            response = self.client.post(self.API_ENDPOINT + str(profile.id) + '/', attr)
            self.assertEqual(200, response.status_code)

        retrieved_user = User.objects(username='******').first()
        reloaded_profile = UserProfile.objects(user=retrieved_user).first()
        self.assertEqual(reloaded_profile.photo.read(), None)
Exemplo n.º 32
0
 def get_non_children_queryset(self):
     fields = Location._fields_ordered
     query_params = {key: value or None for key, value in self.request.GET.items() if key in fields}
     user_profile = UserProfile.objects(user=self.request.user).first()
     user_group = self.request.user.group.name
     if user_profile and user_group in getattr(settings, "DISTRICT_GROUPS", []):
         user_locations = get_user_district_locations(self.request.user)
         query_params.update({"id__in": user_locations})
     return Location.objects(**query_params)
Exemplo n.º 33
0
 def setUp(self):
     self.district = Location(**dict(name='Kampala', type='district', parent=None))
     self.district.save()
     self.user_profile_attr = dict(name='timothy', phone='+256775019449', location=self.district, email=None)
     self.profile = UserProfile(**self.user_profile_attr)
     self.profile.photo.put(open(settings.PROJECT_ROOT + '/../dms/tests/test.jpg', 'rb'), content_type='image/content_type')
     self.profile.save()
     self.client = Client()
     self.login_user()
Exemplo n.º 34
0
 def _mobile_user(self):
     char_index = settings.NUMBER_OF_CHARS_IN_PHONE_NUMBER
     try:
         if len(self.phone_no) > char_index:
             mobile_user = UserProfile.objects.get(phone__endswith=self.phone_no[-1*char_index:len(self.phone_no)])
         else:
             mobile_user = UserProfile.objects.get(phone=self.phone_no)
         return mobile_user
     except MultipleObjectsReturned:
         if len(self.phone_no) > char_index:
             mobile_user = UserProfile.objects(phone__endswith=self.phone_no[-1*char_index:len(self.phone_no)]).first()
         else:
             mobile_user = UserProfile.objects(phone=self.phone_no).first()
         return mobile_user
     except DoesNotExist:
         return None
     except TypeError:
         return None
Exemplo n.º 35
0
 def test_new_password_is_sent_in_email(self, mock_send_mail, mock_make_password):
     message = "Andrew http://necoc.org.ug andrew blabla"
     mock_make_password.return_value = 'blabla'
     profile = UserProfile(name='Andrew', email='*****@*****.**')
     group = Group.objects().first()
     UserProfileService(profile).setup_new_user('andrew', str(group.id))
     mock_send_mail.assert_called_with('Your NECOC Account',
                                       message,
                                       settings.DEFAULT_FROM_EMAIL,
                                       ['*****@*****.**'])
Exemplo n.º 36
0
    def test_serializing_group_name(self):
        mobile_user_attr = self.mobile_user.copy()
        group = Group.objects().first()
        mobile_user_attr['user'] = User(username='******',
                                        password='******',
                                        group=group).save()
        mobile_user = UserProfile(**mobile_user_attr).save()

        serialized_object = UserProfileSerializer(mobile_user)
        self.assertEqual(str(group.id), serialized_object.data['group'])
Exemplo n.º 37
0
 def post_save(self, obj, created=True):
     locations = self.get_location(obj)
     phone_numbers = list(
         UserProfile.objects(location__in=locations).values_list('phone'))
     if obj.ptype == 'yesno':
         text = '%s Reply With: NECOCPoll YES/NO' % obj.question
     else:
         text = '%s Reply With: NECOCPoll %s ...' % (obj.question,
                                                     obj.keyword)
     send_bulk_sms.delay(obj, phone_numbers, text)
Exemplo n.º 38
0
 def test_should_save_photo_of_user(self):
     user_profile_attr = dict(name='timothy',
                              phone='+256775019449',
                              location=self.district,
                              email=None)
     profile = UserProfile(**user_profile_attr)
     user_photo = open(settings.PROJECT_ROOT + '/../dms/tests/test.jpg',
                       'rb')
     profile.photo.put(user_photo, content_type='image/content_type')
     profile.save()
     reloaded_profile = UserProfile.objects(id=profile.id).first()
     self.assertEqual(
         reloaded_profile.photo.read(),
         open(settings.PROJECT_ROOT + '/../dms/tests/test.jpg',
              'rb').read())
     self.assertEqual(reloaded_profile.photo.content_type,
                      'image/content_type')
     self.assertEqual(reloaded_profile.photo_uri(),
                      '/api/v1/photo/' + str(reloaded_profile.id))
Exemplo n.º 39
0
    def handle(self, *args, **options):
        if not len(args):
            user = User.objects(username='******').first() or User(username='******').save()
            user.group = Group.objects(name='Administrator').first()
            user.set_password('password')
            location = Location.objects(type='district').first() or Location(name='Kampala', type='district').save()
            profile = UserProfile.objects(phone='N/A').first() or UserProfile(phone='N/A', name='Admin', location=location, email='*****@*****.**').save()
            profile.user = user
            profile.save()
        else:
            user = User.objects(username=args[0]).first() or User(username=args[0]).save()
            user.group = Group.objects(name='Administrator').first()
            user.set_password(args[1])
            location = Location.objects(name=args[4]).first() or Location(name=args[4], type='district').save()
            profile = UserProfile.objects(phone=args[5]).first() or UserProfile(phone=args[5], name=args[3], location=location, email=args[2]).save().save()
            profile.user = user
            profile.save()

        self.stdout.write('Successfully created superuser')
Exemplo n.º 40
0
class ProfileImageViewTest(MongoAPITestCase):

    PROFILE_IMAGE_ENDPOINT = '/api/v1/photo/'

    def setUp(self):
        self.district = Location(**dict(name='Kampala', type='district', parent=None))
        self.district.save()
        self.user_profile_attr = dict(name='timothy', phone='+256775019449', location=self.district, email=None)
        self.profile = UserProfile(**self.user_profile_attr)
        self.profile.photo.put(open(settings.PROJECT_ROOT + '/../dms/tests/test.jpg', 'rb'), content_type='image/content_type')
        self.profile.save()
        self.client = Client()
        self.login_user()

    def test_successfully_retrieve_profile_image(self):
        response = self.client.get(self.PROFILE_IMAGE_ENDPOINT + str(self.profile.id) + '/')
        self.assertEqual(200, response.status_code)
        self.assertEqual(open(settings.PROJECT_ROOT + '/../dms/tests/test.jpg', 'rb').read(), response.content)

    def test_not_permitted_to_view_profile(self):
        self.assert_permission_required_for_get(self.PROFILE_IMAGE_ENDPOINT + str(self.profile.id) + '/')

    def test_no_image_found(self):
        response = self.client.get(self.PROFILE_IMAGE_ENDPOINT + 'j34ks34344df234/')
        self.assertEqual(200, response.status_code)
        self.assertEqual(open(settings.PROJECT_ROOT + '/../dms/client/app/img/default_profile.jpg', 'rb').read(), response.content)

    def test_allow_user_to_see_their_own(self):
        self.client.logout()
        attr = self.user_profile_attr.copy()
        attr['phone'] = '+2555837295789'
        user = User(username='******', email='*****@*****.**')
        user.group = None
        user.set_password('weak_password')
        attr['user'] = user
        profile = UserProfile(**attr)
        profile.photo.put(open(settings.PROJECT_ROOT + '/../dms/tests/test.jpg', 'rb'), content_type='image/content_type')
        profile.save()
        self.client.login(username='******', password='******')

        response = self.client.get(self.PROFILE_IMAGE_ENDPOINT + str(profile.id) + '/')
        self.assertEquals(response.status_code, 200)
Exemplo n.º 41
0
    def test_only_username_is_serialized_if_user_profile_has_a_user(self):
        mobile_user_attr = self.mobile_user.copy()
        mobile_user_attr['user'] = User(username='******',
                                        password='******').save()
        mobile_user = UserProfile(**mobile_user_attr).save()

        serialized_object = UserProfileSerializer(mobile_user)
        self.assertDictContainsSubset(self.serialized_mobile_user,
                                      serialized_object.data)
        self.assertEqual('cage', serialized_object.data['username'])
        self.assertFalse('user' in serialized_object.data.keys())
 def test_raise_403_given_user_is_trying_to_access_some_other_users_profile(
         self):
     attr = self.mobile_user.copy()
     attr['email'] = '*****@*****.**'
     attr['phone'] = '+256775029500'
     attr['user'] = User(username='******', password='******').save()
     profile = UserProfile(**attr).save()
     self.assert_permission_required_for_get(self.API_ENDPOINT +
                                             str(profile.id) + '/')
     self.assert_permission_required_for_post(self.API_ENDPOINT +
                                              str(profile.id) + '/')
Exemplo n.º 43
0
def get_user_district_locations(user):
        """ Returns a list of locations in a user's district"""
        profile = UserProfile.objects(user=user).first()
        if profile and profile.location:
            if profile.location.type == 'district':
                district = profile.location
            else:
                district = profile.location.parent
            if district:
                return [str(district.id)] + [str(l.id) for l in district.children()]
        return []
Exemplo n.º 44
0
def _mobile_user(phone):
    char_index = settings.NUMBER_OF_CHARS_IN_PHONE_NUMBER
    try:
        if len(phone) > char_index:
            mobile_user = UserProfile.objects.get(
                phone__endswith=phone[-1 * char_index:len(phone)])
        else:
            mobile_user = UserProfile.objects.get(phone=phone)
        return mobile_user
    except MultipleObjectsReturned:
        if len(phone) > char_index:
            mobile_user = UserProfile.objects(
                phone__endswith=phone[-1 * char_index:len(phone)]).first()
        else:
            mobile_user = UserProfile.objects(phone=phone).first()
        return mobile_user
    except DoesNotExist:
        return None
    except TypeError:
        return None
    def test_should_bulk_save_streamed_csv_user_profiles(self):
        dup_user = self.masaka_user.copy()
        dup_user['name'] = 'AnotherMasakarian'
        UserProfile(**dup_user).save()
        self.assertEqual(dup_user['name'], UserProfile.objects(**dup_user).first().name)
        dup_user['name'] = 'NamedChanged'
        bulk_mobile_users = [
            {
                "name":"%s" % self.masaka_user['name'],
                "phone":"%s" % self.masaka_user['phone'],
                "email": "%s" % self.masaka_user['email'],
                "district": "%s" % self.masaka.name,
                "subcounty": "%s" % self.subcounty.name,
             },
            {
                "name":"%s" % self.mobile_user['name'],
                "phone":"%s" % self.mobile_user['phone'],
                "email": None,
                "district": "%s" % self.district.name,
                "subcounty": "%s" % '',
             },
            {
                "name":"%s" % dup_user['name'],
                "phone":"%s" % dup_user['phone'],
                "email": "%s" % dup_user['email'],
                "district": "%s" % self.masaka.name,
                "subcounty": "%s" % self.subcounty.name,
             },
        ]

        response = self.client.post(self.BULK_ENDPOINT, bulk_mobile_users, format='json')

        self.assertEqual(2, UserProfile.objects.count())
        response = UserProfile.objects(**self.masaka_user)
        self.assertEqual(0, response.count())
        response = UserProfile.objects(**dup_user)
        self.assertEqual(1, response.count())
        self.assertEqual(dup_user['name'], UserProfile.objects(**dup_user).first().name)
        self.mobile_user['email']="" #empty string is not equal to None
        response = UserProfile.objects(**self.mobile_user)
        self.assertEqual(1, response.count())
    def test_post_with_non_empty_username_creates_system_user(self):
        attr = self.mobile_user_to_post.copy()
        attr['username'] = '******'
        response = self.client.post(self.API_ENDPOINT, data=attr)
        self.assertEqual(201, response.status_code)

        retrieved_user_profile = UserProfile.objects(name='tim')
        self.assertEqual(1, retrieved_user_profile.count())

        retrieved_user = User.objects(username='******')
        self.assertEqual(1, retrieved_user.count())
        self.assertEqual(retrieved_user.first(), retrieved_user_profile.first().user)
    def test_post_with_photo_file(self):
        attr = self.mobile_user_to_post.copy()
        attr['username'] = '******'

        with open(settings.PROJECT_ROOT + '/../dms/tests/test.jpg', 'rb') as test_image:
            attr['file'] = test_image
            response = self.client.post(self.API_ENDPOINT, data=attr)

        self.assertEqual(201, response.status_code)

        retrieved_user = User.objects(username='******').first()
        reloaded_profile = UserProfile.objects(user=retrieved_user).first()
        self.assertEqual(reloaded_profile.photo.read(), None)
Exemplo n.º 48
0
def get_user_district_coordinates(user):
        """ Returns a list of a users location coordinates"""
        profile = UserProfile.objects(user=user).first()
        if profile and profile.location:
            if profile.location.type == 'district':
                district = profile.location
            else:
                district = profile.location.parent
            if district:
                return district.latlong
            else:
                return []
        return []
Exemplo n.º 49
0
 def test_should_create_default_superuser(self):
     FakeCommand().handle()
     self.assertEqual(1, User.objects().count())
     user = User.objects().first()
     user_profile = UserProfile.objects().first()
     self.assertEqual('admin', user.username)
     self.assertTrue(check_password('password', user.password))
     self.assertNotEqual('password', user.password)
     self.assertEqual('*****@*****.**', user_profile.email)
     self.assertEqual(self.kampala, user_profile.location)
     self.assertEqual('N/A', user_profile.phone)
     self.assertEqual('Admin', user_profile.name)
     self.assertEqual('Administrator', user_profile.user.group.name)
Exemplo n.º 50
0
 def test_should_handle_existing_profile(self):
     UserProfile(phone='N/A', name='Admin', location=self.kampala, email='*****@*****.**').save()
     FakeCommand().handle()
     self.assertEqual(1, User.objects().count())
     user = User.objects().first()
     user_profile = UserProfile.objects().first()
     self.assertEqual('admin', user.username)
     self.assertTrue(check_password('password', user.password))
     self.assertNotEqual('password', user.password)
     self.assertEqual('*****@*****.**', user_profile.email)
     self.assertEqual(self.kampala, user_profile.location)
     self.assertEqual('N/A', user_profile.phone)
     self.assertEqual('Admin', user_profile.name)
     self.assertEqual('Administrator', user_profile.user.group.name)
Exemplo n.º 51
0
    def get_queryset(self):
        query_params = Disaster.map_kwargs_to_db_params(self.request.GET.dict())

        location_queried = self.request.GET.get("location", None)
        if not location_queried:
            if self.request.user.has_perm("dms.can_view_disasters"):
                user_profile = UserProfile.objects(user=self.request.user).first()
                user_group = self.request.user.group.name
                if user_profile and user_group in getattr(settings, "DISTRICT_GROUPS", []):
                    user_locations = get_user_district_locations(self.request.user)
                    query_params.update({"locations__in": user_locations})
                else:
                    if not self.request.user.has_perm("dms.can_manage_disasters"):
                        user_location = user_profile.location.id
                        query_params.update({"locations__in": [user_location]})

        return Disaster.objects(**query_params)
Exemplo n.º 52
0
 def test_should_create_super_user_from_args(self):
     FakeCommand().handle('new_admin',
                          'new_password',
                          '*****@*****.**',
                          'NewAdmin',
                          'Kampala',
                          '1234567890')
     self.assertEqual(1, User.objects().count())
     user = User.objects().first()
     user_profile = UserProfile.objects().first()
     self.assertEqual('new_admin', user.username)
     self.assertTrue(check_password('new_password', user.password))
     self.assertNotEqual('new_password', user.password)
     self.assertEqual('*****@*****.**', user_profile.email)
     self.assertEqual(self.kampala, user_profile.location)
     self.assertEqual('1234567890', user_profile.phone)
     self.assertEqual('NewAdmin', user_profile.name)
     self.assertEqual('Administrator', user_profile.user.group.name)
Exemplo n.º 53
0
    def post(self, request, *args, **kwargs):
        if request.POST.get('resetPass', None):
            form = PasswordForm(request.POST)
            if form.is_valid():
                user = User.objects(username=form.cleaned_data['username'],
                                    email=form.cleaned_data['email']).first()
                profile = UserProfile.objects(user=user).first()
                if user:
                    name = profile.name if profile else 'DMS User'
                    phone = profile.phone if profile else ''
                    subject = 'NECOC Password Reset Request'
                    from_email = settings.DEFAULT_FROM_EMAIL
                    hostname = settings.HOSTNAME
                    admin_email = settings.ADMIN_EMAIL
                    password = UserManager().make_random_password()
                    user.set_password(password)
                    user.save()

                    message = settings.RESET_PASSWORD_MESSAGE % {
                        'name': name,
                        'hostname': hostname,
                        'password': password,
                        'admin_email': admin_email}
                    recipient_list = [user.email]
                    send_email.delay(subject, message, from_email, recipient_list)
                    if phone and getattr(settings, 'SENDSMS_ON_PASSWORD_RESET', False):
                        text = 'Your NECOC password has been reset to %s' % password
                        send_one_sms.delay(None, phone, text)
                else:
                    form.add_error(None, 'No user with matching Username and Email')
            else:
                form.add_error(None, 'Invalid data')
            return render(request, 'login.html', {'form': form})
        else:
            login_form = LoginForm(request.POST)
            if login_form.is_valid():
                user = authenticate(username=(login_form.cleaned_data['username']),
                                    password=(login_form.cleaned_data['password']))
                if user:
                    login(request, user)
                    return redirect('/')
                login_form.add_error(None, 'Username or Password is invalid')
            return render(request, 'login.html', {'login_form': login_form})
Exemplo n.º 54
0
    def get_queryset(self):
        queryset = self._non_location_queried_messages()
        location_queried = self.request.GET.get('location', None)

        if not location_queried:
            if self.request.user.has_perm('dms.can_view_messages') and \
                    not self.request.user.has_perm('dms.can_manage_messages'):
                user_profile = UserProfile.objects(user=self.request.user).first()
                if user_profile:
                    location_queried = user_profile.location.id

        if location_queried:
            location = Location.objects(id=location_queried).first()
            queryset = RapidProMessage.from_(location, _queryset=queryset)

        disaster_type = self.request.GET.get('disaster_type', None)
        if disaster_type:
            queryset = self.query_by_disaster_type(disaster_type, queryset)

        return queryset.order_by('-received_at')
    def test_update_with_group_associates_user_to_new_group(self):
        attr = self.mobile_user_to_post.copy()
        attr['username'] = '******'
        group = Group.objects().first()
        attr['group'] = str(group.id)
        self.client.post(self.API_ENDPOINT, data=attr)

        retrieved_user = User.objects(username='******').first()
        retrieved_user_profile = UserProfile.objects(user=retrieved_user).first()
        new_group = Group.objects().all()[2]

        new_attr = self.mobile_user_to_post.copy()
        new_attr['username'] = '******'
        new_attr['location'] = str(new_attr['location'])
        new_attr['group'] = str(new_group.id)
        new_attr['id'] = str(retrieved_user_profile.id)

        url = self.API_ENDPOINT + str(retrieved_user_profile.id) + '/'
        response = self.client.post(url,
                                    data=new_attr)
        self.assertEqual(200, response.status_code)
        retrieved_user = User.objects(username='******').first()
        self.assertEqual(new_group, retrieved_user.group)
Exemplo n.º 56
0
def get_profile_id(user):
    profile = UserProfile.objects(user=user).first()
    return profile.id if profile else ''