Esempio n. 1
0
 def _prepare_user_page(self, uid):
     """Shared by index_html and simple_profile"""
     is_auth = _is_authenticated(self.REQUEST)
     agent = self._get_ldap_agent(bind=is_auth)
     ldap_roles = sorted(agent.member_roles_info('user',
                                                 uid,
                                                 ('description',)))
     roles = []
     for (role_id, attrs) in ldap_roles:
         roles.append((role_id,
                       attrs.get('description', ('', ))[0].decode('utf8')))
     user = agent.user_info(uid)
     user['jpegPhoto'] = agent.get_profile_picture(uid)
     user['certificate'] = agent.get_certificate(uid)
     if user['organisation']:
         org_info = agent.org_info(user['organisation'])
         org_id = org_info.get('id')
         if 'INVALID' in org_id:
             user['organisation'] = org_id.decode('utf8')
         user['organisation_title'] = org_info['name']
     else:
         user['organisation_title'] = ''
     pwdChangedTime = user['pwdChangedTime']
     if pwdChangedTime:
         pwdChangedTime = datetime.strptime(pwdChangedTime, '%Y%m%d%H%M%SZ')
         user['pwdChanged'] = pwdChangedTime.strftime('%Y-%m-%d %H:%M:%S')
         user['pwdExpired'] = datetime.now() - timedelta(
             days=365) > pwdChangedTime
     else:
         user['pwdChanged'] = ''
         user['pwdExpired'] = True
     return user, roles
Esempio n. 2
0
 def is_authenticated(self):
     return _is_authenticated(self._get_request())
Esempio n. 3
0
    def index_html(self, REQUEST):
        """ """
        uid = REQUEST.form.get('uid')
        if not uid:
            # a missing uid can only mean this page is called by accident
            return
        date_for_roles = REQUEST.form.get('date_for_roles')

        if "," in uid:
            user = None
            roles = None
            multi = json.dumps({'users': uid.split(",")})
        else:
            multi = None
            user, roles = self._prepare_user_page(uid)

        is_auth = _is_authenticated(REQUEST)
        # we can only connect to ldap with bind=True if we have an
        # authenticated user
        agent = self._get_ldap_agent(bind=is_auth)

        user_dn = agent._user_dn(uid)
        log_entries = list(reversed(agent._get_metadata(user_dn)))
        VIEWS = {}
        filtered_roles = set([info[0] for info in roles])   # + owner_roles)
        if date_for_roles:
            filter_date = DateTime(date_for_roles).asdatetime().date()
        else:
            filter_date = DateTime().asdatetime().date()

        for entry in log_entries:
            date = DateTime(entry['timestamp']).toZone("CET")
            entry['timestamp'] = date.ISO()
            view = VIEWS.get(entry['action'])
            if not view:
                view = getMultiAdapter((self, self.REQUEST),
                                       name="details_" + entry['action'])
                VIEWS[entry['action']] = view
            entry['view'] = view

            _roles = entry.get('data', {}).get('roles')
            _role = entry.get('data', {}).get('role')
            if date.asdatetime().date() >= filter_date:
                if entry['action'] == 'ENABLE_ACCOUNT':
                    filtered_roles.difference_update(set(_roles))
                elif entry['action'] == "DISABLE_ACCOUNT":
                    filtered_roles.update(set(_roles))
                elif entry['action'] in ["ADDED_TO_ROLE"]:
                    if _role and _role in filtered_roles:
                        filtered_roles.remove(_role)
                elif entry['action'] in ["REMOVED_FROM_ROLE"]:
                    if _role:
                        filtered_roles.add(_role)

        output = []
        for entry in log_entries:
            if output:
                last_entry = output[-1]
                check = ['author', 'action']
                flag = True
                for k in check:
                    if last_entry[k] != entry[k]:
                        flag = False
                        break
                if flag:
                    last_entry['data'].append(entry['data'])
                else:
                    entry['data'] = [entry['data']]
                    output.append(entry)
            else:
                entry['data'] = [entry['data']]
                output.append(entry)

        removed_roles = []
        if user.get('status') == 'disabled':
            auth_user = self.REQUEST.AUTHENTICATED_USER
            if not bool(auth_user.has_permission(ldap_edit_users, self)):
                raise NotFound("User '%s' does not exist" % uid)
            # process log entries to list the roles the user had before
            # being disabled
            for entry in log_entries:
                if entry['action'] == 'DISABLE_ACCOUNT':
                    for role in entry['data'][0]['roles']:
                        try:
                            role_description = agent.role_info(role)[
                                'description']
                        except Exception:
                            role_description = ("This role doesn't exist "
                                                "anymore")
                        removed_roles.append((role, role_description))
                    break

        return self._render_template(
            "zpt/userdetails/index.zpt", context=self,
            filtered_roles=filtered_roles, user=user, roles=roles,
            removed_roles=removed_roles, multi=multi, log_entries=output)
Esempio n. 4
0
    def export_org(self, REQUEST):
        """ Export of one organisation """
        if not _is_authenticated(REQUEST):
            raise Unauthorized

        org_id = REQUEST.form['id']

        agent = self._get_ldap_agent()
        org_info = agent.org_info(org_id)
        wb = xlwt.Workbook()
        org_sheet = wb.add_sheet("Organisation Details")
        users_sheet = wb.add_sheet("Users")

        style_header = xlwt.XFStyle()
        style_normal = xlwt.XFStyle()
        normalfont = xlwt.Font()
        headerfont = xlwt.Font()
        headerfont.bold = True
        style_header.font = headerfont
        style_normal.font = normalfont

        cols = [
            'id',
            'name',
            'locality',
            'postal_address',
            'fax',
            'email',
        ]
        for i, col in enumerate(cols):
            org_sheet.write(0, i, col, style_header)
            org_sheet.write(2, i, org_info[col], style_normal)

        org_sheet.col(1).set_width(9000)
        org_sheet.col(2).set_width(5000)
        org_sheet.col(3).set_width(9000)
        org_sheet.col(4).set_width(4000)
        org_sheet.col(5).set_width(5000)

        org_members = []
        members = agent.members_in_org(org_id)

        for user_id in members:
            try:
                org_members.append(agent.user_info(user_id))
            except (NO_SUCH_OBJECT, UserNotFound):
                pass

        org_members.sort(key=operator.itemgetter('first_name'))

        cols = [
            'user id',
            'fullname',
            'email',
        ]
        for i, col in enumerate(cols):
            users_sheet.write(0, i, col, style_header)

        for i, member in enumerate(org_members, 2):
            users_sheet.write(i, 0, member['uid'])
            users_sheet.write(i, 1, member['full_name'])
            users_sheet.write(i, 2, member['email'])

        users_sheet.col(0).set_width(4000)
        users_sheet.col(1).set_width(6000)
        users_sheet.col(2).set_width(9000)

        out = StringIO()
        wb.save(out)
        out.seek(0)
        out = out.read()

        RESPONSE = REQUEST.RESPONSE

        RESPONSE.setHeader('Content-Type', "application/vnd.ms-excel")
        RESPONSE.setHeader('Content-Length', len(out))
        RESPONSE.setHeader('Pragma', 'public')
        RESPONSE.setHeader('Cache-Control', 'max-age=0')
        RESPONSE.addHeader("content-disposition",
                           "attachment; filename=%s.xls" % org_id)

        return out