Пример #1
0
 def test_toggle_toggles_user_status(self):
     self.request.user = User.get(User.username == 'admin')
     self.request.context = User.get(User.username == 'manager')
     self.assertEqual(User.get(User.username == 'manager').active, True)
     response = self.views.toggle_status()
     user = User.get(User.username == 'manager')
     self.assertEqual(user.active, False)
     self.assertIsInstance(response, HTTPFound)
     self.assertEqual(response.location,
                      self.request.route_url('users', traverse=()))
Пример #2
0
 def test_edit_user_post(self):
     user = User.get(User.username == 'admin')
     self.request.context = user
     self.request.method = 'POST'
     self.request.POST = MultiDict([('group', 'sm'),
                                    ('municipality_id', '2')])
     response = self.views.edit()
     user = User.get(User.username == 'admin')
     self.assertEqual(user.group, 'sm')
     self.assertEqual(user.municipality_id, '2')
     self.assertIsInstance(response, HTTPFound)
     self.assertEqual(
         response.location,
         self.request.route_url('users', traverse=(user.id, 'edit')))
Пример #3
0
def group_finder(user_id, request):
    from composting.models.user import User
    try:
        user = User.get(User.id == user_id)
    except NoResultFound:
        return None
    else:
        municipality_id = user.municipality_id

        effective_principals = []

        # determine the user's permissions and extend effective_principals
        # with the those
        permissions = GROUP_PERMISSIONS.get(user.group, [])

        # if the user has municipality-edit permissions and also belongs to a
        # municipality, add a 'p:municipality-edit:1' permission
        if municipality_id is not None:
            permissions = [
                p.format(municipality_id)
                for p in GROUP_PERMISSIONS.get(user.group, [])
            ]

        effective_principals.extend(permissions)

        return effective_principals
Пример #4
0
 def test_toggle_doenst_allow_deactivating_own_account(self):
     user = User.get(User.username == 'admin')
     self.request.user = user
     self.request.context = user
     response = self.views.toggle_status()
     self.assertIsInstance(response, HTTPFound)
     self.assertEqual(response.location,
                      self.request.route_url('users', traverse=()))
Пример #5
0
    def setup_test_data(self):

        admin = User(id=1,
                     username='******',
                     password='******',
                     active=True,
                     group='nema')
        municipality = Municipality(name="Mukono")
        other_municipality = Municipality(name="Jinja")
        manager = User(id=2,
                       username='******',
                       password='******',
                       active=True,
                       group='sm',
                       municipality=municipality)
        other_manager = User(id=3,
                             username='******',
                             password='******',
                             active=True,
                             group='sm',
                             municipality=other_municipality)
        skip_a = Skip(municipality=municipality,
                      skip_type='A',
                      small_length=20,
                      large_length=30,
                      small_breadth=10,
                      large_breadth=16)
        skip_b = Skip(municipality=municipality,
                      skip_type='B',
                      small_length=20,
                      large_length=30,
                      small_breadth=10,
                      large_breadth=16)
        submission_handler_manager.clear()
        hook_submission_handlers()
        with transaction.manager:
            DBSession.add_all(
                [admin, manager, municipality, skip_a, skip_b, other_manager])
            for status, raw_json in self.submissions:
                json_payload = json.loads(raw_json)
                handler_class = submission_handler_manager.find_handler(
                    json_payload)
                handler_class().__call__(json_payload, status=status)
Пример #6
0
    def test_create_profile_post(self):
        initial_count = Municipality.count()
        self.request.method = 'POST'
        self.request.user = User()
        self.request.POST = MultiDict([
            ('name', 'Arua Compost Plant'),
            ('wheelbarrow_volume', '0.15'),
            ('box_volume', '0.3'),
            ('leachete_tank_length', '8.0'),
            ('leachete_tank_width', '8.0')
        ])
        result = self.views.create_profile()

        self.assertIsInstance(result, HTTPFound)

        final_count = Municipality.count()
        self.assertEqual(final_count, initial_count + 1)
Пример #7
0
def sign_in(request):
    if request.method == 'POST':
        username = request.POST.get('username')
        password = request.POST.get('password')
        try:
            user = User.get(User.username == username)
        except NoResultFound:
            # we're still here set the error message
            request.session.flash(u"Invalid username or password", 'error')
        else:
            if user.active is False:
                # we're still here set the error message
                request.session.flash(
                    u"Inactive account, please contact your supervisor",
                    'error')
            elif user.check_password(password):
                headers = remember(request, user.id)
                return HTTPFound(
                    request.route_url(
                        'municipalities', traverse=()), headers=headers)
            else:
                # we're still here set the error message
                request.session.flash(u"Invalid username or password", 'error')
    return {}
Пример #8
0
 def test_update(self):
     user = User.get(User.username == 'admin')
     user.update(group='sm', municipality_id=1, active=True)
     self.assertEqual(user.group, 'sm')
     self.assertEqual(user.municipality_id, 1)
     self.assertEqual(user.active, True)
Пример #9
0
 def test_update_when_wb_or_nema(self):
     user = User.get(User.username == 'manager')
     user.update(group='nema', municipality_id=1, active=True)
     self.assertIsNone(user.municipality_id)
Пример #10
0
def main(argv=sys.argv):
    if len(argv) != 2:
        usage(argv)
    config_uri = argv[1]
    setup_logging(config_uri)

    settings = get_appsettings(config_uri)
    engine = engine_from_config(settings, 'sqlalchemy.')
    DBSession.configure(bind=engine)

    Base.metadata.create_all(engine)

    setup_logging(config_uri)

    pwd_context.load_path(config_uri)

    # create models here
    admin = User(username='******', password='******', active=True,
                 group='nema')
    municipality = Municipality(name="Mukono")
    manager = User(username='******', password='******',
                   active=True, group='sm', municipality=municipality)
    skip_a = Skip(municipality=municipality, skip_type='A', small_length=20,
                  large_length=30, small_breadth=10, large_breadth=16)

    # add dummy site reports
    site_report_1 = SiteReport(
        report_date=datetime.date(2014, 6, 1),
        municipality=municipality,
        report_json={
            'volume_of_msw_processed': 400,
            'density_of_msw': 0.5,
            'quantity_of_msw_processed': 550,
            'num_trucks_delivered_msw': 20,
            'volume_of_mature_compost': 500,
            'density_of_mature_compost': 3.5,
            'conversion_factor_mature_to_sieved': 0.145,
            'quantity_of_compost_produced': 351,
            'quantity_of_compost_sold': 405,
            'vehicle_count': 15,
            'average_distance': 20,
            'volume_of_rejects_from_sieving': 500,
            'density_of_rejects_from_sieving': 450,
            'quantity_of_rejects_from_sieving_landfilled': 2.4,
            'total_windrow_samples': 14,
            'low_windrow_sample_count': 5,
            'fuel_consumption': 40,
            'electricity_consumption': 150,
            'leachete_volume_accumulated': 200})

    site_report_2 = SiteReport(
        report_date=datetime.date(2014, 4, 1),
        municipality=municipality,
        report_json={
            'volume_of_msw_processed': 300,
            'density_of_msw': 0.7,
            'quantity_of_msw_processed': 500,
            'num_trucks_delivered_msw': 15,
            'volume_of_mature_compost': 470,
            'density_of_mature_compost': 2.5,
            'conversion_factor_mature_to_sieved': 0.13,
            'quantity_of_compost_produced': 300,
            'quantity_of_compost_sold': 285,
            'vehicle_count': 12,
            'average_distance': 17,
            'volume_of_rejects_from_sieving': 130,
            'density_of_rejects_from_sieving': 150,
            'quantity_of_rejects_from_sieving_landfilled': 1.4,
            'total_windrow_samples': 14,
            'low_windrow_sample_count': 3,
            'fuel_consumption': 28,
            'electricity_consumption': 140,
            'leachete_volume_accumulated': 170})

    site_report_3 = SiteReport(
        report_date=datetime.date(2014, 5, 1),
        municipality=municipality,
        report_json={
            'volume_of_msw_processed': 200,
            'density_of_msw': 3,
            'quantity_of_msw_processed': 250,
            'num_trucks_delivered_msw': 10,
            'volume_of_mature_compost': 300,
            'density_of_mature_compost': 1.5,
            'conversion_factor_mature_to_sieved': 0.125,
            'quantity_of_compost_produced': 251,
            'quantity_of_compost_sold': 200,
            'vehicle_count': 9,
            'average_distance': 17,
            'volume_of_rejects_from_sieving': 300,
            'density_of_rejects_from_sieving': 175,
            'quantity_of_rejects_from_sieving_landfilled': 2,
            'total_windrow_samples': 10,
            'low_windrow_sample_count': 3,
            'fuel_consumption': 18,
            'electricity_consumption': 110,
            'leachete_volume_accumulated': 140})

    submission_handler_manager.clear()
    hook_submission_handlers()

    with transaction.manager:
        admin.save()
        municipality.save()
        manager.save()
        skip_a.save()
        site_report_1.save()
        site_report_2.save()
        site_report_3.save()

        for status, raw_json in TestBase.submissions:
            json_payload = json.loads(raw_json)
            handler_class = submission_handler_manager.find_handler(
                json_payload)
            handler_class().__call__(json_payload, status=status)
Пример #11
0
 def test_list_when_has_not_list_permission_and_has_no_municipality(self):
     self.request.user = User()
     self.config.testing_securitypolicy(userid='manager', permissive=False)
     result = self.views.list()
     self.assertIsInstance(result, HTTPForbidden)
Пример #12
0
 def list(self):
     users = User.all()
     return {'users': users}
Пример #13
0
def get_request_user(request):
    user_id = authenticated_userid(request)
    try:
        return User.get(User.id == user_id)
    except NoResultFound:
        return None
Пример #14
0
 def test_edit_when_municipality_user(self):
     user = User.get(User.username == 'manager')
     url = self.request.route_path('users', traverse=(user.id, 'edit'))
     headers = self._login_user(2)
     self.testapp.get(url, headers=headers, status=403)
Пример #15
0
def oauth_callback(request):
    # check if we have `error` in our params, meaning user canceled
    if 'error' in request.GET:
        # redirect to login page with an alert
        request.session.flash(
            u"You must select authorize to continue", 'error')
        return HTTPFound(request.route_url('oauth', action='sign-in'))

    # TODO: validate the `oauth_state` session
    base_url = request.registry.settings['oauth_base_url']
    state = request.GET.get('state')
    client_id = request.registry.settings['oauth_client_id']
    client_secret = request.registry.settings['oauth_secret']
    token_url = "{base_url}{path}".format(
        base_url=base_url,
        path=request.registry.settings['oauth_token_path'])
    redirect_uri = request.route_url('oauth', action='callback')

    session = OAuth2Session(
        client_id,
        state=state,
        redirect_uri=redirect_uri)
    code = request.GET.get('code')
    token = session.fetch_token(
        token_url,
        client_secret=client_secret,
        code=code)

    # retrieve username and store in db if it doesnt exist yet
    user_api_url = "{base_url}{path}".format(
        base_url=base_url,
        path=request.registry.settings['oauth_user_api_path'])
    response = session.request('GET', user_api_url)
    try:
        user_data = json.loads(response.text)
    except ValueError:
        # couldn't decode json
        pass
    else:
        refresh_token = token['refresh_token']
        try:
            user = User.get_or_create_from_api(user_data)
        except ValueError:
            pass
        else:
            request.session['oauth_token'] = json.dumps(token)

            # check if user's account is active
            if user.active:
                # login user
                headers = remember(request, user.id)
                # TODO: redirect to `came_from` url
                return HTTPFound(
                    request.route_url(
                        'municipalities', traverse=()), headers=headers)
            else:
                request.session.flash(
                    "Your account has been created, please contact your"
                    " administrator to activate it",
                    'error')
                # TODO: redirect to `came_from` url
                return HTTPFound(
                    request.route_url(
                        'oauth', action='sign-in'))

    request.session.flash(
        u"Failed to login, please try again", 'error')
    return HTTPFound(
        request.route_url('oauth', action='sign-in'))