[Zope3-checkins] CVS: Zope3/src/zope/app/securitypolicy/browser - __init__.py:1.1 addrole.pt:1.1 configure.zcml:1.1 grant.pt:1.1 manage_access.pt:1.1 manage_permissionform.pt:1.1 manage_roleform.pt:1.1 principal_permission_edit.pt:1.1 principal_role_association.pt:1.1 principalpermissionview.py:1.1 principalroleview.py:1.1 role_service.gif:1.1 rolepermissionview.py:1.1

Philipp von Weitershausen philikon at philikon.de
Fri Feb 27 07:46:34 EST 2004


Update of /cvs-repository/Zope3/src/zope/app/securitypolicy/browser
In directory cvs.zope.org:/tmp/cvs-serv6059/app/securitypolicy/browser

Added Files:
	__init__.py addrole.pt configure.zcml grant.pt 
	manage_access.pt manage_permissionform.pt manage_roleform.pt 
	principal_permission_edit.pt principal_role_association.pt 
	principalpermissionview.py principalroleview.py 
	role_service.gif rolepermissionview.py 
Log Message:
Moved the securitypolicy package from zope.products to zope.app.


=== Added File Zope3/src/zope/app/securitypolicy/browser/__init__.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
""" Define view component for service manager contents.

$Id: __init__.py,v 1.1 2004/02/27 12:46:31 philikon Exp $
"""
from zope.app.browser.container.contents import Contents
from zope.app.securitypolicy.role import Role, ILocalRoleService

class Add:
    "Provide a user interface for adding a role"
    __used_for__ = ILocalRoleService

    def action(self, id, title, description):
        "Add a contact"
        role = Role(id, title, description)
        self.context[id] = role
        self.request.response.redirect('.')


class Contents(Contents):
    # XXX: What the heck is that? I guess another dead chicken.
    pass


=== Added File Zope3/src/zope/app/securitypolicy/browser/addrole.pt ===
<html metal:use-macro="views/standard_macros/page">
<head>
  <title metal:fill-slot="title" i18n:translate="add-role-form-title">
    Add Role
  </title>
</head>
<body>
<div metal:fill-slot="body">

  <div i18n:translate="">Enter the information about the role.</div>

  <form action="action.html" method="post">

    <div class="row">
      <div class="label" i18n:translate="">Id</div>
      <div class="field">
        <input type="text" name="id" size="40" value="" />
      </div>
    </div>

    <div class="row">
      <div class="label" i18n:translate="">Title</div>
      <div class="field">
        <input type="text" name="title" size="40" value="" />
      </div>
    </div>

    <div class="row">
      <div class="label" i18n:translate="">Description</div>
      <div class="field">
        <textarea name="description" rows="10" cols="60"></textarea>
      </div>
    </div>

    <div class="row">
      <div class="controls">
        <input type="submit" name="submit" value="Create Role"
               i18n:attributes="value create-role-button" />
      </div>
    </div>

  </form>

</div>
</body>
</html>


=== Added File Zope3/src/zope/app/securitypolicy/browser/configure.zcml ===
<zope:configure 
   xmlns:zope="http://namespaces.zope.org/zope"
   xmlns="http://namespaces.zope.org/browser"
   i18n_domain="zope">

<!-- Role Service -->

  <icon
      name="zmi_icon" 
      for="zope.app.securitypolicy.role.ILocalRoleService"
      file="role_service.gif" />

  <pages 
     permission="zope.ManageServices" 
     for="zope.app.securitypolicy.role.IRoleService"
     class=".Contents">

     <page name="index.html" attribute="contents"
           menu="zmi_views" title="Contents" />
     <page name="removeObjects.html" attribute="removeObjects" />

  </pages>

  <pages 
     permission="zope.ManageServices" 
     for="zope.app.securitypolicy.role.IRoleService"
     class=".Add">

    <page name="+" template="addrole.pt" 
          menu="zmi_actions" title="Add" />
    <page name="action.html" attribute="action" />

  </pages>


<!-- Role Permissions -->

  <pages
      for="zope.app.interfaces.annotation.IAnnotatable"
      permission="zope.Security"
      class=".rolepermissionview.RolePermissionView">

    <page name="AllRolePermissions.html" template="manage_access.pt" />
          <!-- menu="zmi_actions" title="Role Permissions" / -->
    <page name="RolePermissions.html" template="manage_roleform.pt" />
    <page name="RolesWithPermission.html" template="manage_permissionform.pt"/>

  </pages>

  <page
    for="zope.app.interfaces.annotation.IAnnotatable"
    name="grant.html"
    permission="zope.Security"
    template="grant.pt" 
    menu="zmi_actions" title="Grant" />

<!-- Principal Roles -->

  <page
      name="PrincipalRoles.html" 
      for="zope.app.interfaces.annotation.IAnnotatable"
      permission="zope.Security"
      class=".principalroleview.PrincipalRoleView"
      template="principal_role_association.pt" />
      <!-- menu="zmi_actions" title="Principal Roles" / -->

<!-- Principal Permission (not working) -->

  <!-- browser:page
      name="PrincipalPermissionsManagement"
      for="zope.app.interfaces.annotation.IAnnotatable"
      class=".principalpermissionview.PrincipalPermissionView" 
      permission="zope.Security"
      allow_attributes="index get_principal unsetPermissions denyPermissions
                        grantPermissions getUnsetPermissionsForPrincipal
                        getPermissionsForPrincipal" 
      /  -->

</zope:configure>


=== Added File Zope3/src/zope/app/securitypolicy/browser/grant.pt ===
<html metal:use-macro="views/standard_macros/page">
<body>

<!-- XXX : This is just a temporary way of overriding the elements not needed,
            only done for visual purposes. Do not clone this ;)
                                                - Alexander
                                                -->
<div metal:fill-slot="tabs" />
<div metal:fill-slot="actions" />

<div metal:fill-slot="body">

  <p>
    <a href="@@AllRolePermissions.html" 
       i18n:translate="">Grant permissions to roles</a>
  </p>
  <p>
    <a href="@@PrincipalRoles.html" 
       i18n:translate="">Grant roles to principals</a>
  </p>

</div>
</body>
</html>



=== Added File Zope3/src/zope/app/securitypolicy/browser/manage_access.pt ===
<html metal:use-macro="views/standard_macros/dialog">
<head>
  <tal:block  
      metal:fill-slot="headers" 
      tal:define="global pagetip string:
      For each permission you want to grant (or deny) to a role, 
      set the entry for that permission and role to a '+' (or '-').
      Permissions are shown on the left side, going down.
      Roles are shown accross the top.
      "
      />
</head>
<body>
<div metal:fill-slot="body">

   <p tal:define="status view/update"
      tal:condition="status"
      tal:content="status" />

  <form action="AllRolePermissions.html" method="post">

    <table width="100%" cellspacing="0" cellpadding="2" border="0" 
           nowrap="nowrap">
  
      <tr class="list-header">
        <td align="left" valign="top">
          <div class="form-label">
            <strong i18n:translate="">Permission</strong>
          </div>
        </td>
        <td align="left">
          <div class="form-label">
            <strong i18n:translate="">Roles</strong>
          </div>
        </td>
      </tr>
  
      <tr class="row-normal">
        <td></td>
        <td align="center" tal:repeat="role view/roles">
          <div class="list-item">
            <a href="RolePermissions.html"
              tal:attributes="
              href string:RolePermissions.html?role_to_manage=${role/getId}" 
              tal:content="role/getTitle">Anonymous</a>
            <input type="hidden" name="r0" value=""
              tal:attributes="
              name string:r${repeat/role/index};
              value  string:${role/getId}" />
  
          </div>
        </td>
      </tr>
  
      <tbody tal:repeat="perm view/permissionRoles">
      <tr class="row-normal"
          tal:attributes="class 
             python:path('repeat/perm/even') and 'row-normal' or 'row-hilite'">
        <td align="left" nowrap="nowrap">
          <div class="list-item">
             <a href="RolesWithPermission.html"
                tal:attributes="href 
           string:RolesWithPermission.html?permission_to_manage=${perm/getId}"
                tal:content="perm/getTitle"
                >Access Transient Objects</a>
             <input type="hidden" name="r0" value=""
                 tal:attributes="
                 name string:p${repeat/perm/index};
                 value  string:${perm/getId}" />
          </div>
        </td>
        <td align="center" tal:repeat="setting perm/roleSettings">
          <select name="p0r0"
              tal:attributes="name 
                  string:p${repeat/perm/index}r${repeat/setting/index}">
            <option value="Unset"
                tal:repeat="option view/availableSettings"
                tal:attributes="value option/id;
                                selected python:setting == option['id']"
                tal:content="option/shorttitle">+</option>
          </select>
        </td>
      </tr>
      </tbody>
  
      <tr>
        <td colspan="5" align="left">
          <div class="form-element">
            <input class="form-element" type="submit" name="SUBMIT" 
                   value="Save Changes" />
          </div>
        </td>
      </tr>
    </table>
  </form>

</div>
</body>
</html>




=== Added File Zope3/src/zope/app/securitypolicy/browser/manage_permissionform.pt ===
<html metal:use-macro="views/standard_macros/page">
<head>
  <style metal:fill-slot="headers" type="text/css">
    <!--
    .row-normal {
      background-color: #ffffff;
      border: none;
    }
    
    .row-hilite {
      background-color: #efefef;
      border: none;
    }
    -->
  </style>
</head>
<body>
<div metal:fill-slot="body">

  <p tal:define="status view/update"
     tal:condition="status"
     tal:content="status" />

  <p class="form-help" i18n:translate="">
    Helpful message.
  </p>

  <div tal:define="perm 
         python:view.permissionForID(request.get('permission_to_manage'))">

    <p class="form-text" i18n:translate="">
      Roles assigned to the permission
      <strong tal:content="perm/getTitle" 
          i18n:name="perm_title">Change DTML Methods</strong>
      (id: <strong tal:content="perm/getId" 
          i18n:name="perm_id">Zope.Some.Permission</strong>)
    </p>

    <form action="AllRolePermissions.html" method="post">

      <input type="hidden" name="permission_id" value="Permission Name"
          tal:attributes="value perm/getId" />

        <div class="form-element">

          <table width="100%" cellspacing="0" cellpadding="2" border="0" 
              nowrap="nowrap">

            <tr class="list-header">
              <td align="left" valign="top">
                <div class="form-label">
                  <strong i18n:translate="">Role</strong>
                </div>
              </td>
              <td align="left">
                <div class="form-label">
                  <strong i18n:translate="">Setting</strong>
                </div>
              </td>
            </tr>

            <tr class="row-normal"
                tal:repeat="setting perm/roleSettings"
                tal:attributes="class 
          python:path('repeat/setting/even') and 'row-normal' or 'row-hilite'">
              <td align="left" valign="top"
                  tal:define="ir repeat/setting/index"
                  tal:content="python:path('view/roles')[ir].getId()">
                Manager
              </td>
              <td>
                <select name="settings:list">
                    <option value="Unset"
                       tal:repeat="option view/availableSettings"
                       tal:attributes="value option/id;
                                       selected python:setting == option['id']"
                       tal:content="option/shorttitle">+</option>
                </select>
              </td>
            </tr>
        </table>

      </div>

      <div class="form-element">
        <input class="form-element" type="submit" name="SUBMIT_PERMS" 
            value="Save Changes" i18n:attributes="value save-changes-button"/>
      </div>
    </form>

  </div>
</div>
</body>
</html>


=== Added File Zope3/src/zope/app/securitypolicy/browser/manage_roleform.pt ===
<html metal:use-macro="views/standard_macros/page">
<body>
<div metal:fill-slot="body">

  <p tal:define="status view/update"
     tal:condition="status"
     tal:content="status" />

  <p class="form-help" i18n:translate="">
    Helpful message explaining about how to set specific roles
  </p>

  <div tal:define="role 
          python:view.roleForID(request.get('role_to_manage'))" tal:omit-tag="">

    <p class="form-text" i18n:translate="">
      Permissions assigned to the role
      <strong tal:content="role/getTitle" 
              i18n:name="role_title">Great Master Guru</strong>
      (id: <strong tal:content="role/getId" 
              i18n:name="role_id">Zope.Some.Role</strong>)
    </p>


    <form action="AllRolePermissions.html" method="get">
      <input type="hidden" name="role_id" value="Role ID"
             tal:attributes="value role/getId" />

      <table width="100%" cellspacing="0" cellpadding="2" border="0" 
             nowrap="nowrap"
             tal:define="availableSettings 
                python:view.availableSettings(noacquire=True)">

        <tr class="list-header">
          <td align="left" valign="top"
              tal:repeat="setting availableSettings">
            <div class="form-label">
              <strong tal:content="setting/title">Allow</strong>
            </div>
          </td>
        </tr>

        <tr>
          <td align="left" valign="top"
              tal:repeat="settinginfo availableSettings">
            <div class="form-element">
              <select name="Unset:list" multiple="multiple" size="20"
                      tal:define="setting settinginfo/id"
                      tal:attributes="name string:${setting}:list">
              <option tal:repeat="permissioninfo role/permissionsInfo"
                      tal:content="permissioninfo/title"
                      tal:attributes="selected 
                         python:path('permissioninfo/setting') == setting;
                                      value permissioninfo/id"
                      >Sample Permission</option>
              </select>
            </div>
          </td>
        </tr>
      </table>

      <div class="form-element">
        <input class="form-element" type="submit" name="SUBMIT_ROLE" 
            value="Save Changes" i18n:attributes="value save-changes-button"/>
      </div>
    </form>

  </div>

</div>
</body>
</html>


=== Added File Zope3/src/zope/app/securitypolicy/browser/principal_permission_edit.pt ===
<html metal:use-macro="views/standard_macros/page">
<body>
<div metal:fill-slot="body"
  tal:define="rprincipal_id python:request['principal_id']">

  <h1 i18n:translate="">Permission settings for
    <span tal:replace="python:view.get_principal(rprincipal_id).getTitle()" 
          i18n:name="principal_title"/>
  </h1>

  <form action="unsetPermissions.html" method="post">
    <h2 i18n:translate="">Permission Settings</h2>

    <table>
      <tr>
        <td valign="top">
          <table border="0">
            <tr>
              <th colspan="2" align="center" 
                  i18n:translate="">Allowed Permissions</th>
            </tr>
            <tr tal:repeat="perm 
       python:view.get_set_permissions_for_principal(rprincipal_id, 'Allow')">
              <td><input type="checkbox" tal:attributes="name perm/getId"/></td>
              <td tal:content="perm/getTitle">Permission1</td>
            </tr>
            <tr tal:replace="nothing">
              <td><input type="checkbox" name="permission_ids" /></td>
              <td>Permission2</td>
            </tr>
            <tr tal:replace="nothing">
              <td><input type="checkbox" name="permission_ids" /></td>
              <td>Permission3</td>
            </tr>
            <tr tal:replace="nothing">
              <td><input type="checkbox" name="permission_ids" /></td>
              <td>Permission5</td>
            </tr>
          </table>
        </td>
        <td valign="top"> 
          <table border="0">
            <tr >
              <th colspan="2" align="center" 
                  i18n:translate="">Denied Permissions</th>
            </tr>
            <tr tal:repeat="perm 
       python:view.get_set_permissions_for_principal(rprincipal_id, 'Deny')">
              <td>
                <input type="checkbox" tal:attributes="name perm/getId" />
              </td>
              <td tal:content="perm/getTitle">Permission1</td>
            </tr>
            <tr tal:replace="nothing">
              <td><input type="checkbox" name="permission_ids" /></td>
              <td>Permission2</td>
            </tr>
          </table>
        </td>
      </tr>
      <tr>
        <td colspan="2" align="center">
          <input type="submit" name="unset" 
                 value="Remove selected permission settings" 
                 i18n:attributes="value"/>
        </td>
      </tr>
    </table>
  </form>

  <p>&nbsp;</p>

  <form action="./" method="post">
    <h2 i18n:translate="">Add permission settings</h2>

    <table>
      <tr>
        <td>
          <select name="permissions" multiple="multiple">
            <option 
              tal:repeat="perm 
                python:view.get_unset_permissions_for_principal(rprincipal_id)"
              tal:attributes="value perm/getId"
              tal:content="perm/getTitle">Perm1</option>
            <option tal:replace="nothing">Perm2</option>
            <option tal:replace="nothing">Perm3</option>
          </select>
        </td>        
        <td valign="center">
          <p>
            <input type="submit" name="grantPermissions.html:method" 
                   value="Grant" i18n:attributes="value grant-button"/>
          </p>
          <p>
            <input type="submit" name="denyPermissions.html:method"
                   value="Deny" i18n:attributes="value grant-button"/>
          </p>
        </td>
      </tr>
    </table>
  </form>

</div>
</body>
</html>


=== Added File Zope3/src/zope/app/securitypolicy/browser/principal_role_association.pt ===
<html metal:use-macro="views/standard_macros/dialog">
<body>
<div metal:fill-slot="body">

   <p tal:define="status view/update"
      tal:condition="status"
      tal:content="status" />

   <metal:block define-macro="formbody"
      tal:define="hasFilter python:request.get('Filter', None)">

   <div tal:condition="not: hasFilter">
     <span class="message" i18n:translate="">Apply filter</span>
     <form action="@@PrincipalRoles.html"
           method="POST"
           tal:attributes="action request/URL">
       <span i18n:translate="">Principal(s)</span>:
       <select name="principals:list" multiple="multiple">
         <option tal:repeat="principal view/getAllPrincipals"
                 tal:attributes="value principal/getId"
                 tal:content="principal/getTitle">my title</option>
       </select>

       <span i18n:translate="">Role(s)</span>:
       <select name="roles:list" multiple="multiple">
         <option tal:repeat="role view/getAllRoles"
                 tal:attributes="value role/getId"
                 tal:content="role/getTitle">my title</option>
       </select>

       <input type="submit" name="Filter" value="Filter"
              i18n:attributes="value filter-button"/>
     </form>

   </div>

   <div tal:condition="hasFilter">
     <div class="principalRolesGrid"
          tal:define="principalRoleGrid view/createGrid">

       <span tal:define="
           global listPrincipals principalRoleGrid/principals;
           global listRoles principalRoleGrid/roles;
           global listValues principalRoleGrid/listAvailableValues" />

       <form action="@@PrincipalRoles.html"
             method="POST"
             tal:attributes="action request/URL">
         <table>
           <tr class="roleHeading">
             <td class="principal">
               &nbsp;
             </td>
             <td class="role" tal:repeat="role listRoles"
                              tal:content="role/getTitle">
               Role Id
             </td>
           </tr>

           <tr class="principalRoleRow" tal:repeat="principal listPrincipals">
             <td class="principalLabel" tal:content="string:${principal/getLogin} (${principal/getTitle|principal/getLogin})">
               Principal Id
             </td>

             <td class="principalRole" tal:repeat="role listRoles">
               <select name="grid.role.principal:records"
                       tal:attributes="
                           name string:grid.${role/getId}.${principal/getId}"
                       tal:define="selectedValue
                                   python:principalRoleGrid.getValue(
                                              principal.getId(),
                                              role.getId()
                                              )" >
                 <option value="" tal:repeat="defaultValue listValues"
                         tal:attributes="
                             selected python:defaultValue==selectedValue;
                             value defaultValue;
                             debugsel selectedValue"
                        tal:content="defaultValue">
                   &nbsp;
                 </option>
               </select>
             </td>
           </tr>

         </table>

         <input type="hidden" name="principals:list"
                tal:repeat="principal listPrincipals"
                tal:attributes="value principal/getId" />

         <input type="hidden" name="roles:list"
                tal:repeat="role listRoles"
                tal:attributes="value role/getId" />

	 <metal:block define-slot="buttons">

	 <input type="submit" name="APPLY" value="Apply"
                i18n:attributes="value apply-button"/>

	 </metal:block>

       </form>

     </div>
   </div>

   </metal:block>

</div>
</body>
</html>


=== Added File Zope3/src/zope/app/securitypolicy/browser/principalpermissionview.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Principal Permission View Classes

$Id: principalpermissionview.py,v 1.1 2004/02/27 12:46:31 philikon Exp $
"""
import time

from zope.component import getService, getAdapter
from zope.publisher.browser import BrowserView

from zope.app.pagetemplate.viewpagetemplatefile import ViewPageTemplateFile
from zope.app.security.settings import Allow, Deny, Unset
from zope.app.services.servicenames import Permissions, Authentication

from zope.app.securitypolicy.interfaces import IPrincipalPermissionManager
from zope.app.securitypolicy.interfaces import IPrincipalPermissionMap


class PrincipalPermissionView(BrowserView):

    index = ViewPageTemplateFile('principal_permission_edit.pt')

    def get_permission_service(self):
        return getService(self.context, Permissions)

    def get_principal(self, principal_id):
        return getService(self.context,
                          Authentication
                          ).getPrincipal(principal_id)

    def unsetPermissions(self, principal_id, permission_ids, REQUEST=None):
        """Form action unsetting a principals permissions"""
        permission_service = self.get_permission_service()
        principal = self.get_principal(principal_id)
        ppm = getAdapter(self.context, IPrincipalPermissionManager)

        for perm_id in permission_ids:
            permission = permission_service.getPermission(perm_id)
            ppm.unsetPermissionForPrincipal(permission , principal)

        if REQUEST is not None:
            return self.index(message="Settings changed at %s"
                                        % time.ctime(time.time()))

    def grantPermissions(self, principal_id, permission_ids, REQUEST=None):
        """Form action granting a list of permissions to a principal"""
        permission_service = self.get_permission_service()
        principal = self.get_principal(principal_id)
        ppm = getAdapter(self.context, IPrincipalPermissionManager)

        for perm_id in permission_ids:
            permission = permission_service.getPermission(perm_id)
            ppm.grantPermissionToPrincipal(permission , principal)
        if REQUEST is not None:
            return self.index(message="Settings changed at %s"
                                        % time.ctime(time.time()))

    def denyPermissions(self, principal_id, permission_ids, REQUEST=None):
        """Form action denying a list of permissions for a principal"""
        permission_service = self.get_permission_service()
        principal = self.get_principal(principal_id)
        ppm = getAdapter(self.context, IPrincipalPermissionManager)

        for perm_id in permission_ids:
            permission = permission_service.getPermission(perm_id)
            ppm.denyPermissionToPrincipal(permission , principal)
        if REQUEST is not None:
            return self.index(message="Settings changed at %s"
                                        % time.ctime(time.time()))

    # Methods only called from the zpt view
    def getUnsetPermissionsForPrincipal(self, principal_id):
        """Returns all unset permissions for this principal"""

        ppmap = getAdapter(self.context, IPrincipalPermissionMap)
        principal = self.get_principal(principal_id)
        perm_serv = getService(self.context, Permissions)
        result = []
        for perm in perm_serv.getPermissions():
            if ppmap.getSetting(perm, principal) == Unset:
                result.append(perm)

        return result

    def getPermissionsForPrincipal(self, principal_id, setting_name):
        """Return a list of permissions with the given setting_name
           string for the principal.

           Return empty list if there are no permissions.
        """

        ppmap = getAdapter(self.context, IPrincipalPermissionMap)
        principal = self.get_principal(principal_id)

        permission_settings = ppmap.getPermissionsForPrincipal(principal)
        setting_map = {'Deny': Deny, 'Allow':Allow}
        asked_setting = setting_map[setting_name]

        result = []
        for permission, setting in permission_settings:
            if asked_setting == setting:
                result.append(permission)

        return result


=== Added File Zope3/src/zope/app/securitypolicy/browser/principalroleview.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Management view component for principal-role management (Zope2's
"local roles").

$Id: principalroleview.py,v 1.1 2004/02/27 12:46:31 philikon Exp $
"""
from datetime import datetime

from zope.component import getService, getAdapter
from zope.app.i18n import ZopeMessageIDFactory as _
from zope.app.security.settings import Unset, Deny, Allow
from zope.app.services.servicenames import Authentication

from zope.app.securitypolicy.interfaces import IPrincipalRoleManager
from zope.app.securitypolicy.interfaces import IPrincipalRoleMap

class PrincipalRoleView:

    def getAllPrincipals(self):
        principals = getattr(self, '_principals', None)
        if principals is None:
            principals = self._principals = getService(
                self.context, Authentication
                ).getPrincipals('')
        return principals

    def getAllRoles(self):
        roles = getattr(self, '_roles', None)
        if roles is None:
            roles = self._roles = getService(self.context, "Roles"
                ).getRoles()
        return roles

    def createGrid(self, principals=None, roles=None):
        if principals is None:
            principals = self.request.get('principals')
            if principals is None:
                principals = self.getAllPrincipals()
            else:
                # Ugh, we have ids, but we want objects
                auth_service = getService(self.context, Authentication)
                principals = [auth_service.getPrincipal(principal)
                              for principal in principals]


        if roles is None:
            roles = self.request.get('roles')
            if roles is None:
                roles = self.getAllRoles()
            else:
                # Ugh, we have ids, but we want objects
                # XXX This code path needs a test
                role_service = getService(self.context, 'Roles')
                roles = [role_service.getRole(role)
                         for role in roles]

        return PrincipalRoleGrid(principals, roles, self.context)

    def update(self, testing=None):
        status = ''

        if 'APPLY' in self.request:
            principals = self.request.get('principals')
            roles = self.request.get('roles')
            prm = getAdapter(self.context, IPrincipalRoleManager)
            for role in roles:
                for principal in principals:
                    name = 'grid.%s.%s' % (role, principal)
                    setting = self.request.get(name, 'Unset')
                    if setting == 'Unset':
                        prm.unsetRoleForPrincipal(role, principal)
                    elif setting == 'Allow':
                        prm.assignRoleToPrincipal(role, principal)
                    elif setting == 'Deny':
                        prm.removeRoleFromPrincipal(role, principal)
                    else:
                        raise ValueError("Incorrect setting %s" % setting)

            formatter = self.request.locale.dates.getFormatter(
                'dateTime', 'medium')
            status = _("Settings changed at ${date_time}")
            status.mapping = {'date_time': formatter.format(datetime.utcnow())}

        return status

class PrincipalRoleGrid:

    def __init__(self, principals, roles, context):
        self._principals = principals
        self._roles = roles
        self._grid = {}

        map = getAdapter(context, IPrincipalRoleMap)

        for role in roles:
            rid = role.getId()
            for principal in principals:
                pid = principal.getId()
                setting = map.getSetting(rid, pid)
                self._grid[(pid, rid)] = setting.getName()

    def principals(self):
        return self._principals

    def principalIds(self):
        return [p.getId() for p in self._principals]

    def roles(self):
        return self._roles

    def roleIds(self):
        return [r.getId() for r in self._roles]

    def getValue(self, principal_id, role_id):
        return self._grid[(principal_id, role_id)]

    def listAvailableValues(self):
        return (Unset.getName(), Allow.getName(), Deny.getName())


=== Added File Zope3/src/zope/app/securitypolicy/browser/role_service.gif ===
  <Binary-ish file>

=== Added File Zope3/src/zope/app/securitypolicy/browser/rolepermissionview.py ===
##############################################################################
#
# Copyright (c) 2001, 2002 Zope Corporation and Contributors.
# All Rights Reserved.
#
# This software is subject to the provisions of the Zope Public License,
# Version 2.0 (ZPL).  A copy of the ZPL should accompany this distribution.
# THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED
# WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
# WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS
# FOR A PARTICULAR PURPOSE.
#
##############################################################################
"""Role Permission View Classes

$Id: rolepermissionview.py,v 1.1 2004/02/27 12:46:31 philikon Exp $
"""
from datetime import datetime

from zope.component import getService, getAdapter
from zope.app.i18n import ZopeMessageIDFactory as _
from zope.app.security.settings import Unset, Allow, Deny
from zope.app.services.servicenames import Permissions

from zope.app.securitypolicy.interfaces import IRolePermissionManager
from zope.app.securitypolicy.permissionroles import PermissionRoles
from zope.app.securitypolicy.rolepermission import RolePermissions

class RolePermissionView:

    def roles(self):
        roles = getattr(self, '_roles', None)
        if roles is None:
            roles = self._roles = getService(
                self.context, "Roles"
                ).getRoles()
        return roles

    def permissions(self):
        permissions = getattr(self, '_permissions', None)
        if permissions is None:
            permissions = self._permissions = getService(
                self.context, Permissions
                ).getPermissions()
        return permissions

    def availableSettings(self, noacquire=False):
        aq = {'id': Unset.getName(), 'shorttitle': ' ',
              'title': _('permission-acquire', 'Acquire')}
        rest = [{'id': Allow.getName(), 'shorttitle': '+',
                 'title': _('permission-allow', 'Allow')},
                {'id': Deny.getName(), 'shorttitle': '-',
                 'title': _('permission-deny', 'Deny')},
                ]
        if noacquire:
            return rest
        else:
            return [aq]+rest

    def permissionRoles(self):
        context = self.context
        roles = self.roles()
        return [PermissionRoles(permission, context, roles)
                for permission in self.permissions()]

    def permissionForID(self, pid):
        context = self.context
        roles = self.roles()
        perm = getService(context, Permissions
                          ).getPermission(pid)
        return PermissionRoles(perm, context, roles)

    def roleForID(self, rid):
        context = self.context
        permissions = self.permissions()
        role = getService(context, "Roles"
                          ).getRole(rid)
        return RolePermissions(role, context, permissions)


    def update(self, testing=None):
        status = ''
        changed = False

        if 'SUBMIT' in self.request:
            roles       = [r.getId() for r in self.roles()]
            permissions = [p.getId() for p in self.permissions()]
            prm         = getAdapter(self.context, IRolePermissionManager)
            for ip in range(len(permissions)):
                rperm = self.request.get("p%s" % ip)
                if rperm not in permissions: continue
                for ir in range(len(roles)):
                    rrole = self.request.get("r%s" % ir)
                    if rrole not in roles: continue
                    setting = self.request.get("p%sr%s" % (ip, ir), None)
                    if setting is not None:
                        if setting == Unset.getName():
                            prm.unsetPermissionFromRole(rperm, rrole)
                        elif setting == Allow.getName():
                            prm.grantPermissionToRole(rperm, rrole)
                        elif setting == Deny.getName():
                            prm.denyPermissionToRole(rperm, rrole)
                        else:
                            raise ValueError("Incorrect setting: %s" % setting)
            changed = True

        if 'SUBMIT_PERMS' in self.request:
            prm = getAdapter(self.context, IRolePermissionManager)
            roles = self.roles()
            rperm = self.request.get('permission_id')
            settings = self.request.get('settings', ())
            for ir in range(len(roles)):
                rrole = roles[ir].getId()
                setting = settings[ir]
                if setting == Unset.getName():
                    prm.unsetPermissionFromRole(rperm, rrole)
                elif setting == Allow.getName():
                    prm.grantPermissionToRole(rperm, rrole)
                elif setting == Deny.getName():
                    prm.denyPermissionToRole(rperm, rrole)
                else:
                    raise ValueError("Incorrect setting: %s" % setting)
            changed = True

        if 'SUBMIT_ROLE' in self.request:
            role_id = self.request.get('role_id')
            prm = getAdapter(self.context, IRolePermissionManager)
            allowed = self.request.get(Allow.getName(), ())
            denied = self.request.get(Deny.getName(), ())
            for permission in self.permissions():
                rperm = permission.getId()
                if rperm in allowed and rperm in denied:
                    raise ValueError("Incorrect setting for %s" % rperm)
                if rperm in allowed:
                    prm.grantPermissionToRole(rperm, role_id)
                elif rperm in denied:
                    prm.denyPermissionToRole(rperm, role_id)
                else:
                    prm.unsetPermissionFromRole(rperm, role_id)
            changed = True

        if changed:
            formatter = self.request.locale.dates.getFormatter(
                'dateTime', 'medium')
            status = _("Settings changed at ${date_time}")
            status.mapping = {'date_time': formatter.format(datetime.utcnow())}

        return status





More information about the Zope3-Checkins mailing list