Exemple #1
0
    def activeUsers(self):
        """
        method:
            monitoring/activeUsers

        description:
            for each realm, display the resolvers and
            the number of users which have at least one assigned active token
            per resolver
            the 'total' gives the number of all users, which are in an allowed
            realm and own an active token
            users are conted per resolver (not per realm), so if resolver is in
            multiple realms and one user ons tokens in 2 realms, the user will
            be counted only once

        arguments:
            * realms - optional: takes realms, only information on these realms
                will be displayed
        """
        result = {}
        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')

            monit_handl = MonitorHandler()

            policies = getAdminPolicies('activeUsers', scope='monitoring')

            realm_whitelist = []
            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                realm_info[a_realm] = monit_handl.active_users_per_realm(a_realm)

            result['Realms'] = realm_info
            result['total'] = monit_handl.active_users_total(realms)

            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[resolvers] done')
Exemple #2
0
    def activeUsers(self):
        """
        method:
            monitoring/activeUsers

        description:
            for each realm, display the resolvers and
            the number of users which have at least one assigned active token
            per resolver
            the 'total' gives the number of all users, which are in an allowed
            realm and own an active token
            users are conted per resolver (not per realm), so if resolver is in
            multiple realms and one user ons tokens in 2 realms, the user will
            be counted only once

        arguments:
            * realms - optional: takes realms, only information on these realms
                will be displayed
        """
        result = {}
        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')

            monit_handl = MonitorHandler()

            policies = getAdminPolicies('activeUsers', scope='monitoring')

            realm_whitelist = []
            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                realm_info[a_realm] = monit_handl.active_users_per_realm(
                    a_realm)

            result['Realms'] = realm_info
            result['total'] = monit_handl.active_users_total(realms)

            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemple #3
0
    def userinfo(self):
        """
        method:
            monitoring/userinfo

        description:
            for each realm, display the resolvers and the number of users
            per resolver

        arguments:
            * realms - optional: takes a realm, only information on this realm
                will be displayed

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        """
        result = {}
        try:
            request_realms = self.request_params.get("realms", "").split(",")

            monit_handler = MonitorHandler()

            policies = getAdminPolicies("userinfo", scope="monitoring")

            realm_whitelist = []
            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            if "/:no realm:/" in realms:
                realms.remove("/:no realm:/")

            realm_info = {}
            for a_realm in realms:
                realm_info[a_realm] = monit_handler.resolverinfo(a_realm)

            result["Realms"] = realm_info

            db.session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemple #4
0
    def delete_all(self):
        """
        method:
            reporting/delete_all

        description:
            delete the reporting database table

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            realm_whitelist = []
            policies = getAdminPolicies('tokens', scope='monitoring')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            if '*' in status:
                status.remove('*')
                status.extend(['active', 'inactive', 'assigned', 'unassigned',
                               'active&assigned', 'active&unassigned',
                               'inactive&assigned', 'inactive&unassigned',
                               'total'])

            result = delete(realms=realms, status=status)
            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[delete_all] done')
Exemple #5
0
    def activeUsers(self):
        """
        method:
            monitoring/activeUsers

        description:
            for each realm, display the resolvers and
            the number of users which have at least one assigned active token
            per resolver
            the 'total' gives the number of all users, which are in an allowed
            realm and own an active token
            users are conted per resolver (not per realm), so if resolver is in
            multiple realms and one user ons tokens in 2 realms, the user will
            be counted only once

        arguments:
            * realms - optional: takes realms, only information on these realms
                will be displayed
        """
        result = {}
        try:
            request_realms = self.request_params.get("realms", "").split(",")

            monit_handl = MonitorHandler()

            policies = getAdminPolicies("activeUsers", scope="monitoring")

            realm_whitelist = []
            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                realm_info[a_realm] = monit_handl.active_users_per_realm(
                    a_realm
                )

            result["Realms"] = realm_info
            result["total"] = monit_handl.active_users_total(realms)

            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemple #6
0
    def show(self):
        """
        method:
            reporting/show

        description:
            show entries from the reporting database table

        arguments:
        * date - optional: only show entries which are newer than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries are shown
        * realms - optional: takes realms, only the reporting entries
                from this realm are shown
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'
        * sortby  - optional: sort the output by column
        * sortdir - optional: asc/desc
        * page    - optional: reqeuest a certain page
        * pagesize - optional: limit the number of returned tokens
        * outform - optional: if set to "csv", the output will be a .csv file

        returns: a json result with:
            { "head": [],
            "data": [ [row1]
            , [row2]
            , [row3] .. ]
            }
        in case of csv:
        first line: header of columns
        other lines: column values


        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            param = self.request_params
            page = param.get('page')
            sort = param.get('sortby')
            sortdir = param.get('sortdir')
            psize = param.get('pagesize')
            output_format = param.get('outform', 'json')
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', [])
            border_day = param.get('date')

            if border_day:
                # this may throw ValueError if date is in wrong format
                datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies('show', scope='reporting.access')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            reports = ReportingIterator(realms=realms, status=status, date=None,
                                        page=page, psize=psize, sort=sort,
                                        sortdir=sortdir)
            info = reports.getResultSetInfo()

            c.audit['success'] = True
            Session.commit()

            if output_format == 'csv':
                response.content_type = "application/force-download"
                response.headers['Content-disposition'] = \
                    'attachment; filename=linotp-reports.csv'
                return sendCSVIterator(reports.iterate_reports())
            else:
                response.content_type = 'application/json'
                return sendResultIterator(reports.iterate_reports(), opt=info)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except ValueError as value_error:
            log.exception(value_error)
            Session.rollback()
            return sendError(response, unicode(value_error), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemple #7
0
    def tokens(self):
        """
        method:
            monitoring/tokens

        description:

            Displays the number of tokens (with status) per realm
            (one token might be in multiple realms).
            The Summary gives the sum of all tokens in all given realms and
            might be smaller than the summ of all tokens
            as tokens which have two realms are only counted once!

        arguments:
            * status - optional: takes assigned or unassigned, give the number
                of tokens with this characteristic

            * realms - optional: takes realms, only the number of tokens in
                these realms will be displayed

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        exception:
            if an error occurs an exception is serialized and returned
        """
        result = {}
        try:
            # extract and strip the list of requested statuses + default
            # statuses and ignore empty values.

            status_params = self.request_params.get("status", "").split(",")
            status = list(
                set(
                    ["total", "total users"]
                    + [s.strip() for s in status_params if s.strip()]
                )
            )

            request_realms = self.request_params.get("realms", "").split(",")

            monit_handler = MonitorHandler()
            realm_whitelist = []

            policies = getAdminPolicies("tokens", scope="monitoring")

            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                token_count = monit_handler.token_count([a_realm], status)
                realm_info[a_realm] = token_count

            result["Summary"] = monit_handler.token_count(realms, status)
            result["Realms"] = realm_info

            db.session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemple #8
0
    def show(self):
        """
        method:
            reporting/show

        description:
            show entries from the reporting database table

        arguments:
        * date - optional: only show entries which are newer than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries are shown
        * realms - optional: takes realms, only the reporting entries
                from this realm are shown
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'
        * sortby  - optional: sort the output by column
        * sortdir - optional: asc/desc
        * page    - optional: reqeuest a certain page
        * pagesize - optional: limit the number of returned tokens
        * outform - optional: if set to "csv", the output will be a .csv file

        returns: a json result with:
            { "head": [],
            "data": [ [row1]
            , [row2]
            , [row3] .. ]
            }
        in case of csv:
        first line: header of columns
        other lines: column values


        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            param = request.params
            page = param.get('page')
            sort = param.get('sortby')
            sortdir = param.get('sortdir')
            psize = param.get('pagesize')
            output_format = param.get('outform', 'json')
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', [])
            border_day = param.get('date')

            if border_day:
                # this may throw ValueError if date is in wrong format
                datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies('show', scope='reporting.access')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            reports = ReportingIterator(realms=realms,
                                        status=status,
                                        date=None,
                                        page=page,
                                        psize=psize,
                                        sort=sort,
                                        sortdir=sortdir)
            info = reports.getResultSetInfo()

            c.audit['success'] = True
            Session.commit()

            if output_format == 'csv':
                response.content_type = "application/force-download"
                response.headers['Content-disposition'] = \
                    'attachment; filename=linotp-reports.csv'
                return sendCSVIterator(reports.iterate_reports())
            else:
                response.content_type = 'application/json'
                return sendResultIterator(reports.iterate_reports(), opt=info)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except ValueError as value_error:
            log.exception(value_error)
            Session.rollback()
            return sendError(response, unicode(value_error), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemple #9
0
    def delete_before(self):
        """
        method:
            reporting/delete_before

        description:
            delete all entries from reporting database with respect to the
            arguments
            date must be given in format: 'yyyy-mm-dd'

        arguments:
        * date - optional: only delete entries which are older than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries get deleted
        * realms - optional: takes realms, only the reporting entries
                from this realm are dedleted
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:

            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            param = request.params
            border_day = param.get('date')

            # this may throw ValueError if date is in wrong format
            datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies('delete_before', scope='reporting')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            result = delete(date=border_day, realms=realms, status=status)
            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except ValueError as value_error:
            log.exception(value_error)
            Session.rollback()
            return sendError(response, unicode(value_error), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemple #10
0
    def delete_all(self):
        """
        method:
            reporting/delete_all

        description:
            delete entries from the reporting database table

        arguments:
        * realms - optional: takes realms, only the reporting entries
                from this realm are dedleted
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            realm_whitelist = []
            policies = getAdminPolicies('delete_all', scope='reporting.access')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            if '*' in status:
                status.remove('*')
                status.extend([
                    'active', 'inactive', 'assigned', 'unassigned',
                    'active&assigned', 'active&unassigned',
                    'inactive&assigned', 'inactive&unassigned', 'total'
                ])

            result = delete(realms=realms, status=status)
            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemple #11
0
    def period(self):
        """
        method:
            reporting/period

        description:
            return the maximum of tokens in a given realm with given status
            for a given period

        arguments:
            * realms - required: takes realms, only the reporting entries for
                this realms will be displayed
            * status - optional: (default is 'active')
                takes assigned/unassigned/active/ etc.
                and shows max of lines in database with this characteristic
            * from - optional: (default is 1970-1-1)
                    the start day for the reporting max lookup
            * to - optional: (default is tomorow 0:0:0)
                    the end day for the reporting max lookup

        returns:
            a json result with:
            {
            "status": "true",
            "value": {
                realms: [ {}, {}],
                period: {
                    'from':
                    'to':
                }
            }
            with a realm entry {} as:
            {
            'realm': 'realmname',
            'tokencount': {
                'active': nn,

                }
            }

        exception:
            if an error occurs an exception is serialized and returned

        :return:
        """
        result = {}
        try:
            request_realms = self.request_params.get("realms", "").split(",")
            status = self.request_params.get("status", ["total"])
            if status != ["total"]:
                status = status.split(",")

            # ------------------------------------------------------------- --

            # handle start and stop
            # for backward compatibility start and stop are optional

            # if start is not given, we use the unix time start 1.1.1970

            start = datetime(year=1970, month=1, day=1)
            if "from" in self.request_params:
                start_str = self.request_params.get("from")
                start = convert_to_datetime(start_str, TIME_FMTS)

            # if end is not defined, we use tomorrow at 0:0:0

            _now = datetime.utcnow()
            end = datetime(year=_now.year, month=_now.month,
                           day=_now.day) + timedelta(days=1)
            if "to" in self.request_params:
                end_str = self.request_params.get("to")
                end = convert_to_datetime(end_str, TIME_FMTS)

            # ------------------------------------------------------------- --

            realm_whitelist = []
            policies = getAdminPolicies("period", scope="reporting.access")
            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = request_context["Realms"].keys()

            realms = match_realms(request_realms, realm_whitelist)

            result["realms"] = []
            for realm in realms:
                result_realm = {"name": realm}
                max_token_counts = {}
                for stat in status:

                    # search for the max token in the period [start : end]

                    max_token_stat = get_max_token_count_in_period(realm,
                                                                   status=stat,
                                                                   start=start,
                                                                   end=end)

                    # if none is found (-1) we search for the last entry
                    # before the period start

                    if max_token_stat == -1:
                        max_token_stat = get_last_token_count_before_date(
                            realm, status=stat, before_date=start)

                    max_token_counts[stat] = max_token_stat

                result_realm["maxtokencount"] = max_token_counts
                result["realms"].append(result_realm)

            result["period"] = {
                "from": start.isoformat(),
                "to": end.isoformat(),
            }

            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemple #12
0
    def userinfo(self):
        """
        method:
            monitoring/userinfo

        description:
            for each realm, display the resolvers and the number of users
            per resolver

        arguments:
            * realms - optional: takes a realm, only information on this realm
                will be displayed

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        """
        result = {}
        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')

            monit_handler = MonitorHandler()

            policies = getAdminPolicies('userinfo', scope='monitoring')

            realm_whitelist = []
            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            if '/:no realm:/' in realms:
                realms.remove('/:no realm:/')

            realm_info = {}
            for a_realm in realms:
                realm_info[a_realm] = monit_handler.resolverinfo(a_realm)

            result['Realms'] = realm_info

            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemple #13
0
    def tokens(self):
        """
        method:
            monitoring/tokens

        description:

            Displays the number of tokens (with status) per realm
            (one token might be in multiple realms).
            The Summary gives the sum of all tokens in all given realms and
            might be smaller than the summ of all tokens
            as tokens which have two realms are only counted once!

        arguments:
            * status - optional: takes assigned or unassigned, give the number
                of tokens with this characteristic

            * realms - optional: takes realms, only the number of tokens in
                these realms will be displayed

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        exception:
            if an error occurs an exception is serialized and returned
        """
        result = {}
        try:
            param = request.params

            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')
                status.append('total')
            request_realms = param.get('realms', '').split(',')

            monit_handler = MonitorHandler()
            realm_whitelist = []

            policies = getAdminPolicies('tokens', scope='monitoring')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                token_count = monit_handler.token_count([a_realm],
                                                        status)
                realm_info[a_realm] = token_count

            result[_('Summary')] = monit_handler.token_count(realms, status)
            result[_('Realms')] = realm_info

            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[tokens] done')
Exemple #14
0
    def maximum(self):
        """
        method:
            reporting/maximum

        description:
            return the maximum of tokens in a given realm with given status

        arguments:
            * realms - required: takes realms, only the reporting entries for
                this realms will be displayed
            * status - optional: (default is 'active')
                takes assigned/unassigned/active/ etc.
                and shows max of lines in database with this characteristic

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        exception:
            if an error occurs an exception is serialized and returned

        :return:
        """
        result = {}
        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            realm_whitelist = []
            policies = getAdminPolicies('tokens', scope='monitoring')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            for realm in realms:
                for stat in status:
                    result[realm] = get_max(realm, stat)

            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[maximum] done')
Exemple #15
0
    def show(self):
        """
        method:
            reporting/show

        description:
            show entries from the reporting database table

        arguments:
        * date - optional: only show entries which are newer than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries are shown
        * realms - optional: takes realms, only the reporting entries
                from this realm are shown
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }


        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', [])

            param = request.params
            border_day = param.get('date')

            if border_day:
                # this may throw ValueError if date is in wrong format
                datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies('show', scope='reporting.access')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            reports = ReportingIterator(realms=realms, status=status, date=None,
                                        page=None, psize=None, sort=None,
                                        sortdir=None)

            c.audit['success'] = True

            # put in the result
            result = {}

            # now row by row
            lines = []
            for rep in reports:
                # CKO:
                log.debug("tokenline: %s" % rep)
                lines.append(rep)

            result["data"] = lines
            result["resultset"] = reports.getResultSetInfo()

            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except ValueError as value_error:
            log.exception(value_error)
            Session.rollback()
            return sendError(response, unicode(value_error), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[delete_before] done')
Exemple #16
0
    def show(self):
        """
        method:
            reporting/show

        description:
            show entries from the reporting database table

        arguments:
        * date - optional: only show entries which are newer than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries are shown
        * realms - optional: takes realms, only the reporting entries
                from this realm are shown
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'
        * sortby  - optional: sort the output by column
        * sortdir - optional: asc/desc
        * page    - optional: reqeuest a certain page
        * pagesize - optional: limit the number of returned tokens
        * outform - optional: if set to "csv", the output will be a .csv file

        returns: a json result with:
            { "head": [],
            "data": [ [row1]
            , [row2]
            , [row3] .. ]
            }
        in case of csv:
        first line: header of columns
        other lines: column values


        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            param = self.request_params
            page = param.get("page")
            sort = param.get("sortby")
            sortdir = param.get("sortdir")
            psize = param.get("pagesize")
            output_format = param.get("outform", "json")
            request_realms = param.get("realms", "").split(",")
            status = param.get("status", [])

            start_day = None
            if "date" in param:
                start_day = convert_to_datetime(param.get("date"), TIME_FMTS)

            realm_whitelist = []
            policies = getAdminPolicies("show", scope="reporting.access")

            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            reports = ReportingIterator(
                realms=realms,
                status=status,
                date=start_day,
                page=page,
                psize=psize,
                sort=sort,
                sortdir=sortdir,
            )
            info = reports.getResultSetInfo()

            g.audit["success"] = True
            db.session.commit()

            if output_format == "csv":
                headers = Headers()
                headers.add(
                    "Content-Disposition",
                    "attachment",
                    filename="linotp-reports.csv",
                )
                return Response(
                    stream_with_context(
                        sendCSVIterator(reports.iterate_reports())),
                    mimetype="text/csv",
                    headers=headers,
                )
            else:
                return Response(
                    stream_with_context(
                        sendResultIterator(reports.iterate_reports(),
                                           opt=info)),
                    mimetype="application/json",
                )

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except ValueError as value_error:
            log.error(value_error)
            db.session.rollback()
            return sendError(response, value_error, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemple #17
0
    def delete_before(self):
        """
        method:
            reporting/delete_before

        description:
            delete all entries from reporting database with respect to the
            arguments
            date must be given in format: 'yyyy-mm-dd'

        arguments:
        * date - optional: only delete entries which are older than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries get deleted
        * realms - optional: takes realms, only the reporting entries
                from this realm are dedleted
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            request_realms = self.request_params.get("realms", "").split(",")
            status = self.request_params.get("status", ["total"])
            if status != ["total"]:
                status = status.split(",")

            border_day = self.request_params.get("date")

            # this may throw ValueError if date is in wrong format
            datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies("delete_before", scope="reporting")

            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            result = delete(date=border_day, realms=realms, status=status)
            db.session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except ValueError as value_error:
            log.error(value_error)
            db.session.rollback()
            return sendError(response, value_error, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemple #18
0
    def delete_all(self):
        """
        method:
            reporting/delete_all

        description:
            delete entries from the reporting database table

        arguments:
        * realms - optional: takes realms, only the reporting entries
                from this realm are dedleted
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            request_realms = self.request_params.get("realms", "").split(",")
            status = self.request_params.get("status", ["total"])
            if status != ["total"]:
                status = status.split(",")

            realm_whitelist = []
            policies = getAdminPolicies("delete_all", scope="reporting.access")

            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            if "*" in status:
                status.remove("*")
                status.extend([
                    "active",
                    "inactive",
                    "assigned",
                    "unassigned",
                    "active&assigned",
                    "active&unassigned",
                    "inactive&assigned",
                    "inactive&unassigned",
                    "total",
                ])

            result = delete(realms=realms, status=status)
            db.session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)
Exemple #19
0
    def delete_before(self):
        """
        method:
            reporting/delete_before

        description:
            delete all entries from reporting database with respect to the
            arguments
            date must be given in format: 'yyyy-mm-dd'

        arguments:
        * date - optional: only delete entries which are older than date;
                date must be given in format 'yyyy-mm-dd'
                if no date is given, all entries get deleted
        * realms - optional: takes realms, only the reporting entries
                from this realm are dedleted
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            request_realms = self.request_params.get('realms', '').split(',')
            status = self.request_params.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            border_day = self.request_params.get('date')

            # this may throw ValueError if date is in wrong format
            datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies('delete_before', scope='reporting')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            result = delete(date=border_day, realms=realms, status=status)
            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except ValueError as value_error:
            log.exception(value_error)
            Session.rollback()
            return sendError(response, unicode(value_error), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemple #20
0
    def tokens(self):
        """
        method:
            monitoring/tokens

        description:

            Displays the number of tokens (with status) per realm
            (one token might be in multiple realms).
            The Summary gives the sum of all tokens in all given realms and
            might be smaller than the summ of all tokens
            as tokens which have two realms are only counted once!

        arguments:
            * status - optional: takes assigned or unassigned, give the number
                of tokens with this characteristic

            * realms - optional: takes realms, only the number of tokens in
                these realms will be displayed

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        exception:
            if an error occurs an exception is serialized and returned
        """
        result = {}
        try:
            param = request.params

            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')
                status.append('total')
            request_realms = param.get('realms', '').split(',')

            monit_handler = MonitorHandler()
            realm_whitelist = []

            policies = getAdminPolicies('tokens', scope='monitoring')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                token_count = monit_handler.token_count([a_realm], status)
                realm_info[a_realm] = token_count

            result['Summary'] = monit_handler.token_count(realms, status)
            result['Realms'] = realm_info

            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemple #21
0
    def maximum(self):
        """
        method:
            reporting/maximum

        description:
            return the maximum of tokens in a given realm with given status

        arguments:
            * realms - required: takes realms, only the reporting entries for
                this realms will be displayed
            * status - optional: (default is 'active')
                takes assigned/unassigned/active/ etc.
                and shows max of lines in database with this characteristic

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        exception:
            if an error occurs an exception is serialized and returned

        :return:
        """
        result = {}
        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            realm_whitelist = []
            policies = getAdminPolicies('maximum', scope='reporting.access')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            for realm in realms:
                result[realm] = {}
                for stat in status:
                    result[realm][stat] = get_max(realm, stat)

            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
Exemple #22
0
    def delete_before(self):
        """
        method:
            reporting/delete_before

        description:
            delete all entries from reporting database which are older than date
            date must be given in format: 'yyyy-mm-dd'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:

            param = request.params
            request_realms = param.get('realms', '').split(',')
            status = param.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            param = request.params
            border_day = param.get('date')

            # this may throw ValueError if date is in wrong format
            datetime.strptime(border_day, "%Y-%m-%d")

            realm_whitelist = []
            policies = getAdminPolicies('tokens', scope='monitoring')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            result = delete(date=border_day, realms=realms, status=status)
            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except ValueError as value_error:
            log.exception(value_error)
            Session.rollback()
            return sendError(response, unicode(value_error), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[tokens] done')
Exemple #23
0
    def maximum(self):
        """
        method:
            reporting/maximum

        description:
            return the maximum of tokens in a given realm with given status

        arguments:
            * realms - required: takes realms, only the reporting entries for
                this realms will be displayed
            * status - optional: (default is 'active')
                takes assigned/unassigned/active/ etc.
                and shows max of lines in database with this characteristic

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        exception:
            if an error occurs an exception is serialized and returned

        :return:
        """
        result = {}
        try:
            # ------------------------------------------------------------- --
            start = datetime(year=1970, month=1, day=1)

            _now = datetime.utcnow()
            end = datetime(year=_now.year, month=_now.month,
                           day=_now.day) + timedelta(days=1)
            # ------------------------------------------------------------- --

            request_realms = self.request_params.get("realms", "").split(",")
            status = self.request_params.get("status", ["total"])
            if status != ["total"]:
                status = status.split(",")

            realm_whitelist = []
            policies = getAdminPolicies("maximum", scope="reporting.access")

            if policies["active"] and policies["realms"]:
                realm_whitelist = policies.get("realms")

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or "*" in realm_whitelist:
                realm_whitelist = list(request_context["Realms"].keys())

            realms = match_realms(request_realms, realm_whitelist)

            for realm in realms:
                result[realm] = {}
                for stat in status:
                    result[realm][stat] = get_max_token_count_in_period(
                        realm, status=stat, start=start, end=end)
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.error(policy_exception)
            db.session.rollback()
            return sendError(response, policy_exception, 1)

        except Exception as exc:
            log.error(exc)
            db.session.rollback()
            return sendError(response, exc)

        finally:
            db.session.close()
Exemple #24
0
    def userinfo(self):
        """
        method:
            monitoring/userinfo

        description:
            for each realm, display the resolvers and the number of users
            per resolver

        arguments:
            * realms - optional: takes a realm, only information on this realm
                will be displayed

        returns:
            a json result with:
            { "head": [],
            "data": [ [row1], [row2] .. ]
            }

        """
        result = {}
        try:
            param = request.params
            request_realms = param.get('realms', '').split(',')

            monit_handler = MonitorHandler()

            policies = getAdminPolicies('userinfo', scope='monitoring')

            realm_whitelist = []
            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            realm_info = {}
            for a_realm in realms:
                realm_info[a_realm] = monit_handler.resolverinfo(a_realm)

            result[_('Realms')] = realm_info

            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()
            log.debug('[resolvers] done')
Exemple #25
0
    def delete_all(self):
        """
        method:
            reporting/delete_all

        description:
            delete entries from the reporting database table

        arguments:
        * realms - optional: takes realms, only the reporting entries
                from this realm are dedleted
        * status - optional: filters reporting entries by status
                like 'assigned' or 'inactive'

        returns: dict in which value is the number of deleted rows

        exception:
            if an error occurs an exception is serialized and returned
        """

        try:
            request_realms = self.request_params.get('realms', '').split(',')
            status = self.request_params.get('status', ['total'])
            if status != ['total']:
                status = status.split(',')

            realm_whitelist = []
            policies = getAdminPolicies('delete_all', scope='reporting.access')

            if policies['active'] and policies['realms']:
                realm_whitelist = policies.get('realms')

            # if there are no policies for us, we are allowed to see all realms
            if not realm_whitelist or '*' in realm_whitelist:
                realm_whitelist = request_context['Realms'].keys()

            realms = match_realms(request_realms, realm_whitelist)

            if '*' in status:
                status.remove('*')
                status.extend(['active', 'inactive', 'assigned', 'unassigned',
                               'active&assigned', 'active&unassigned',
                               'inactive&assigned', 'inactive&unassigned',
                               'total'])

            result = delete(realms=realms, status=status)
            Session.commit()
            return sendResult(response, result)

        except PolicyException as policy_exception:
            log.exception(policy_exception)
            Session.rollback()
            return sendError(response, unicode(policy_exception), 1)

        except Exception as exc:
            log.exception(exc)
            Session.rollback()
            return sendError(response, exc)

        finally:
            Session.close()