예제 #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_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))
예제 #3
0
파일: base.py 프로젝트: unicefuganda/necoc
 def login_with_permission(self, permission_codename):
     self.client.logout()
     ct = ContentType(app_label='dms', model=str(uuid.uuid4()), name=str(uuid.uuid4())).save()
     permission = Permission(name=permission_codename, codename=permission_codename, content_type=ct.id).save()
     group = Group(name=str(uuid.uuid4()), permissions=[permission]).save()
     user = User(username='******', group=group)
     user.set_password('pw')
     self.client.login(username='******', password='******')
예제 #4
0
    def handle(self, *args, **options):
        if len(args):
            user = User.objects(username=args[0], email=args[2]).first() or User(username=args[0], email=args[2])
            if len(args) > 3:
                ct = ContentType(app_label='dms', model=str(uuid.uuid4()), name=str(uuid.uuid4())).save()
                permission = Permission(name=args[3], codename=args[3], content_type=ct.id).save()
                group = Group(name=str(uuid.uuid4()), permissions=[permission]).save()
                user.group = group

            user.set_password(args[1])

            self.stdout.write('Successfully created user')
예제 #5
0
 def login_with_permission(self, permission_codename):
     self.client.logout()
     ct = ContentType(app_label='dms',
                      model=str(uuid.uuid4()),
                      name=str(uuid.uuid4())).save()
     permission = Permission(name=permission_codename,
                             codename=permission_codename,
                             content_type=ct.id).save()
     group = Group(name=str(uuid.uuid4()), permissions=[permission]).save()
     user = User(username='******', group=group)
     user.set_password('pw')
     self.client.login(username='******', password='******')
def _post_with_basic_auth(api_endpoint, data_dict):
    api_url = settings.HOSTNAME + api_endpoint
    data = json.dumps(data_dict)
    payload = {'username': '******', 'password': settings.API_USER_PASS}
    api_user = User.objects.order_by('-id').first()
    if api_user is None:
        api_user = User(**dict(username=payload['username'], is_active=True)).save()
        api_user.set_password(payload['password'])
        basic_auth_key = _basic_auth_header(payload['username'], payload['password'])
    else:
        basic_auth_key = _basic_auth_header(api_user.username, settings.API_USER_PASS)

    return requests.post(api_url, data, \
                         headers={'Authorization': basic_auth_key, 'content-type': 'application/json'})
예제 #7
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)
예제 #8
0
 def setUp(self):
     user_attrs = dict(username="******",
                       first_name="NavaL",
                       last_name="Andria",
                       email="*****@*****.**",
                       password="******")
     self.user = User(**user_attrs).save()
    def test_not_raising_403_if_user_only_wants_access_to_their_profile(self):
        self.client.logout()
        attr = self.mobile_user.copy()
        attr['email'] = '*****@*****.**'
        attr['phone'] = '+256775029500'
        user = User(username='******', email='*****@*****.**')
        user.group = None
        user.set_password('hahahah')
        attr['user'] = user
        profile = UserProfile(**attr).save()
        self.client.login(username='******', password='******')

        response = self.client.get(self.API_ENDPOINT + str(profile.id) + '/')
        self.assertEquals(response.status_code, 200)
        response = self.client.post(self.API_ENDPOINT + str(profile.id) + '/')
        self.assertEquals(response.status_code, 200)
    def test_not_raising_403_if_user_only_wants_access_to_their_profile(self):
        self.client.logout()
        attr = self.mobile_user.copy()
        attr['email'] = '*****@*****.**'
        attr['phone'] = '+256775029500'
        user = User(username='******', email='*****@*****.**')
        user.group = None
        user.set_password('hahahah')
        attr['user'] = user
        profile = UserProfile(**attr).save()
        self.client.login(username='******', password='******')

        response = self.client.get(self.API_ENDPOINT + str(profile.id) + '/')
        self.assertEquals(response.status_code, 200)
        response = self.client.post(self.API_ENDPOINT + str(profile.id) + '/')
        self.assertEquals(response.status_code, 200)
예제 #11
0
def _post_with_basic_auth(api_endpoint, data_dict):
    api_url = settings.HOSTNAME + api_endpoint
    data = json.dumps(data_dict)
    payload = {'username': '******', 'password': settings.API_USER_PASS}
    api_user = User.objects.order_by('-id').first()
    if api_user is None:
        api_user = User(
            **dict(username=payload['username'], is_active=True)).save()
        api_user.set_password(payload['password'])
        basic_auth_key = _basic_auth_header(payload['username'],
                                            payload['password'])
    else:
        basic_auth_key = _basic_auth_header(api_user.username,
                                            settings.API_USER_PASS)

    return requests.post(api_url, data, \
                         headers={'Authorization': basic_auth_key, 'content-type': 'application/json'})
예제 #12
0
def _post_with_token_auth(api_endpoint, data_dict):
    api_url = settings.HOSTNAME + api_endpoint
    payload = {'username': '******', 'password': settings.API_USER_PASS}
    api_user = User.objects.order_by('-id').first()
    if api_user is None:
        api_user = User(**dict(username=payload['username'], is_active=True)).save()
        api_user.set_password(payload['password'])

        token, created = Token.objects.get_or_create(user=api_user)
    else:
        try:
            token = Token.objects.get(user=api_user)
        except DoesNotExist:
            token, created = Token.objects.get_or_create(user=api_user)

    return requests.post(api_url, json.dumps(data_dict), \
                  headers={'Authorization': 'Token %s' % token.key, 'content-type': 'application/json'})
예제 #13
0
def _post_with_token_auth(api_endpoint, data_dict):
    api_url = settings.HOSTNAME + api_endpoint
    payload = {'username': '******', 'password': settings.API_USER_PASS}
    api_user = User.objects.order_by('-id').first()
    if api_user is None:
        api_user = User(
            **dict(username=payload['username'], is_active=True)).save()
        api_user.set_password(payload['password'])

        token, created = Token.objects.get_or_create(user=api_user)
    else:
        try:
            token = Token.objects.get(user=api_user)
        except DoesNotExist:
            token, created = Token.objects.get_or_create(user=api_user)

    return requests.post(api_url, json.dumps(data_dict), \
                  headers={'Authorization': 'Token %s' % token.key, 'content-type': 'application/json'})
    def test_user_can_only_change_their_password(self):
        attr = self.mobile_user_attr.copy()
        del attr['user']
        profile = UserProfile(**attr).save()
        response = self.client.post(self.API_ENDPOINT + str(profile.id) + '/password/', self.password_data)
        users = User.objects(username=self.user.username)

        self.assertEqual(403, response.status_code)
        self.assertTrue(users.first().check_password(self.password_data['old_password']))
    def test_user_must_be_logged_in_to_change_their_password(self):
        profile = UserProfile(**(self.mobile_user_attr.copy())).save()

        self.client.logout()
        response = self.client.post(self.API_ENDPOINT + str(profile.id) + '/password/', self.password_data)

        users = User.objects(username=self.user.username)
        self.assertEqual(403, response.status_code)
        self.assertTrue(users.first().check_password(self.password_data['old_password']))
예제 #16
0
 def test_should_reset_password_of_user(self):
     profile = UserProfile(**self.mobile_user_attr).save()
     response = self.client.post(self.API_ENDPOINT + str(profile.id) +
                                 '/password_reset/')
     self.assertEqual(200, response.status_code)
     self.assertEqual({}, response.data)
     self.assertFalse(
         (User.objects(username=self.user.username)).first().check_password(
             self.initial_password))
    def test_post_with_group_associates_user_to_group(self):
        attr = self.mobile_user_to_post.copy()
        attr['username'] = '******'
        group = Group.objects().first()
        attr['group'] = str(group.id)
        response = self.client.post(self.API_ENDPOINT, data=attr)
        self.assertEqual(201, response.status_code)

        retrieved_user = User.objects(username='******').first()
        self.assertEqual(group, retrieved_user.group)
예제 #18
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())
예제 #19
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')
예제 #20
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'])
    def test_post_with_group_associates_user_to_group(self):
        attr = self.mobile_user_to_post.copy()
        attr['username'] = '******'
        group = Group.objects().first()
        attr['group'] = str(group.id)
        response = self.client.post(self.API_ENDPOINT, data=attr)
        self.assertEqual(201, response.status_code)

        retrieved_user = User.objects(username='******').first()
        self.assertEqual(group, retrieved_user.group)
 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) + '/')
예제 #23
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())
예제 #24
0
    def test_mapping_user_id_to_user_profile(self):
        user = User(username='******').save()
        location = Location(name='Kampala', type='district').save()

        profile = UserProfile(phone='N/A',
                              name='Admin',
                              location=location,
                              user=user,
                              email='*****@*****.**').save()

        self.assertEqual(profile.id, get_profile_id(user))
예제 #25
0
    def test_user_must_be_logged_in_to_change_their_password(self):
        profile = UserProfile(**(self.mobile_user_attr.copy())).save()

        self.client.logout()
        response = self.client.post(
            self.API_ENDPOINT + str(profile.id) + '/password/',
            self.password_data)

        users = User.objects(username=self.user.username)
        self.assertEqual(403, response.status_code)
        self.assertTrue(users.first().check_password(
            self.password_data['old_password']))
예제 #26
0
    def test_user_can_only_change_their_password(self):
        attr = self.mobile_user_attr.copy()
        del attr['user']
        profile = UserProfile(**attr).save()
        response = self.client.post(
            self.API_ENDPOINT + str(profile.id) + '/password/',
            self.password_data)
        users = User.objects(username=self.user.username)

        self.assertEqual(403, response.status_code)
        self.assertTrue(users.first().check_password(
            self.password_data['old_password']))
예제 #27
0
    def test_saving_a_system_user(self):
        user = User(username='******', password='******').save()
        user_profile_attr = dict(name='timothy',
                                 phone='+256775019449',
                                 location=self.district,
                                 email=None,
                                 user=user)

        UserProfile(**user_profile_attr).save()

        self.assertEqual(user,
                         UserProfile.objects.get(**user_profile_attr).user)
예제 #28
0
 def setup_new_user(self, username, group_id):
     user = User(username=username, group=group_id).save()
     password = self.set_new_password(user)
     message = self._build_new_user_email_message(username, password)
     send_email.delay('Your NECOC Account', message,
                      settings.DEFAULT_FROM_EMAIL, [self.profile.email])
     if self.profile.phone and getattr(settings,
                                       'SENDSMS_ON_PASSWORD_RESET', False):
         text = 'Your NECOC password for user: %s has been set to %s' % (
             username, password)
         send_one_sms.delay(None, self.profile.phone, text)
     return user
    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_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)
    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)
    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)
예제 #35
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})
    def test_should_update_password_of_user(self):
        profile = UserProfile(**self.mobile_user_attr).save()
        response = self.client.post(self.API_ENDPOINT + str(profile.id) + '/password/', self.password_data)

        profiles = UserProfile.objects()
        users = User.objects(username=self.user.username)

        self.assertEqual(200, response.status_code)
        self.assertEqual({}, response.data)
        self.assertEqual(1, profiles.count())
        self.assertEqual(1, users.count())
        self.assertTrue(users.first().check_password(self.password_data['new_password']))

        response = self.client.login(username=self.user.username, password=self.password_data['new_password'])
        self.assertTrue(response)
    def test_should_get_a_single_user(self):
        attr = self.mobile_user.copy()
        user = User(username='******', password='******').save()
        attr['user'] = user
        profile = UserProfile(**attr).save()

        response = self.client.get(self.API_ENDPOINT + str(profile.id) + '/')

        self.assertEqual(200, response.status_code)
        self.assertEqual(self.mobile_user['name'], response.data['name'])
        self.assertEqual(self.mobile_user['phone'], response.data['phone'])
        self.assertEqual(self.mobile_user['email'], response.data['email'])
        self.assertEqual(self.district.name, response.data['location']['name'])
        self.assertEqual('cage', response.data['username'])
        self.assertEqual(str(user.id), response.data['user_id'])
    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_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)
예제 #40
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})
예제 #41
0
    def test_should_update_password_of_user(self):
        profile = UserProfile(**self.mobile_user_attr).save()
        response = self.client.post(
            self.API_ENDPOINT + str(profile.id) + '/password/',
            self.password_data)

        profiles = UserProfile.objects()
        users = User.objects(username=self.user.username)

        self.assertEqual(200, response.status_code)
        self.assertEqual({}, response.data)
        self.assertEqual(1, profiles.count())
        self.assertEqual(1, users.count())
        self.assertTrue(users.first().check_password(
            self.password_data['new_password']))

        response = self.client.login(
            username=self.user.username,
            password=self.password_data['new_password'])
        self.assertTrue(response)
예제 #42
0
 def login_without_permissions(self):
     self.client.logout()
     empty_group = Group(name='Empty', permissions=[])
     User(username='******', password='******', group=empty_group)
     self.client.login(username='******', password='******')
 def test_should_reset_password_of_user(self):
     profile = UserProfile(**self.mobile_user_attr).save()
     response = self.client.post(self.API_ENDPOINT + str(profile.id) + '/password_reset/')
     self.assertEqual(200, response.status_code)
     self.assertEqual({}, response.data)
     self.assertFalse((User.objects(username=self.user.username)).first().check_password(self.initial_password))
예제 #44
0
 def validate_username(self, attrs, source):
     username = attrs.get(source)
     updated_value = not (self.object and username == self.object.username())
     self.__check_uniqueness(attrs, 'username', User.objects(username=username), updated_value)
     return attrs
예제 #45
0
 def test_serializer_should_be_invalid_if_username_is_not_unique(self):
     User(username='******', password='******').save()
     self.serialized_mobile_user['location'] = self.district.id
     self.serialized_mobile_user['username'] = '******'
     serializer = UserProfileSerializer(data=self.serialized_mobile_user)
     self.assertFalse(serializer.is_valid())
 def setUp(self):
     self.user = User(username='******')
     self.user.set_password('hehe')
     self.password_data = dict(old_password='******',
                               new_password='******',
                               confirm_password='******')
class PasswordChangeSerializerTest(MongoTestCase):
    def setUp(self):
        self.user = User(username='******')
        self.user.set_password('hehe')
        self.password_data = dict(old_password='******',
                                  new_password='******',
                                  confirm_password='******')

    def test_serialize_should_show_nothing(self):
        serializer = UserPasswordChangeSerializer(self.user,
                                                  data=self.password_data)
        self.assertEqual({}, serializer.data)

    def test_should_deserialize_user_object(self):
        serializer = UserPasswordChangeSerializer(self.user,
                                                  data=self.password_data)

        self.assertTrue(serializer.is_valid())
        saved_user = serializer.save()

        self.assertTrue(isinstance(saved_user, User))
        self.assertTrue(
            saved_user.check_password(self.password_data['new_password']))

    def test_serializer_should_be_invalid_if_current_password_does_not_match(
            self):
        data = self.password_data.copy()
        data['old_password'] = '******'
        serializer = UserPasswordChangeSerializer(self.user, data=data)

        self.assertFalse(serializer.is_valid())
        self.assertEqual(['Current password incorrect.'],
                         serializer.errors['old_password'])

    def test_serializer_should_be_invalid_if_new_password_and_confirm_password_do_not_match(
            self):
        data = self.password_data.copy()
        data['confirm_password'] = '******'
        serializer = UserPasswordChangeSerializer(self.user, data=data)

        self.assertFalse(serializer.is_valid())
        self.assertEqual(["The two password fields didn't match."],
                         serializer.errors['confirm_password'])

    def test_new_password_is_required(self):
        data = self.password_data.copy()
        data['new_password'] = ''
        serializer = UserPasswordChangeSerializer(self.user, data=data)

        self.assertFalse(serializer.is_valid())
        self.assertEqual(['This field is required.'],
                         serializer.errors['new_password'])

        del data['new_password']
        serializer = UserPasswordChangeSerializer(self.user, data=data)

        self.assertFalse(serializer.is_valid())
        self.assertEqual(['This field is required.'],
                         serializer.errors['new_password'])

    def test_confirm_password_is_required(self):
        data = self.password_data.copy()
        data['confirm_password'] = ''
        serializer = UserPasswordChangeSerializer(self.user, data=data)

        self.assertFalse(serializer.is_valid())
        self.assertEqual(['This field is required.'],
                         serializer.errors['confirm_password'])

        del data['confirm_password']
        serializer = UserPasswordChangeSerializer(self.user, data=data)

        self.assertFalse(serializer.is_valid())
        self.assertEqual(['This field is required.'],
                         serializer.errors['confirm_password'])
 def setUp(self):
     self.user = User(username='******')
     self.user.set_password('hehe')
     self.password_data = dict(old_password='******', new_password='******', confirm_password='******')
class PasswordChangeSerializerTest(MongoTestCase):
    def setUp(self):
        self.user = User(username='******')
        self.user.set_password('hehe')
        self.password_data = dict(old_password='******', new_password='******', confirm_password='******')

    def test_serialize_should_show_nothing(self):
        serializer = UserPasswordChangeSerializer(self.user, data=self.password_data)
        self.assertEqual({}, serializer.data)

    def test_should_deserialize_user_object(self):
        serializer = UserPasswordChangeSerializer(self.user, data=self.password_data)

        self.assertTrue(serializer.is_valid())
        saved_user = serializer.save()

        self.assertTrue(isinstance(saved_user, User))
        self.assertTrue(saved_user.check_password(self.password_data['new_password']))

    def test_serializer_should_be_invalid_if_current_password_does_not_match(self):
        data = self.password_data.copy()
        data['old_password'] = '******'
        serializer = UserPasswordChangeSerializer(self.user, data=data)

        self.assertFalse(serializer.is_valid())
        self.assertEqual(['Current password incorrect.'], serializer.errors['old_password'])

    def test_serializer_should_be_invalid_if_new_password_and_confirm_password_do_not_match(self):
        data = self.password_data.copy()
        data['confirm_password'] = '******'
        serializer = UserPasswordChangeSerializer(self.user, data=data)

        self.assertFalse(serializer.is_valid())
        self.assertEqual(["The two password fields didn't match."], serializer.errors['confirm_password'])

    def test_new_password_is_required(self):
        data = self.password_data.copy()
        data['new_password'] = ''
        serializer = UserPasswordChangeSerializer(self.user, data=data)

        self.assertFalse(serializer.is_valid())
        self.assertEqual(['This field is required.'], serializer.errors['new_password'])

        del data['new_password']
        serializer = UserPasswordChangeSerializer(self.user, data=data)

        self.assertFalse(serializer.is_valid())
        self.assertEqual(['This field is required.'], serializer.errors['new_password'])

    def test_confirm_password_is_required(self):
        data = self.password_data.copy()
        data['confirm_password'] = ''
        serializer = UserPasswordChangeSerializer(self.user, data=data)

        self.assertFalse(serializer.is_valid())
        self.assertEqual(['This field is required.'], serializer.errors['confirm_password'])

        del data['confirm_password']
        serializer = UserPasswordChangeSerializer(self.user, data=data)

        self.assertFalse(serializer.is_valid())
        self.assertEqual(['This field is required.'], serializer.errors['confirm_password'])