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_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 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')
Exemple #4
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
Exemple #5
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
    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_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))
 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())
Exemple #9
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_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())
Exemple #11
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
 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)
    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')
Exemple #14
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 _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_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 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 []
    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 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 []
    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)
Exemple #21
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)
 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)
    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 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)
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 []
    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)
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 []
    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)
 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)
Exemple #30
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 for user: %s has been reset to %s' % (
                            user.username, 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})
Exemple #31
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)
    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_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)
Exemple #34
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)
    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)
    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)
 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)
 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))
Exemple #39
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})
    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')
Exemple #41
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')
Exemple #42
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)
    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)
    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)
Exemple #45
0
def get_profile_id(user):
    profile = UserProfile.objects(user=user).first()
    return profile.id if profile else ''
Exemple #46
0
 def get_location_id(self, user):
     profile = UserProfile.objects(user=user).first()
     return profile.location.id if profile else ''
Exemple #47
0
 def has_permission(self, request, view):
     profile = UserProfile.objects(user=request.user).first()
     return profile is not None and str(profile.id) in request.path
 def has_permission(self, request, view):
     profile = UserProfile.objects(user=request.user).first()
     return profile is not None and str(profile.id) in request.path
Exemple #49
0
def get_profile_id(user):
    profile = UserProfile.objects(user=user).first()
    return profile.id if profile else ''
    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_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())
Exemple #52
0
def get_location_id(user):
    profile = UserProfile.objects(user=user).first()
    return profile.location.id if profile else ''