Exemplo n.º 1
0
    def render(self):
        from datetime import datetime
        today = datetime.now()
        end_date = datetime(today.year, 10, 31)

        previsions = Request.get_previsions(self.session, end_date)

        users_per_id = dict([(user.id, user)
                             for user in User.find(self.session)])

        settings = self.request.registry.settings
        use_ldap = False
        if 'pyvac.use_ldap' in settings:
            use_ldap = asbool(settings.get('pyvac.use_ldap'))

        user_attr = {}
        users_teams = {}
        if use_ldap:
            # synchronise user groups/roles
            User.sync_ldap_info(self.session)
            ldap = LdapCache()
            user_attr = ldap.get_users_units()
            users_teams = {}
            for team, members in list(ldap.list_teams().items()):
                for member in members:
                    users_teams.setdefault(member, []).append(team)

        return {'users_per_id': users_per_id,
                'use_ldap': use_ldap,
                'ldap_info': user_attr,
                'users_teams': users_teams,
                'previsions': previsions,
                'today': today,
                'end_date': end_date,
                }
Exemplo n.º 2
0
    def render(self):

        settings = self.request.registry.settings
        use_ldap = False
        if 'pyvac.use_ldap' in settings:
            use_ldap = asbool(settings.get('pyvac.use_ldap'))

        user_attr = {}
        users_teams = {}
        active_users = []
        if use_ldap:
            # synchronise user groups/roles
            User.sync_ldap_info(self.session)
            ldap = LdapCache()

            user_attr = ldap.get_users_units()
            users_teams = {}
            for team, members in ldap.list_teams().iteritems():
                for member in members:
                    users_teams.setdefault(member, []).append(team)

            active_users = ldap.list_active_users()

        return {
            u'user_count': User.find(self.session, count=True),
            u'users': User.find(self.session, order_by=[User.dn]),
            'use_ldap': use_ldap,
            'ldap_info': user_attr,
            'users_teams': users_teams,
            'active_users': active_users,
        }
Exemplo n.º 3
0
    def render(self):
        # synchronise user groups/roles
        User.sync_ldap_info(self.session)
        ldap = LdapCache()
        users_entity = {}
        for team, members in list(ldap.list_teams().items()):
            for member in members:
                users_entity.setdefault(member, []).append(team)

        # keep only managed users for managers
        # use all users for admin
        overviews = {}
        if self.user.is_admin or self.user.has_feature('squad_overview_full'):
            for _, target_squad in list(self.squad_leaders.items()):
                squad_stats = self.get_squad_stats(target_squad, users_entity)
                overviews.update({target_squad: squad_stats})
        elif self.user.is_manager:
            # retrieve logged squad leader
            target_squad = self.squad_leaders[self.user.login]
            squad_stats = self.get_squad_stats(target_squad, users_entity)
            overviews = {target_squad: squad_stats}
        else:
            return HTTPFound(location=route_url('home', self.request))

        return {'users_entity': users_entity, 'overviews': overviews}
Exemplo n.º 4
0
    def render(self):

        settings = self.request.registry.settings
        use_ldap = False
        if 'pyvac.use_ldap' in settings:
            use_ldap = asbool(settings.get('pyvac.use_ldap'))

        user_attr = {}
        users_teams = {}
        if use_ldap:
            # synchronise user groups/roles
            User.sync_ldap_info(self.session)
            ldap = LdapCache()
            user_attr = ldap.get_users_units()
            users_teams = {}
            for team, members in ldap.list_teams().iteritems():
                for member in members:
                    users_teams.setdefault(member, []).append(team)

        return {u'user_count': User.find(self.session, count=True),
                u'users': User.find(self.session, order_by=[User.dn]),
                'use_ldap': use_ldap,
                'ldap_info': user_attr,
                'users_teams': users_teams,
                }
Exemplo n.º 5
0
 def test_get_rtt_usage(self):
     from pyvac.models import User
     user = User.by_login(self.session, 'jdoe')
     self.assertIsInstance(user, User)
     self.assertEqual(user.login, 'jdoe')
     self.assertEqual(user.name, 'John Doe')
     self.assertEqual(user.role, 'user')
     with freeze_time(
             '2014-12-25',
             ignore=['celery', 'psycopg2', 'sqlalchemy', 'icalendar']):
         with patch('pyvac.models.User.arrival_date',
                    new_callable=PropertyMock) as mock_foo:
             mock_foo.return_value = datetime(2014, 1, 1)
             expected = {
                 'allowed': 10,
                 'left': 9.5,
                 'state': 'warning',
                 'taken': 0.5,
                 'year': 2014
             }
             self.assertEqual(user.get_rtt_usage(self.session), expected)
             # no RTT for us country
             user = User.by_login(self.session, 'manager3')
             self.assertIsInstance(user, User)
             self.assertEqual(user.country, 'us')
             self.assertIsNone(user.get_rtt_usage(self.session))
Exemplo n.º 6
0
    def render(self):
        from datetime import datetime
        today = datetime.now()
        end_date = datetime(today.year, 10, 31)

        previsions = Request.get_previsions(self.session, end_date)

        users_per_id = dict([(user.id, user)
                             for user in User.find(self.session)])

        settings = self.request.registry.settings
        use_ldap = False
        if 'pyvac.use_ldap' in settings:
            use_ldap = asbool(settings.get('pyvac.use_ldap'))

        user_attr = {}
        users_teams = {}
        if use_ldap:
            # synchronise user groups/roles
            User.sync_ldap_info(self.session)
            ldap = LdapCache()
            user_attr = ldap.get_users_units()
            users_teams = {}
            for team, members in ldap.list_teams().iteritems():
                for member in members:
                    users_teams.setdefault(member, []).append(team)

        return {'users_per_id': users_per_id,
                'use_ldap': use_ldap,
                'ldap_info': user_attr,
                'users_teams': users_teams,
                'previsions': previsions,
                'today': today,
                'end_date': end_date,
                }
Exemplo n.º 7
0
    def render(self):
        # keep only managed users for managers
        # use all users for admin
        overviews = {}
        extra_managers = []
        # check if admin user is also a manager
        if User.managed_users(self.session, self.user):
            extra_managers = [self.user]
        if self.user.is_admin or self.user.has_feature('squad_overview_full'):
            for manager in extra_managers + User.by_role(
                    self.session, 'manager'):  # noqa
                # retrieve logged leader squad
                users_entity = User.managed_users(self.session, manager)
                target_manager = manager.login.replace('.', '_')
                manager_stats = self.get_manager_stats(users_entity)
                if not manager_stats:
                    continue
                overviews.update({target_manager: manager_stats})
        elif self.user.is_manager:
            # retrieve logged leader squad
            users_entity = User.managed_users(self.session, self.user)
            target_manager = self.user.login.replace('.', '_')
            manager_stats = self.get_manager_stats(users_entity)
            if manager_stats:
                overviews = {target_manager: manager_stats}
        else:
            return HTTPFound(location=route_url('home', self.request))

        return {'users_entity': users_entity, 'overviews': overviews}
Exemplo n.º 8
0
    def render(self):
        user = User.by_id(self.session,
                          int(self.request.matchdict['user_id']))

        if self.user.has_no_role:
            # can only see own requests
            if user.id != self.user.id:
                return HTTPFound(location=route_url('list_request',
                                                    self.request))

        if self.user.is_manager:
            # can only see own requests and managed user requests
            if ((user.id != self.user.id)
                    and (user.manager_id != self.user.id)):
                return HTTPFound(location=route_url('list_request',
                                                    self.request))

        today = datetime.now()
        year = int(self.request.params.get('year', today.year))

        start = datetime(2014, 5, 1)
        years = [item for item in reversed(range(start.year, today.year + 1))]

        pool_history = User.get_rtt_history(self.session, user, year)

        return {'user': user, 'year': year, 'years': years,
                'pool_history': pool_history}
Exemplo n.º 9
0
    def render(self):
        # synchronise user groups/roles
        User.sync_ldap_info(self.session)
        ldap = LdapCache()
        users_entity = {}
        for chapter, members in ldap.list_chapters().iteritems():
            for member in members:
                users_entity.setdefault(member, []).append(chapter)

        # keep only managed users for managers
        # use all users for admin
        overviews = {}
        if self.user.is_admin or self.user.has_feature(
                'chapter_overview_full'):  # noqa
            for _, target_chapter in self.chapter_leaders.items():
                chapter_stats = self.get_chapter_stats(target_chapter,
                                                       users_entity)  # noqa
                overviews.update({target_chapter: chapter_stats})
        elif self.user.is_manager:
            # retrieve logged chapter leader
            target_chapter = self.chapter_leaders[self.user.login]
            chapter_stats = self.get_chapter_stats(target_chapter,
                                                   users_entity)  # noqa
            overviews = {target_chapter: chapter_stats}
        else:
            return HTTPFound(location=route_url('home', self.request))

        return {'users_entity': users_entity, 'overviews': overviews}
Exemplo n.º 10
0
    def test_cp_validate_request(self):
        from pyvac.models import CPVacation, User

        date_start = datetime.now() - relativedelta(months=3)
        date_end = datetime.now() + relativedelta(months=3)
        with patch('pyvac.models.User.arrival_date',
                   new_callable=PropertyMock) as mock_foo:
            mock_foo.return_value = datetime.now() - relativedelta(months=7)
            with patch('pyvac.models.User.pool',
                       new_callable=PropertyMock) as mock_foo:
                mocked_pool1 = mock_pool(12.48, date_start, date_end)
                mocked_pool2 = mock_pool(0, date_start, date_end)
                mock_foo.return_value = {
                    'CP acquis': mocked_pool1,
                    'CP restant': mocked_pool2
                }

                user = User.by_login(self.session, 'jdoe')
                self.assertIsInstance(user, User)
                cp_pool = user.pool.get('CP acquis')
                self.assertTrue(cp_pool)
                cp_pool = user.pool.get('CP restant')
                self.assertTrue(cp_pool)

                days = 3
                date_from = datetime.now()
                date_to = datetime.now() + relativedelta(days=3)
                err = CPVacation.validate_request(user, None, days, date_from,
                                                  date_to)
                self.assertEqual(err, None)

        with patch('pyvac.models.User.arrival_date',
                   new_callable=PropertyMock) as mock_foo:
            mock_foo.return_value = datetime.now() - relativedelta(months=7)
            with patch('pyvac.models.User.pool',
                       new_callable=PropertyMock) as mock_foo:
                mocked_pool1 = mock_pool(12.48, date_start, date_end)
                mocked_pool2 = mock_pool(0, date_start, date_end)
                mock_foo.return_value = {
                    'CP acquis': mocked_pool1,
                    'CP restant': mocked_pool2
                }

                user = User.by_login(self.session, 'jdoe')
                self.assertIsInstance(user, User)
                cp_pool = user.pool.get('CP acquis')
                self.assertTrue(cp_pool)
                cp_pool = user.pool.get('CP restant')
                self.assertTrue(cp_pool)

                days = 3
                date_from = datetime.now().replace(year=datetime.now().year +
                                                   2)  # noqa
                date_to = date_from + relativedelta(days=3)
                err = CPVacation.validate_request(user, None, days, date_from,
                                                  date_to)
                msg = 'CP can only be used until %s.' % user.pool[
                    'CP acquis'].date_end.strftime('%d/%m/%Y')  # noqa
                self.assertEqual(err, msg)
Exemplo n.º 11
0
 def test_by_country(self):
     from pyvac.models import User
     country_id = 1
     users = User.by_country(self.session, country_id)
     self.assertEqual(len(users), 5)
     country_id = 3
     users = User.by_country(self.session, country_id)
     self.assertEqual(len(users), 1)
Exemplo n.º 12
0
 def test_by_country(self):
     from pyvac.models import User
     country_id = 1
     users = User.by_country(self.session, country_id)
     self.assertEqual(len(users), 5)
     country_id = 3
     users = User.by_country(self.session, country_id)
     self.assertEqual(len(users), 1)
Exemplo n.º 13
0
    def render(self):
        if self.user and not self.user.is_admin:
            return HTTPFound(location=route_url('home', self.request))

        country = Countries.by_name(self.session, self.user.country)
        users = User.by_country(self.session, country.id)

        today = datetime.now()
        data = []
        rtt_usage = {}
        cp_usage = {}
        for user in users:
            if self.user.country == 'fr':
                rtts = user.get_rtt_usage(self.session)
                if rtts:
                    rtt_usage[user.login] = rtts['left']

            cps = user.get_cp_usage(self.session, today=today, taken_end=today)
            total = 0
            if cps:
                total = cps['restant']['left'] + cps['acquis']['left']
                if self.user.country == 'fr':
                    total = total + cps['n_1']['left'] + cps.get(
                        'extra', {}).get('left', 0)  # noqa
            cp_usage[user.login] = total
            if self.user.country == 'fr':
                if user.login not in self.ignore_users:
                    data.append('%s,%s,%s,%s' % (
                        user.login,
                        rtt_usage.get(user.login, 0),
                        cps.get('extra', {}).get('left', 0)
                        if cps else 0,  # noqa
                        cps['restant']['left'] if cps else 0,
                    ))

        if data:
            # sort list by name
            data = sorted(data)
            header = ('%s,%s,%s,%s' % ('Login', 'RTT', 'CP N-1', 'CP N'))
            data.insert(0, header)

        ret = {
            u'user_count': User.find(self.session, count=True),
            u'users': users,
            u'today': today,
            u'cp_usage': cp_usage,
            u'exported': '\n'.join(data)
        }

        if self.user.country == 'fr':
            ret['rtt_usage'] = rtt_usage

        return ret
Exemplo n.º 14
0
    def test_get_rtt_taken_year(self):
        from pyvac.models import User
        user = User.by_login(self.session, u'jdoe')
        self.assertIsInstance(user, User)
        self.assertEqual(user.login, u'jdoe')
        self.assertEqual(user.name, u'John Doe')
        self.assertEqual(user.role, u'user')

        self.assertEqual(user.get_rtt_taken_year(self.session, 2014), 0.5)
        # no RTT for us country
        user = User.by_login(self.session, u'manager3')
        self.assertIsInstance(user, User)
        self.assertEqual(user.country, u'us')
        self.assertEqual(user.get_rtt_taken_year(self.session, 2014), 0)
Exemplo n.º 15
0
    def get_old_history(self, user, today, year):
        """Retrieve pool history using epoch recomputing."""
        pool_history = {}
        pool_history['RTT'] = User.get_rtt_history(self.session, user, year)

        if today.year > year:
            if user.country == 'lu':
                today = datetime(year, 12, 31)
            else:
                today = datetime(year, 5, 31)

        history, restant = User.get_cp_history(self.session, user, year, today)

        vac_class = user.get_cp_class(self.session)

        cp_history = []
        pool_acquis = 0
        pool_restant = 0
        for idx, entry in enumerate(history):
            if idx == 0:
                pool_restant = restant[entry['date']]

            if entry['value'] < 0:
                if user.country == 'lu':
                    pool_restant, pool_acquis = vac_class.consume(
                        taken=entry['value'],
                        restant=pool_restant,
                        acquis=pool_acquis)
                else:
                    _, pool_restant, pool_acquis, _ = vac_class.consume(
                        taken=entry['value'],
                        restant=pool_restant,
                        acquis=pool_acquis,
                        n_1=0,
                        extra=0)
            else:
                pool_acquis = pool_acquis + entry['value']

            item = {
                'date': entry['date'],
                'value': entry['value'],
                'restant': pool_restant,
                'acquis': pool_acquis,
                'flavor': entry.get('flavor', ''),
            }
            cp_history.append(item)

        pool_history['CP'] = cp_history

        return pool_history
Exemplo n.º 16
0
    def test_get_rtt_taken_year(self):
        from pyvac.models import User
        user = User.by_login(self.session, u'jdoe')
        self.assertIsInstance(user, User)
        self.assertEqual(user.login, u'jdoe')
        self.assertEqual(user.name, u'John Doe')
        self.assertEqual(user.role, u'user')

        self.assertEqual(user.get_rtt_taken_year(self.session, 2014), 0.5)
        # no RTT for us country
        user = User.by_login(self.session, u'manager3')
        self.assertIsInstance(user, User)
        self.assertEqual(user.country, u'us')
        self.assertEqual(user.get_rtt_taken_year(self.session, 2014), 0)
Exemplo n.º 17
0
 def test_by_credentials_ok(self):
     from pyvac.models import User
     user = User.by_credentials(self.session, u'jdoe', u'changeme')
     self.assertIsInstance(user, User)
     self.assertEqual(user.login, u'jdoe')
     self.assertEqual(user.name, u'John Doe')
     self.assertEqual(user.role, u'user')
Exemplo n.º 18
0
    def update_view(self, model, view):
        settings = self.request.registry.settings
        ldap = False
        if 'pyvac.use_ldap' in settings:
            ldap = asbool(settings.get('pyvac.use_ldap'))

        if view['errors']:
            self.request.session.flash('error;%s' % ','.join(view['errors']))

        view['groups'] = Group.all(self.session, order_by=Group.name)
        view['managers'] = User.by_role(self.session, 'manager')

        if ldap:
            ldap = LdapCache()
            login = self.get_model().login
            if login:
                view['ldap_user'] = ldap.search_user_by_login(login)
            else:
                view['ldap_user'] = {}
            view['managers'] = ldap.list_manager()
            view['units'] = ldap.list_ou()
            view['countries'] = Countries.all(self.session,
                                              order_by=Countries.name)
            # generate a random password for the user, he must change it later
            password = randomstring()
            log.info('temporary password generated: %s' % password)
            view['password'] = password
            view['view_name'] = self.__class__.__name__.lower()
            view['myself'] = (self.user.id == self.get_model().id)
Exemplo n.º 19
0
    def test_cp_validate_request(self):
        from pyvac.models import CPVacation, User
        user = User.by_login(self.session, u'jdoe')
        self.assertIsInstance(user, User)

        with patch('pyvac.models.User.arrival_date',
                   new_callable=PropertyMock) as mock_foo:
            mock_foo.return_value = datetime.now() - relativedelta(months=7)
            pool = user.get_cp_usage(self.session)
            days = 3
            date_from = datetime.now()
            date_to = datetime.now() + relativedelta(days=3)
            err = CPVacation.validate_request(user, pool, days,
                                              date_from, date_to)
            self.assertEqual(err, None)

        with patch('pyvac.models.User.arrival_date',
                   new_callable=PropertyMock) as mock_foo:
            mock_foo.return_value = datetime.now() - relativedelta(months=7)
            pool = user.get_cp_usage(self.session)
            days = 3
            date_from = datetime.now().replace(year=datetime.now().year + 2)
            date_to = date_from + relativedelta(days=3)
            err = CPVacation.validate_request(user, pool, days,
                                              date_from, date_to)
            msg = 'CP can only be used until 31/05/%d.' % pool['acquis']['expire'].year # noqa
            self.assertEqual(err, msg)
Exemplo n.º 20
0
    def get_data(self, session, country):
        now = datetime.now()
        th_trial, th_good = self.trial_thresholds[country]

        ldap = LdapCache()
        arrivals = ldap.list_arrivals_country(country)

        matched = []
        for user_dn, dt in list(arrivals.items()):
            if not dt:
                continue

            dt_trial_threshold = dt + relativedelta(months=th_trial)
            dt_good = dt + relativedelta(months=th_good)
            if (now > dt_trial_threshold) and not (now > dt_good):
                matched.append((user_dn, dt))

        datas = []
        for user_dn, dt in matched:
            user = User.by_dn(session, user_dn)
            if not user:
                self.log.info('user not found: %s' % user_dn)
                continue
            if user.country not in self.countries:
                continue

            data = {'user_id': user.id}
            param = json.dumps(OrderedDict(data))
            rem = CoreReminder.by_type_param(session, 'trial_threshold', param)
            if not rem:
                data['duration'] = th_trial
                data['subject'] = self.subject
                datas.append(data)

        return datas
Exemplo n.º 21
0
 def test_get_admin_by_country_full(self):
     from pyvac.models import User
     admins = User.get_admin_by_country(self.session, 'fr', full=True)
     self.assertEqual(len(admins), 1)
     admin = admins[0]
     self.assertEqual(admin.login, 'admin')
     self.assertEqual(admin.country, 'fr')
Exemplo n.º 22
0
    def test_post_send_rtt_usage_not_enough_ko(self):
        self.config.testing_securitypolicy(userid=u'janedoe',
                                           permissive=True)
        from pyvac.models import Request, User
        from pyvac.views.request import Send
        total_req = Request.find(self.session, count=True)

        def mock_get_rtt_usage(self, session):
            """ Get rrt usage for a user """
            return {'allowed': 10, 'left': 0.5, 'state': 'error',
                    'taken': 9.5, 'year': 2014}

        orig_get_rtt_usage = User.get_rtt_usage
        User.get_rtt_usage = mock_get_rtt_usage
        user = User.by_login(self.session, u'janedoe')
        rtt_data = user.get_rtt_usage(self.session)
        self.assertTrue(rtt_data)

        request = self.create_request({'days': 1,
                                       'date_from': '05/05/2015 - 05/05/2015',
                                       'type': '2',
                                       'breakdown': 'FULL',
                                       })
        view = Send(request)()
        self.assertIsRedirect(view)
        # no new requests were made
        self.assertEqual(Request.find(self.session, count=True), total_req)
        expected = ['error;You only have 0.5 RTT to use.']
        self.assertEqual(request.session.pop_flash(), expected)
        User.get_rtt_usage = orig_get_rtt_usage
Exemplo n.º 23
0
    def test_post_send_rtt_usage_empty_ok(self):
        self.config.testing_securitypolicy(userid=u'janedoe',
                                           permissive=True)
        from pyvac.models import Request, User
        from pyvac.views.request import Send
        total_req = Request.find(self.session, count=True)

        def mock_get_rtt_usage(self, session):
            """ Get rrt usage for a user """
            return

        orig_get_rtt_usage = User.get_rtt_usage
        User.get_rtt_usage = mock_get_rtt_usage
        user = User.by_login(self.session, u'janedoe')
        rtt_data = user.get_rtt_usage(self.session)
        self.assertIsNone(rtt_data)

        view = Send(self.create_request({
            'days': 1,
            'date_from': '05/05/2015 - 05/05/2015',
            'type': '2',
            'breakdown': 'AM',
        }))()
        self.assertIsRedirect(view)
        self.assertEqual(Request.find(self.session, count=True), total_req + 1)
        User.get_rtt_usage = orig_get_rtt_usage
Exemplo n.º 24
0
    def test_post_send_rtt_holiday_ok(self):
        self.config.testing_securitypolicy(userid=u'janedoe',
                                           permissive=True)
        from pyvac.models import Request, User
        from pyvac.views.request import Send

        total_req = Request.find(self.session, count=True)

        janedoe = User.by_login(self.session, u'janedoe')
        old_created_at = janedoe.created_at
        janedoe.created_at = janedoe.created_at.replace(month=1)
        janedoe.get_rtt_usage(self.session)

        with freeze_time('2016-12-01',
                         ignore=['celery', 'psycopg2', 'sqlalchemy',
                                 'icalendar']):
            request = self.create_request({
                'days': 5,
                'date_from': '11/07/2016 - 15/07/2016',
                'type': '2',
                'breakdown': 'FULL',
            })
            view = Send(request)()

        self.assertIsRedirect(view)
        self.assertEqual(Request.find(self.session, count=True), total_req + 1)
        last_req = Request.find(self.session)[-1]
        self.assertEqual(last_req.status, u'PENDING')
        self.assertEqual(last_req.days, 4.0)
        janedoe.created_at = old_created_at
        self.delete_last_req(last_req)
Exemplo n.º 25
0
    def test_post_send_rtt_year_ko(self):
        self.config.testing_securitypolicy(userid=u'janedoe',
                                           permissive=True)
        from pyvac.models import Request, User
        from pyvac.views.request import Send
        total_req = Request.find(self.session, count=True)

        with patch('pyvac.models.User.pool',
                   new_callable=PropertyMock) as mock_foo:
            mocked_pool = mock_pool(10, datetime(2015, 1, 1),
                                    datetime(2015, 12, 31))
            mock_foo.return_value = {'RTT': mocked_pool}

            user = User.by_login(self.session, u'janedoe')
            rtt_pool = user.pool.get('RTT')
            self.assertTrue(rtt_pool)

            request = self.create_request({
                'days': 1,
                'date_from': '06/05/2016 - 06/05/2016',
                'type': '2',
                'breakdown': 'AM',
            })
            view = Send(request)()

        self.assertIsRedirect(view)
        # no new requests were made
        self.assertEqual(Request.find(self.session, count=True), total_req)
        expected = ['error;RTT can only be used between 01/01/2015 and 31/12/2015']  # noqa
        self.assertEqual(request.session.pop_flash(), expected)
Exemplo n.º 26
0
    def test_by_name_country_rtt_ok(self):
        from pyvac.models import User, VacationType

        jdoe = User.by_login(self.session, u"jdoe")
        with freeze_time("2014-12-25", ignore=["celery", "psycopg2", "sqlalchemy", "icalendar"]):
            vac = VacationType.by_name_country(self.session, u"RTT", jdoe.country)
            self.assertEqual(vac, 10)
Exemplo n.º 27
0
    def process(self, data):
        """send a trial reminder mail for a user to his admin"""
        user = User.by_id(self.session, data['user_id'])
        duration = data['duration']

        conf = ConfCache()
        sender = conf.get('reminder', {}).get('sender', 'pyvac')
        # send mail to user country admin (HR)
        subject = 'Trial period reminder: %s' % user.name
        admin = user.get_admin(self.session)
        target = self.get_admin_mail(admin)
        content = """Hello,

This is a reminder that %s trial period has been running for %d months.
Arrival date: %s

""" % (user.name, duration, user.arrival_date.strftime('%d/%m/%Y'))

        try:
            self.smtp.send_mail(sender, target, subject, content)

            data = {'user_id': user.id}
            parameters = json.dumps(OrderedDict(data))
            rem = Reminder(type='trial_threshold', parameters=parameters)
            self.session.add(rem)
            self.session.flush()
            transaction.commit()

        except Exception:
            self.log.exception('Error while sending mail')
Exemplo n.º 28
0
 def test_by_credentials_ok(self):
     from pyvac.models import User
     user = User.by_credentials(self.session, u'jdoe', u'changeme')
     self.assertIsInstance(user, User)
     self.assertEqual(user.login, u'jdoe')
     self.assertEqual(user.name, u'John Doe')
     self.assertEqual(user.role, u'user')
Exemplo n.º 29
0
    def test_post_send_rtt_usage_not_enough_ko(self):
        self.config.testing_securitypolicy(userid=u'janedoe',
                                           permissive=True)
        from pyvac.models import Request, User
        from pyvac.views.request import Send
        total_req = Request.find(self.session, count=True)

        def mock_get_rtt_usage(self, session):
            """ Get rrt usage for a user """
            return {'allowed': 10, 'left': 0.5, 'state': 'error',
                    'taken': 9.5, 'year': 2014}

        orig_get_rtt_usage = User.get_rtt_usage
        User.get_rtt_usage = mock_get_rtt_usage
        user = User.by_login(self.session, u'janedoe')
        rtt_data = user.get_rtt_usage(self.session)
        self.assertTrue(rtt_data)

        request = self.create_request({'days': 1,
                                       'date_from': '05/05/2015 - 05/05/2015',
                                       'type': '2',
                                       'breakdown': 'FULL',
                                       })
        view = Send(request)()
        self.assertIsRedirect(view)
        # no new requests were made
        self.assertEqual(Request.find(self.session, count=True), total_req)
        expected = ['error;You only have 0.5 RTT to use.']
        self.assertEqual(request.session.pop_flash(), expected)
        User.get_rtt_usage = orig_get_rtt_usage
Exemplo n.º 30
0
    def process(self, data):
        """ denied by last_action_user_id
        send mail to user
        """
        req = Request.by_id(self.session, data['req_id'])

        # retrieve user who performed last action
        action_user = User.by_id(self.session, req.last_action_user_id)
        # send mail to user
        src = action_user.email
        dst = req.user.email
        content = """Your request has been refused for the following reason: %s
Request details: %s""" % (req.reason, req.summarymail)
        try:
            self.send_mail(sender=src, target=dst, request=req,
                           content=content)

            # update request status after sending email
            req.notified = True
        except Exception as err:
            self.log.exception('Error while sending mail')
            req.flag_error(str(err), self.session)

        self.session.flush()
        transaction.commit()
Exemplo n.º 31
0
    def validate(self, model, errors):
        r = self.request
        settings = r.registry.settings
        ldap = False

        if 'pyvac.use_ldap' in settings:
            ldap = asbool(settings.get('pyvac.use_ldap'))

        if 'current_password' in r.params and r.params['current_password']:
            if not User.by_credentials(self.session, model.login,
                                       r.params['current_password'], ldap):
                errors.append(_(u'current password is not correct'))
            elif r.params['user.password'] == r.params['current_password']:
                errors.append(_(u'password is unchanged'))

            if r.params['user.password'] != r.params['confirm_password']:
                errors.append(_(u'passwords do not match'))

        if (r.params.get('remove_photo', 'no') == 'no'):
            try:
                photo = r.POST['photofile'].file.read()
                photo_size = len(photo)
                if photo_size > 200000:
                    errors.append(_(u'Invalid photo size: %d' % photo_size))
            except:
                pass

        if errors:
            self.request.session.flash('error;%s' % ','.join(errors))

        return len(errors) == 0
Exemplo n.º 32
0
    def test_post_send_rtt_usage_empty_ok(self):
        self.config.testing_securitypolicy(userid=u'janedoe',
                                           permissive=True)
        from pyvac.models import Request, User
        from pyvac.views.request import Send
        total_req = Request.find(self.session, count=True)

        def mock_get_rtt_usage(self, session):
            """ Get rrt usage for a user """
            return

        orig_get_rtt_usage = User.get_rtt_usage
        User.get_rtt_usage = mock_get_rtt_usage
        user = User.by_login(self.session, u'janedoe')
        rtt_data = user.get_rtt_usage(self.session)
        self.assertIsNone(rtt_data)

        view = Send(self.create_request({
            'days': 1,
            'date_from': '05/05/2015 - 05/05/2015',
            'type': '2',
            'breakdown': 'AM',
        }))()
        self.assertIsRedirect(view)
        self.assertEqual(Request.find(self.session, count=True), total_req + 1)
        User.get_rtt_usage = orig_get_rtt_usage
Exemplo n.º 33
0
    def test_post_send_rtt_usage_not_enough_ko(self):
        self.config.testing_securitypolicy(userid=u'janedoe',
                                           permissive=True)
        from pyvac.models import Request, User
        from pyvac.views.request import Send
        total_req = Request.find(self.session, count=True)

        with patch('pyvac.models.User.pool',
                   new_callable=PropertyMock) as mock_foo:
            mocked_pool = mock_pool(0.5, datetime(2014, 1, 1),
                                    datetime(2014, 12, 31))
            mock_foo.return_value = {'RTT': mocked_pool}

            user = User.by_login(self.session, u'janedoe')
            rtt_pool = user.pool.get('RTT')
            self.assertTrue(rtt_pool)

            request = self.create_request({'days': 1,
                                           'date_from': '05/05/2015 - 05/05/2015', # noqa
                                           'type': '2',
                                           'breakdown': 'FULL',
                                           })
            view = Send(request)()

        self.assertIsRedirect(view)
        # no new requests were made
        self.assertEqual(Request.find(self.session, count=True), total_req)
        expected = ['error;You only have 0.5 RTT to use.']
        self.assertEqual(request.session.pop_flash(), expected)
Exemplo n.º 34
0
    def authenticated_userid(self, request):

        auth = request.environ.get('HTTP_AUTHORIZATION')
        try:
            authmeth, auth = auth.split(' ', 1)
        except AttributeError as ValueError:  # not enough values to unpack
            return None

        if authmeth.lower() != 'basic':
            return None

        try:
            # Python 3's string is already unicode
            auth = auth.strip().decode('base64')
            if sys.version_info[0] == 2:
                auth = unicode(auth)
        except binascii.Error:  # can't decode
            return None
        try:
            login, password = auth.split(':', 1)
        except ValueError:  # not enough values to unpack
            return None

        if User.by_credentials(DBSession(), login, password):
            return login

        return None
Exemplo n.º 35
0
    def test_get_rtt_usage(self):
        from pyvac.models import User

        user = User.by_login(self.session, u"jdoe")
        self.assertIsInstance(user, User)
        self.assertEqual(user.login, u"jdoe")
        self.assertEqual(user.name, u"John Doe")
        self.assertEqual(user.role, u"user")
        with freeze_time("2014-12-25", ignore=["celery", "psycopg2", "sqlalchemy", "icalendar"]):
            expected = {"allowed": 10, "left": 9.5, "state": "warning", "taken": 0.5, "year": 2014}
            self.assertEqual(user.get_rtt_usage(self.session), expected)
            # no RTT for us country
            user = User.by_login(self.session, u"manager3")
            self.assertIsInstance(user, User)
            self.assertEqual(user.country, u"us")
            self.assertIsNone(user.get_rtt_usage(self.session))
Exemplo n.º 36
0
    def process(self, data):
        """ denied by last_action_user_id
        send mail to user
        """
        req = Request.by_id(self.session, data['req_id'])

        # retrieve user who performed last action
        action_user = User.by_id(self.session, req.last_action_user_id)
        # send mail to user
        src = action_user.email
        dst = req.user.email
        content = """You request has been refused for the following reason: %s
Request details: %s""" % (req.reason, req.summarymail)
        try:
            self.send_mail(sender=src, target=dst, request=req,
                           content=content)

            # update request status after sending email
            req.notified = True
        except Exception as err:
            self.log.exception('Error while sending mail')
            req.flag_error(str(err))

        self.session.flush()
        transaction.commit()
Exemplo n.º 37
0
 def test_by_country_ok(self):
     from pyvac.models import User, VacationType
     manager3 = User.by_login(self.session, u'manager3')
     vac_types = VacationType.by_country(self.session, manager3.country)
     self.assertEqual(len(vac_types), 5)
     # take the first
     vac_type = vac_types.pop()
     self.assertIsInstance(vac_type, VacationType)
Exemplo n.º 38
0
 def test_by_manager(self):
     from pyvac.models import User, Request
     manager1 = User.by_login(self.session, u'manager1')
     requests = Request.by_manager(self.session, manager1)
     self.assertEqual(len(requests), 2)
     # take the first
     request = requests.pop()
     self.assertIsInstance(request, Request)
Exemplo n.º 39
0
 def get_target_user(self, logged_user):
     if self.user.is_admin:
         sudo_user_id = int(self.request.params.get('sudo_user'))
         if sudo_user_id != -1:
             user = User.by_id(self.session, sudo_user_id)
             if user:
                 return user
     return logged_user
Exemplo n.º 40
0
    def get_squad_stats(self, target_squad, users_entity):
        # retrieve squad members
        users_per_id = {}
        for user in User.find(self.session):
            if target_squad in users_entity.get(user.dn, []):
                users_per_id[user.id] = user

        return self.get_users_stats(users_per_id)
Exemplo n.º 41
0
 def test_by_country_ok(self):
     from pyvac.models import User, VacationType
     manager3 = User.by_login(self.session, u'manager3')
     vac_types = VacationType.by_country(self.session, manager3.country)
     self.assertEqual(len(vac_types), 5)
     # take the first
     vac_type = vac_types.pop()
     self.assertIsInstance(vac_type, VacationType)
Exemplo n.º 42
0
    def test_alias_ko(self):
        from pyvac.models import Sudoer
        from pyvac.models import User
        user = User.by_login(self.session, u'jdoe')
        self.assertIsInstance(user, User)

        sudoers = Sudoer.alias(self.session, user)
        self.assertEqual(sudoers, [])
Exemplo n.º 43
0
    def test_alias_ko(self):
        from pyvac.models import Sudoer
        from pyvac.models import User
        user = User.by_login(self.session, u'jdoe')
        self.assertIsInstance(user, User)

        sudoers = Sudoer.alias(self.session, user)
        self.assertEqual(sudoers, [])
Exemplo n.º 44
0
def populate(engine, ldap):
    """ Retrieve users from ldap directory and import them in local database
    """

    session = DBSession()

    # retrieve managers from dedicated group
    managers = ldap.list_manager()

    # retrieve users
    searchFilter = '(&(objectClass=inetOrgPerson)(employeetype=Employee))'
    required = ['objectClass', 'employeeType', 'cn', 'givenName', 'sn',
                'manager', 'mail', 'ou', 'uid', 'userPassword']

    users = ldap._search(searchFilter, required)
    for user_dn, user_entry in users:
        user_data = ldap.parse_ldap_entry(user_dn, user_entry)
        if not user_data or not user_data.get('login'):
            continue
        login = user_data['login'].decode('utf-8')
        # check what type of user it is
        group = 'user'
        # if it's a manager he should be in manager group
        if user_data['dn'] in managers:
            group = 'manager'
        # if it's an admin he should be in admin group
        what = '(member=%s)' % user_data['dn']
        if len(ldap._search_admin(what, None)) > 0:
            group = 'admin'

        user = User.by_login(session, login)
        if not user:
            user = User.create_from_ldap(session, user_data, group)
        else:
            # update user with ldap informations in case it changed
            user.email = user_data['email'].decode('utf-8')
            user.firstname = user_data['firstname'].decode('utf-8')
            user.lastname = user_data['lastname'].decode('utf-8')
            user.manager_dn = user_data['manager_dn'].decode('utf-8')
            user.dn = user_data['dn'].decode('utf-8')
            user.role = group

        session.add(user)

    session.commit()
Exemplo n.º 45
0
 def test_get_rtt_usage(self):
     from pyvac.models import User
     user = User.by_login(self.session, u'jdoe')
     self.assertIsInstance(user, User)
     self.assertEqual(user.login, u'jdoe')
     self.assertEqual(user.name, u'John Doe')
     self.assertEqual(user.role, u'user')
     with freeze_time('2014-12-25',
                      ignore=['celery', 'psycopg2', 'sqlalchemy',
                              'icalendar']):
         expected = {'allowed': 10, 'left': 9.5, 'state': 'warning',
                     'taken': 0.5, 'year': 2014}
         self.assertEqual(user.get_rtt_usage(self.session), expected)
         # no RTT for us country
         user = User.by_login(self.session, u'manager3')
         self.assertIsInstance(user, User)
         self.assertEqual(user.country, u'us')
         self.assertIsNone(user.get_rtt_usage(self.session))
Exemplo n.º 46
0
    def render(self):
        def fmt_req_type(req):
            label = ' %s' % req.label if req.label else ''
            return '%s%s' % (req.type, label)

        filter_nick = self.request.params.get('nick')
        filter_name = self.request.params.get('name')
        filter_date = self.request.params.get('date')
        # strict if provided will disable partial search for nicknames
        strict = self.request.params.get('strict')

        # remove unwanted chars from filter_date
        if filter_date:
            filter_date = re.sub('[^\d+]', '', filter_date)

        if filter_nick:
            # retrieve all availables nicknames
            all_nick = [nick.lower()
                        for nick in User.get_all_nicknames(self.session)]
            if strict:
                match = filter_nick.lower() in all_nick
            else:
                match = set([nick for nick in all_nick
                             if filter_nick.lower() in nick.lower()])
            if not match:
                # filter_nick does not match any known uid, stop here
                return JsonHTTPNotFound({'message': ('%s not found'
                                                     % filter_nick)})

        requests = Request.get_active(self.session, filter_date)
        data_name = dict([(req.user.name.lower(), fmt_req_type(req))
                          for req in requests])
        data_nick = dict([(req.user.nickname, fmt_req_type(req))
                          for req in requests])

        ret = val = None
        if filter_nick:
            val = data_nick.get(filter_nick.lower())
            if val:
                ret = {filter_nick: val}
            elif not strict:
                val = dict([(k, v) for k, v in data_nick.items()
                            if filter_nick.lower() in k])
                return val
            else:
                return {}

        if filter_name:
            val = data_name.get(filter_name.lower())
            if val:
                ret = {filter_name: val}
            else:
                val = dict([(k, v) for k, v in data_name.items()
                            if filter_name.lower() in k])
                return val

        return ret if ret else data_name
Exemplo n.º 47
0
 def test_get_rtt_usage(self):
     from pyvac.models import User
     user = User.by_login(self.session, u'jdoe')
     self.assertIsInstance(user, User)
     self.assertEqual(user.login, u'jdoe')
     self.assertEqual(user.name, u'John Doe')
     self.assertEqual(user.role, u'user')
     with freeze_time('2014-12-25',
                      ignore=['celery', 'psycopg2', 'sqlalchemy',
                              'icalendar']):
         expected = {'allowed': 10, 'left': 9.5, 'state': 'warning',
                     'taken': 0.5, 'year': 2014}
         self.assertEqual(user.get_rtt_usage(self.session), expected)
         # no RTT for us country
         user = User.by_login(self.session, u'manager3')
         self.assertIsInstance(user, User)
         self.assertEqual(user.country, u'us')
         self.assertIsNone(user.get_rtt_usage(self.session))
Exemplo n.º 48
0
 def test_by_name_country_rtt_ok(self):
     from pyvac.models import User, VacationType
     jdoe = User.by_login(self.session, u'jdoe')
     with freeze_time('2014-12-25',
                      ignore=['celery', 'psycopg2', 'sqlalchemy',
                              'icalendar']):
         vac = VacationType.by_name_country(self.session, u'RTT',
                                            jdoe.country)
         self.assertEqual(vac, 10)
Exemplo n.º 49
0
    def render(self):

        settings = self.request.registry.settings
        use_ldap = False
        if 'pyvac.use_ldap' in settings:
            use_ldap = asbool(settings.get('pyvac.use_ldap'))

        user_attr = {}
        if use_ldap:
            # synchronise user groups/roles
            User.sync_ldap_info(self.session)
            ldap = LdapCache()
            user_attr = ldap.get_users_units()

        return {u'user_count': User.find(self.session, count=True),
                u'users': User.find(self.session, order_by=[User.dn]),
                'use_ldap': use_ldap,
                'ldap_info': user_attr,
                }
Exemplo n.º 50
0
def populate(engine, ldap):
    """ Retrieve users from ldap directory and import them in local database
    """

    session = DBSession()

    # retrieve managers from dedicated group
    managers = ldap.list_manager()

    # retrieve users
    searchFilter = '(&(objectClass=inetOrgPerson)(employeetype=Employee))'
    required = ['objectClass', 'employeeType', 'cn', 'givenName', 'sn',
                'manager', 'mail', 'ou', 'uid', 'userPassword']

    users = ldap._search(searchFilter, required)
    for user_dn, user_entry in users:
        user_data = ldap.parse_ldap_entry(user_dn, user_entry)
        login = user_data['login'].decode('utf-8')
        # check what type of user it is
        group = u'user'
        # if it's a manager he should be in manager group
        if user_data['dn'] in managers:
            group = u'manager'
        # if it's an admin he should be in admin group
        what = '(member=%s)' % user_data['dn']
        if len(ldap._search_admin(what, None)) > 0:
            group = u'admin'

        user = User.by_login(session, login)
        if not user:
            user = User.create_from_ldap(session, user_data, group)
        else:
            # update user with ldap informations in case it changed
            user.email = user_data['email'].decode('utf-8')
            user.firstname = user_data['firstname'].decode('utf-8')
            user.lastname = user_data['lastname'].decode('utf-8')
            user.manager_dn = user_data['manager_dn'].decode('utf-8')
            user.dn = user_data['dn'].decode('utf-8')
            user.role = group

        session.add(user)

    session.commit()
Exemplo n.º 51
0
    def test_alias(self):
        from pyvac.models import Sudoer
        from pyvac.models import User
        user = User.by_login(self.session, u'janedoe')
        self.assertIsInstance(user, User)

        sudoers = Sudoer.alias(self.session, user)
        self.assertEqual(len(sudoers), 1)
        sudoer = sudoers[0]
        self.assertIsInstance(sudoer, User)
Exemplo n.º 52
0
 def test_by_manager(self):
     from pyvac.models import User, Request
     manager1 = User.by_login(self.session, u'manager1')
     with freeze_time('2015-03-01',
                      ignore=['celery', 'psycopg2', 'sqlalchemy',
                              'icalendar']):
         requests = Request.by_manager(self.session, manager1)
     self.assertEqual(len(requests), 8)
     # take the first
     request = requests.pop()
     self.assertIsInstance(request, Request)
Exemplo n.º 53
0
 def test_post_delete_ok(self):
     from pyvac.views.account import Delete
     from pyvac.models import User
     view = Delete(self.create_request({'form.submitted': '1',
                                        },
                                       matchdict={'user_id': self.account_id
                                                  },))()
     self.assertIsRedirect(view)
     account = User.by_id(self.session, self.account_id)
     self.assertIsNone(account)
     self.account_todelete = []
Exemplo n.º 54
0
    def test_by_user_outdated(self):
        from pyvac.models import User, Request

        user1 = User.by_login(self.session, u"jdoe")
        requests = Request.by_user(self.session, user1)
        self.assertEqual(len(requests), 5)

        outdated = Request.by_id(self.session, 7)
        self.assertIsInstance(outdated, Request)
        self.assertEqual(outdated.user, user1)
        self.assertFalse(outdated in requests)
Exemplo n.º 55
0
    def render(self):
        if not self.user:
            return self.redirect()

        _ = self.request.translate

        self.user.rtt = self.user.get_rtt_usage(self.session)

        holidays = get_holiday(self.user)

        ret_dict = {'types': [], 'holidays': holidays, 'sudo_users': [],
                    'futures_pending': [], 'futures_approved': []}

        vacation_types = VacationType.by_country(self.session,
                                                 self.user.country)
        for vac in vacation_types:
            if vac.visibility and self.user.role not in vac.visibility:
                continue
            ret_dict['types'].append({'name': _(vac.name), 'id': vac.id})

        if self.user.is_admin:
            ret_dict['sudo_users'] = User.for_admin(self.session, self.user)

        futures_pending = [timestamp
                           for req in
                           Request.by_user_future_pending(self.session,
                                                          self.user)
                           for timestamp in req.timestamps]
        ret_dict['futures_pending'] = futures_pending
        futures_approved = [timestamp
                            for req in
                            Request.by_user_future_approved(self.session,
                                                            self.user)
                            for timestamp in req.timestamps]
        ret_dict['futures_approved'] = futures_approved

        exception_info_tooltip = """\
This type is for events which are not covered by other types: \
wedding, funeral, etc.

Providing a reason for this request is mandatory.
"""
        ret_dict['exception_info_tooltip'] = _(exception_info_tooltip)

        if self.request.matched_route:
            matched_route = self.request.matched_route.name
            ret_dict.update({
                'matched_route': matched_route,
                'csrf_token': self.request.session.get_csrf_token()})
            return ret_dict

        ret_dict.update({'csrf_token': self.request.session.get_csrf_token()})
        return ret_dict
Exemplo n.º 56
0
 def test_change_password_post_ok(self):
     from pyvac.models import User
     from pyvac.views.user import ChangePassword as ChangePwd
     ChangePwd(self.create_request({'form.submitted': u'1',
                                    'current_password': u'changeme',
                                    'user.password': u'newpassw',
                                    'confirm_password': u'newpassw',
                                    }))()
     admin = User.by_credentials(self.session, u'admin', u'newpassw')
     self.assertIsInstance(admin, User)
     admin.password = u'changeme'
     self.session.add(admin)
Exemplo n.º 57
0
 def test_change_password_post_ko_unchanged(self):
     from pyvac.models import User
     from pyvac.views.user import ChangePassword as ChangePwd
     view = ChangePwd(self.create_request({'form.submitted': u'1',
                                           'current_password': u'changeme',
                                           'user.password': u'changeme',
                                           'confirm_password': u'changeme',
                                           }))()
     self.assertEqual(view['errors'],
                      [u'password is inchanged'])
     admin = User.by_credentials(self.session, u'admin', u'changeme')
     self.assertIsInstance(admin, User)
Exemplo n.º 58
0
 def test_change_password_post_ko_not_matched(self):
     from pyvac.models import User
     from pyvac.views.user import ChangePassword as ChangePwd
     view = ChangePwd(self.create_request({'form.submitted': u'1',
                                           'current_password': u'CHANGEME',
                                           'user.password': u'newpassw',
                                           'confirm_password': u'NEWPASSW',
                                           }))()
     self.assertEqual(view['errors'],
                      [u'current password is not correct',
                       u'passwords do not match'])
     admin = User.by_credentials(self.session, u'admin', u'changeme')
     self.assertIsInstance(admin, User)
Exemplo n.º 59
0
    def test_by_user_outdated(self):
        from pyvac.models import User, Request
        user1 = User.by_login(self.session, u'jdoe')
        with freeze_time('2015-08-01',
                         ignore=['celery', 'psycopg2', 'sqlalchemy',
                                 'icalendar']):
            requests = Request.by_user(self.session, user1)
        self.assertEqual(len(requests), 8)

        outdated = Request.by_id(self.session, 7)
        self.assertIsInstance(outdated, Request)
        self.assertEqual(outdated.user, user1)
        self.assertFalse(outdated in requests)