Exemplo n.º 1
0
 def __call__(self):
     params = self.get_base_params()
     form, request = None, self.request
     is_a_post = request.method == 'POST'
     deleting = request.params.get('user_action', '') == 'delete'
     if is_a_post and deleting:
         items = [a[1]
                  for a in request.POST.items()
                  if a[0] == 'delete']
         todelete = session.query(
             apexmodels.AuthUser).filter(
                 apexmodels.AuthUser.id.in_(items)
             ).all()
         noecho = [apexmodels.delete_user(i) for i in todelete]
         session.commit()
         request.session.flash(_('Items have been deleted'), 'info')
     action = request.params.get('user_action', '')
     users = session.query(apexmodels.AuthUser).order_by(apexmodels.AuthUser.login,
                                                         apexmodels.AuthUser.username,
                                                         apexmodels.AuthUser.email).all()
     rdata = []
     for u in users:
         item = {
             'id': u.id,
             'username': u.username,
             'login': u.login,
             'email': u.email,
             'deletable': True,
         }
         rdata.append(item)
     params['users'] = rdata
     return render_to_response(self.template, params, request)
Exemplo n.º 2
0
def register_default_acls(session, force=False):
    # authentication settings
    if not force:
        force = not get_registry_key('mobyle2.configured_acl', False)
    if not force:
        return
    for p in default_acls:
        try:
            perm = Permission.by_name(p)
        except:
            import pdb;pdb.set_trace()  ## Breakpoint ##

        roles = default_acls[p]
        for role in roles:
            access = roles[role]
            orole = Role.by_name(role)
            if access:
                if not perm in orole.global_permissions:
                    orole.global_permissions.append(perm)
                    session.add(orole)
                    session.commit()
            else:
                if perm in orole.global_permissions:
                    del orole.global_permissions[orole.global_permissions.index(perm)]
                    session.add(orole)
                    session.commit()
            set_registry_key('mobyle2.configured_acl', "1")
    session.flush()
Exemplo n.º 3
0
def create_local_server(registry=None):
    server_name = LOCAL_SERVER_NAME
    s = None
    try:
        s = Server.by_name(server_name)
    except NoResultFound, e:
        s = Server(name=LOCAL_SERVER_NAME,)
        session.add(s)
        session.commit()
Exemplo n.º 4
0
def user_created(event):
    request = event.request
    user = event.user
    if not session.query(User).filter_by(id=user.id).all():
        newuser = User(base_user=user, status='a')
        session.add(newuser)
        session.commit()
    else:
        message = _(u'a user with this id %d already exists' % user.id)
        request.session.flash(message, 'error')
Exemplo n.º 5
0
 def construct(self, commit=True):
     # !IMPORTANT! Call autolink on localhost server when we traverse /project/servers
     # link here localhost node
     localhost = Server.get_local_server()
     modified = False
     if not localhost in self.servers:
         modified = True
         self.servers.append(localhost)
     if commit and modified:
         session.add(self)
         session.commit()
Exemplo n.º 6
0
    def __call__(self):

        global_auth_settings = [u'auth.allow_anonymous',
                                u'auth.self_registration',
                                u'auth.use_captcha']

        global_auth_text_settings = [u'auth.recaptcha_public_key',
                                     u'auth.recaptcha_private_key']
        request = self.request
        controls = self.request.POST.items()
        keys = session.query(r.Registry).filter(r.Registry.name.in_(
                                                   global_auth_settings)
                                                ).all()
        tkeys = session.query(r.Registry).filter(r.Registry.name.in_(
                                                 global_auth_text_settings)
                                                 ).all()
        items = OrderedDict()
        authbackend_schema = colander.SchemaNode(colander.Mapping())
        struct = {}
        for i in keys:
            authbackend_schema.add(
                colander.SchemaNode(colander.Boolean(),
                                    name=i.name.replace('auth.', ''),
                                    default=bool_values.get(i.value.lower(),
                                                            False),
                                    missing=None
                                   ))
        for i in tkeys:
            authbackend_schema.add(
                colander.SchemaNode(colander.String(),
                                    name=i.name.replace('auth.', ''),
                                    default=i.value and i.value or '',
                                    missing=None
                                   ))
        form = w.Form(request, authbackend_schema, buttons=(_('Send'),), use_ajax=True)

        if request.method == 'POST':
            try:
                struct = form.validate(controls)
                restart = True
                for obj in keys + tkeys:
                    ki = obj.name.replace('auth.', '')
                    # store settings in database
                    value = struct.get(ki, False)
                    if obj.value != value:
                        obj.value = value
                        session.commit()
                        restart = True
                if restart:
                    self.request.registry.notify(RegenerateVelruseConfigEvent(
                                                    self.request)
                                                 )
            except  ValidationFailure, e:
                pass
Exemplo n.º 7
0
def get_registry_key(key, default=notset, as_bool=True):
    session = DBSession()
    res = None
    try:
        res = session.query(Registry).filter(Registry.name == key).one().value
        if as_bool:
            res = asbool(res)
    except exc.NoResultFound, e:
        if isinstance(default, NotSet):
            raise
        else:
            res = default
Exemplo n.º 8
0
    def by_participation(cls, usr):
        # fiest get user projects
        res = []

        def uniq_append(items):
            for p in items:
                if not p.resource in res:
                    res.append(p.resource)

        uniq_append(session.query(ProjectUserRole).filter_by(user=usr).all())
        for g in usr.groups:
            uniq_append(session.query(ProjectGroupRole).filter_by(group=g).all())
        return res
Exemplo n.º 9
0
 def __call__(self, form, field):
     session = DBSession()
     if field.data and isinstance(field.data, basestring):
         data = field.data.strip().lower()
         users = session.query(
             AuthUser).filter(
                 func.lower(AuthUser.email) == data).all()
         if len(users):
             self.message = field.gettext(
                 _(u'This email already exists, '
                   'please choose another one or '
                   'retrieve your identity.'))
             field.errors[:] = []
             raise validators.StopValidation(self.message)
Exemplo n.º 10
0
 def __call__(self):
     form, request = None, self.request
     gurl = "%s@@ajax_groups_list" % (
         self.request.resource_url(self.request.context)
     )
     is_a_get = request.method == 'GET'
     is_a_post = request.method == 'POST'
     params = self.get_base_params()
     r_types = {'users':_('Users'), 'groups': _('Groups',)}
     rid = -666
     try:
         rid = int(request.params.get('userid', '-666'))
     except:
         pass
     usr = None
     try:
         usr = session.query(
             user.User).filter(
                 user.User.id==int(rid)).first()
     except:
         pass
     def existing_user_validator(node, value, column):
         item, value = None, value.strip()
         try:
             item = session.query(apexmodels.AuthUser).filter(
                 getattr(apexmodels.AuthUser, column) == value).first()
         except Exception, e:
             raise colander.Invalid(node, _('Unknown Error: %s' % e))
         if item is not None:
             if usr.id != item.id:
                 raise colander.Invalid(node, _('Already exists'))
Exemplo n.º 11
0
 def existing_user_validator(node, value, column):
     item, value = None, value.strip()
     try:
         item = session.query(apexmodels.AuthUser).filter(
             getattr(apexmodels.AuthUser, column) == value).first()
     except Exception, e:
         raise colander.Invalid(node, _('Unknown Error: %s' % e))
def insert_update_service(name,stype,description,package,classification):
    """Insert a service in the database as belonging
    to the local - and only - server of the public project."""
    try:
	svc = session.query(Service).filter_by(name=name,
				             server=public_project.servers[0],
				             project=public_project).first()
	if not svc:
	    logging.info("service %s new, adding to the server" % name)
            svc = Service()
            svc.name = name
            svc.server = public_project.servers[0]
            svc.project = public_project
	    session.add(svc)
	else:
	    logging.info("service %s already here, updating" % name)
        svc.description = description
        svc.package = package
        svc.classification = classification
        svc.type = stype
        session.commit()
        return svc
    except:
	session.rollback()
	raise
Exemplo n.º 13
0
 def __call__(self):
     params = self.get_base_params()
     form, request = None, self.request
     is_a_post = request.method == 'POST'
     adding = request.params.get('__formid__', '') == 'add_group'
     default_groups = [a[0]
                       for a in apexmodels.get_default_groups(
                           request.registry.settings)]
     deleting = request.params.get('group_action', '') == 'delete'
     class GroupSH(colander.MappingSchema):
         name = colander.SchemaNode(
             colander.String(),
             title = _('Group name'),
             validator = colander.All(
                 v.not_empty_string,
                 v.existing_group,
             )
         )
         description = colander.SchemaNode(colander.String(), title=_('Group description'),)
     add_form = deform.Form( GroupSH(), buttons=(_('Send'),), formid = 'add_group')
     if is_a_post and deleting:
         items = [a[1]
                  for a in request.POST.items()
                  if a[0] == 'delete' and not a[1] in default_groups]
         todelete = session.query(
             user.Group).filter(
                 se.and_(
                     user.Group.id.in_(items),
                     se.not_(user.Group.name.in_(default_groups))
                 )
             ).all()
         noecho = [session.delete(i) for i in todelete]
         session.commit()
         request.session.flash(_('Items have been deleted'), 'info')
     if is_a_post and adding:
         controls = request.POST.items()
         try:
             data = add_form.validate(controls)
             group = session.query(
                 user.Group).filter(
                     user.Group.name == data['name']
                 ).first()
             if not group:
                 rl = user.Group(name=data['name'], description=data['description'])
                 session.add(rl)
                 session.commit()
                 request.session.flash(_('Group added: %s' % rl.name, 'info'))
                 params['add_form'] = add_form.render()
         except Exception, e:
             params['add_form'] = e.render()
Exemplo n.º 14
0
 def create_directory(self):
     p = self
     if p.id is None:
         raise Exception("Project.create: invalid project state")
     subdir = "%s" % (p.id / 1000)
     pdir = os.path.join(p.projects_dir, subdir, "%s" % p.id)
     tries = 0
     if os.path.exists(pdir):
         while tries < 10000:
             pdir = os.path.join("%s_%s" % (pdir, tries))
             if not os.path.exists(pdir):
                 break
     if not os.path.exists(pdir):
         os.makedirs(pdir)
         p._directory = pdir
         session.add(p)
         session.commit()
     else:
         raise Exception("Project directory Alrealdy exists")
Exemplo n.º 15
0
    def __call__(self):
        params = self.get_base_params()
        form, request = None, self.request
        is_a_post = request.method == 'POST'
        adding = request.params.get('__formid__', '') == 'add_permission'
        deleting = request.params.get('permission_action', '') == 'delete'
        class PermissionSH(colander.MappingSchema):
            name = colander.SchemaNode(
                colander.String(), title=_('Permission name'), validator = colander.All(
                    v.not_empty_string,
                    v.existing_group,
                )
            )
            description = colander.SchemaNode(colander.String(), title=_('Permission description'),)
        add_form = deform.Form( PermissionSH(), buttons=(_('Send'),), formid = 'add_permission')
        if is_a_post and deleting:
            items = [a[1]
                     for a in request.POST.items()
                     if a[0] == 'delete']
            todelete = session.query(
                auth.Permission).filter(
                    se.and_(
                        auth.Permission.id.in_(items),
                        se.not_(auth.Permission.name.in_(auth.default_permissions.keys()))
                    )

                ).all()
            noecho = [session.delete(i) for i in todelete]
            session.commit()
            request.session.flash(_('Items have been deleted'), 'info')
        if is_a_post and adding:
            controls = request.POST.items()
            try:
                data = add_form.validate(controls)
                permission = session.query(
                    auth.Permission).filter(
                        auth.Permission.name == data['name']
                    ).first()
                if not permission:
                    rl = auth.Permission(name=data['name'],
                              description=data['description'])
                    session.add(rl)
                    session.commit()
                    request.session.flash(_('Permission added: %s' % rl.name, 'info'))
                    params['add_form'] = add_form.render()
            except Exception, e:
                params['add_form'] = e.render()
Exemplo n.º 16
0
def register_default_permissions(session):
    # authentication settings
    for k in default_permissions:
        try:
            session.query(Permission).filter(Permission.name == k).one()
        except NoResultFound, e:
            try:
                session.add(
                    Permission(name=k, description=default_permissions[k])
                )
                session.commit()
            except IntegrityError:
                session.rollback()
Exemplo n.º 17
0
def user_deleted(event):
    request = event.request
    usr = event.user
    # delete user projects and associated acls.
    for p in User.by_id(usr.id).projects[:]:
        try:
            res = []
            res.extend(ProjectGroupRole.by_resource(p))
            res.extend(ProjectUserRole.by_resource(p))
            res.append(p)
            modified = False
            for i in res:
                modified = True
                session.delete(i)
            if modified:
                session.commit()
        except Exception, e:
            error = 'Default project for %s cannot be deleted' % usr.username
            message = '%s' % e
            if message: error += ' : %s' % message
            logging.getLogger('mobyle2.delete_user').error(error)
Exemplo n.º 18
0
def create_user(nick, password, superuser=True):
    """."""
    t = [amodels.AuthUser.get_by_login(nick) is None,
          amodels.AuthUser.get_by_username(nick) is None]
    if False in t: raise Exception('%s already exists'%nick)
    usr = amodels.create_user(**{
        'login':nick,
        'username':nick,
        'password':password,
        'email':'%s@mobyle2internal'%nick,
    })
    u = user.User.by_id(usr.id)
    roles, sroles = [], ["internal_user", "external_user"]
    if superuser:
        sroles.append("portal_administrator")
    for r in sroles:
        roles.append(auth.Role.by_name(auth.R[r]))
    for r in roles:
        u.global_roles.append(r)
    session.add(u)
    session.commit()
Exemplo n.º 19
0
 def __call__(self):
     #_ = self.translate
     request = self.request
     struct = {}
     params = {}
     params.update(get_base_params(self))
     form = self.form
     if request.method == 'POST':
         controls = request.POST.items()
         # we are in regular post, just registering data in database
         try:
             struct = form.validate(controls)
             fmap = self.fmap
             kwargs = {}
             cstruct = copy.deepcopy(struct)
             for k in cstruct:
                 kwargs[fmap.get(k, k)] = cstruct[k]
             try:
                 kwargs['user'] = user.User.by_id(self.request.user.id)
                 ba = project.Project.create(**kwargs)
                 self.request.session.flash(
                     _('A new project has been created'),
                     'info')
                 item = self.request.root['projects']["%s" % ba.id]
                 url = request.resource_url(item)
                 return HTTPFound(location=url)
             except Exception, e:
                 message = _(u'You can try to change some '
                             'settings because an exception occured '
                             'while adding your new project '
                             ': ${msg}',
                             mapping={'msg': u'%s' % e})
                 self.request.session.flash(message, 'error')
                 session.rollback()
             # we are set, create the request
             params['f_content'] = form.render(struct)
         except  ValidationFailure, e:
             params['f_content'] = e.render()
Exemplo n.º 20
0
def register_default_roles(session, force=False):
    # authentication settings
    if not force:
        force = not get_registry_key('mobyle2.configured_roles', False)
    if not force:
        return
    for k in default_roles:
        try:
            session.query(Role).filter(Role.name == k).one()
        except NoResultFound, e:
            try:
                session.add(
                    Role(name=k, description=default_roles[k])
                )
                session.commit()
            except IntegrityError:
                session.rollback()
Exemplo n.º 21
0
 def __call__(self):
     term = '%(%)s%(s)s%(%)s' % {
         's': self.request.params.get('term', '').lower(),
         '%': '%',
     }
     table = userm.Group
     rows = session.query(table).filter(
         table.name.ilike(term)
     ).order_by(table.name)
     data = []
     for row in rows:
         label = row.name
         item = ("%s"%row.id, label)
         if not item in data:
             data.append(item)
     return data
Exemplo n.º 22
0
def set_registry_key(key, value):
    session = DBSession()
    res = None
    try:
        try:
            res = session.query(Registry).filter(Registry.name == key).one()
            res.value = value
        except exc.NoResultFound, e:
            res = Registry(key, value)
            session.add(res)
        session.commit()
Exemplo n.º 23
0
def not_existing_validator(node, values, table, label='item'):
    if isinstance(values, basestring):
        values = [values]
    errors = []
    for value in values:
        v = value
        if isinstance(v, tuple) or isinstance(v, tuple):
            v = v[0]
        item, v = None, (isinstance(v, int)) and v or v.strip()
        if not v: continue
        try:
            item = session.query(
                table).filter(table.id==int(v)).one()
        except Exception, e:
            pass
        if item is not None:
            continue
        errors.append(v)
Exemplo n.º 24
0
def velruse_config(config):
    settings = config.registry.settings

    settings['velruse.openid.store'] = 'mobyle2.core.velruse.get_sqlstore'
    #settings['velruse.openid.realm'] = settings.get('velruse.openid.realm', 'realm')
    key = 'velruse.store.'
    if not key+'url' in settings:
        key = 'sqlalchemy.'
    engine = engine_from_config(settings, key)
    providers = settings.get('velruse.providers', '')
    initialize_sql(engine)
    for ab in session.query(AuthenticationBackend).filter(
        AuthenticationBackend.enabled == True
    ):
        t = ab.backend_type
        if ab.backend_type in ['ldap']:
            providers += '\n%s' % 'velruse.providers.ldapprovider'
            url = 'ldap'
            if ab.use_ssl:
                url += 's'
            url += '://%s' % ab.hostname
            if ab.port:
                url +=':%s' % ab.port
            lk = 'velruse.providers.ldapprovider.urls'
            settings[lk] = settings.get(lk, '')+'\n%s' % url
            settings['velruse.providers.ldapprovider.basedn'] = ab.ldap_dn
        if ab.backend_type in ['openid',]:
            providers += '\n%s' % 'velruse.providers.openidconsumer'
            if ab.realm:
                settings['velruse.openid.realm'] = ab.realm
        if ab.backend_type in ['twitter', 'github', 'google', 'facebook']:
            providers += '\n%s' % 'velruse.providers.%s' % (t)
            settings['velruse.%s.consumer_key'    % (t)] = ab.username
            settings['velruse.%s.consumer_secret' % (t)] = ab.password
            if ab.authorize:
                if ab.backend_type in ['twitter', 'github', 'google', 'facebook']:
                    settings['velruse.%s.authorize' %(t)] = ab.authorize
                if ab.backend_type in ['github']:
                    settings['velruse.%s.scope' %(t)] = ab.authorize
		if ab.backend_type=='facebook':
		    settings['velruse.%s.app_id' %(t)] = ab.username
		    settings['velruse.%s.app_secret' %(t)] = ab.password
    settings['velruse.providers'] = providers
Exemplo n.º 25
0
 def __call__(self):
     #_ = self.translate
     request = self.request
     struct = {}
     params = self.get_base_params()
     form = self.form
     if request.method == 'POST':
         controls = request.POST.items()
         if self.for_ajax_form:
             params['f_content'] = form.render(controls)
         else:
             # we are in regular post, just registering data in database
             try:
                 struct = form.validate(controls)
                 fmap = self.fmap
                 kwargs = {}
                 cstruct = dict([(a, struct[a])
                                 for a in struct if not a == 'auth_backend_infos'] +
                                [(a, struct.get('auth_backend_infos', {})[a])
                                 for a in struct.get('auth_backend_infos', {})])
                 for k in cstruct:
                     kwargs[fmap.get(k, k)] = cstruct[k]
                 try:
                     ba = auth.AuthenticationBackend(**kwargs)
                     session.add(ba)
                     self.request.registry.notify(RegenerateVelruseConfigEvent(self.request))
                     session.commit()
                     self.request.session.flash(
                         _('A new authentication backend has been created'),
                         'info')
                     item = self.request.root['auths']["%s" % ba.id]
                     url = request.resource_url(item)
                     return HTTPFound(location=url)
                 except Exception, e:
                     message = _(u'You can try to change some '
                                 'settings because an exception occured '
                                 'while adding your new authbackend '
                                 ': ${msg}',
                                 mapping={'msg': u'%s' % e})
                     self.request.session.flash(message, 'error')
                     session.rollback()
                 # we are set, create the request
                 params['f_content'] = form.render(struct)
             except  ValidationFailure, e:
                 params['f_content'] = e.render()
Exemplo n.º 26
0
 def __call__(self):
     term = '%(%)s%(s)s%(%)s' % {
         's': self.request.params.get('term', '').lower(),
         '%': '%',
     }
     table = userm.User
     bu = apexmodels.AuthUser
     rows = session.query(table).join(bu).filter(
         se.and_(
             table.status == 'a',
             se.or_(bu.username.ilike(term),
                    bu.email.ilike(term),
                    bu.login.ilike(term),
                   )
         )
     ).order_by(bu.email, bu.username, bu.login).all()
     data = []
     for row in rows:
         u = row.base_user
         label = format_user_for_form(u)
         item = ("%s"%row.id, label)
         if not item in data:
             data.append(item)
     return data
Exemplo n.º 27
0
    def __call__(self):
        auths_list = self.request.resource_url(
            self.request.root['auths']
        ) + '@@list'

        class authbackend_delete_schema(colander.MappingSchema):
            submitted = colander.SchemaNode(
                colander.String(),
                widget=deform.widget.HiddenWidget(),
                default='true',
                validator=colander.OneOf(['true']),
                title=_('delete me'))
        params = self.get_base_params()
        request = self.request
        params['ab'] = ab = self.request.context.ab
        form = w.Form(request, authbackend_delete_schema(), buttons=(_('Send'),))
        params['f_content'] = form.render()
        if request.method == 'POST':
            controls = request.POST.items()
            # we are in regular post, just registering data in database
            try:
                struct = form.validate(controls)
                try:
                    session.delete(ab)
                    self.request.registry.notify(RegenerateVelruseConfigEvent(self.request))
                    session.commit()
                    self.request.session.flash(_('Authentication backend deleted'), 'error')
                    return HTTPFound(location=auths_list)
                except Exception, e:
                    message = _(u'You can try to change some '
                                'settings because an exception occured '
                                'while adding your new authbackend '
                                ': ${msg}',
                                mapping={'msg': u'%s' % e})
                    self.request.session.flash(message, 'error')
                    session.rollback()
            except  ValidationFailure, e:
                params['f_content'] = e.render()
Exemplo n.º 28
0
 def __call__(self):
     params = {'view': self}
     params.update(get_base_params(self))
     request = self.request
     params['ab'] = ab = self.request.context.project
     form = self.form
     if request.method == 'POST':
         controls = request.POST.items()
         # we are in regular post, just registering data in database
         try:
             struct = form.validate(controls)
             try:
                 fmap = self.fmap
                 kwargs = {}
                 cstruct = copy.deepcopy(struct)
                 for k in cstruct:
                     kwargs[fmap.get(k, k)] = cstruct[k]
                 for k in kwargs:
                     setattr(ab, k, kwargs[k])
                 session.add(ab)
                 session.commit()
                 self.request.session.flash(
                     _('Project has been updated'),
                     'info')
                 item = self.request.root['projects']["%s" % ab.id]
                 url = request.resource_url(item)
                 return HTTPFound(location=url)
             except Exception, e:
                 message = _(u'You can try to change some '
                             'settings because an exception occured '
                             'while editing your authbackend'
                             ': ${msg}',
                             mapping={'msg': u'%s' % e})
                 self.request.session.flash(message, 'error')
                 session.rollback()
         except  ValidationFailure, e:
             params['f_content'] = e.render()
Exemplo n.º 29
0
    def __call__(self):
        request = self.request
        params = self.get_base_params()
        roles = OrderedDict([(str(ro.id), ro)
                             for ro in session.query(auth.Role
                                      ).order_by(auth.Role.name).all()])
        permissions = OrderedDict([(str(p.id), p)
                                   for p in session.query(
                                       auth.Permission
                                   ).order_by(auth.Permission.name).all()])
        data = OrderedDict()
        params['data'] = data
        data['permissions'] = permissions
        data['roles'] = roles
        form = construct_schema_acls(request, permissions=permissions, roles=roles)

        if request.method == 'POST':
            try:
                controls = request.POST.items()
                data = form.validate(controls)
                perms = [permissions.get(pid, None)
                         for pid in data['roles']
                         if permissions.get(pid, None)]
                modified, error = False, False
                try:
                    for permission in perms:
                        mapping = data['roles'][str(permission.id)]
                        rles = [roles.get(rid, None)
                                for rid in mapping
                                if rid in roles]
                        for role in rles:
                            # maybe unactivate role
                            if not mapping[str(role.id)]:
                                if permission in role.global_permissions:
                                    modified = True
                                    role.global_permissions.pop(
                                        role.global_permissions.index(
                                            permission
                                        )
                                    )
                                    session.add(role)
                                    session.commit()
                            # maybe activate role
                            else:
                                if not permission in role.global_permissions:
                                    modified = True
                                    role.global_permissions.append(permission)
                                    session.add(role)
                                    session.commit()
                except Exception, e:
                    request.session.flash(_('Something goes wrong while saving access parameters: %s')%e, 'error')
                    error = True
                    # sql failure !
                    try:
                        session.rollback()
                    except:
                        pass
                if modified:
                    if not error:
                        request.session.flash(_('Access parameters have been saved'), 'info')
                    form = construct_schema_acls(request, permissions=permissions, roles=roles)
            except  ValidationFailure, e:
                params['form'] = e.render()
Exemplo n.º 30
0
 def __call__(self):
     form, request = None, self.request
     url = "%s@@ajax_users_list" % (
         self.request.resource_url(self.request.context)
     )
     gurl = "%s@@ajax_groups_list" % (
         self.request.resource_url(self.request.context)
     )
     is_a_get = request.method == 'GET'
     is_a_post = request.method == 'POST'
     params = self.get_base_params()
     r_types = {'users':_('Users'), 'groups': _('Groups',)}
     rid = -666
     try:
         rid = int(request.params.get('roleid', '-666'))
     except:
         pass
     role = None
     try:
         role = session.query(
             auth.Role).filter(auth.Role.id==int(rid)).first()
     except:
         pass
     params['role'] = role
     if role is not None:
         role_users = []
         role_groups = []
         def reset_default_users_groups(role, users, groups,):
             for l in users, groups:
                 while len(l) > 0:
                     l.pop()
             for u in role.global_users:
                users.append(
                     (u.id, format_user_for_form(u.base_user))
                 )
             for group in role.global_groups:
                 groups.append(
                     (group.id, group.name)
                 )
         reset_default_users_groups(role, role_users, role_groups)
         class UserS(colander.TupleSchema):
             id = colander.SchemaNode(colander.Int(), missing = '',)
             label = colander.SchemaNode(colander.String(), missing = '',)
         class GroupS(colander.TupleSchema):
             id = colander.SchemaNode(colander.Int(), missing = '',)
             label = colander.SchemaNode(colander.String(), missing = '',)
         class GroupSc(colander.SequenceSchema):
             group = GroupS(name="group", missing=tuple())
         class UserSc(colander.SequenceSchema):
             user = UserS(name="user", missing=tuple())
         class Members(colander.MappingSchema):
             users = UserSc(name="users", title=_('Users'),widget = widget.ChosenSelectWidget(url), default=role_users, validator = v.not_existing_user, missing=tuple(),)
             groups = GroupSc(name="groups", title=_('Groups'), widget = widget.ChosenSelectWidget(gurl), default=role_groups, validator = v.not_existing_group, missing=tuple(),)
         class Schema(colander.Schema):
             roleid = colander.SchemaNode(
                 colander.String(),
                 widget = deform.widget.HiddenWidget(),
                 validator = v.not_existing_role,
                 default = rid,
                 name = 'roleid',
                 title = _('Role'),
             )
             #name = colander.SchemaNode(
             #    colander.String(),
             #    widget = deform.widget.TextInputWidget(size=len('%s'%role.name)),
             #    default = role.name,
             #    name = 'role',
             #    title = _('Role'),
             #)
             description = colander.SchemaNode(
                 colander.String(),
                 widget = deform.widget.TextAreaWidget(),
                 default = role.description,
                 missing = '',
                 name = 'desc',
                 title = _('Description'),
             )
             members = Members(name="members")
         form = widget.Form(request,
                            Schema(title=_('Edit role %s' % role.name), validator=v.role_edit_form_global_validator),
                            buttons=(_('Send'),), formid = 'add_permission')
         if is_a_get:
             params['form'] = form.render()
         if is_a_post:
             try:
                 modified = False
                 controls = request.POST.items()
                 data  = form.validate(controls)
                 role = auth.Role.by_id(data['roleid'])
                 #if not role.name == data['name']:
                 #    role.name = data['name']
                 #    form.schema['name'].default = role.name
                 #    modified = True
                 if not role.description == data['description']:
                     role.description = data['description']
                     form.schema['description'].default = role.description
                     modified = True
                 users = []
                 for uid, label in data['members']['users']:
                     u = user.User.by_id(uid)
                     users.append(u)
                 groups = []
                 for uid, label in data['members']['groups']:
                     u = user.Group.by_id(uid)
                     groups.append(u)
                 for ilist, olist in ((users, role.global_users), (groups, role.global_groups)):
                     if not ilist:
                         modified = True
                         for item in olist[:]:
                             del olist[olist.index(item)]
                     else:
                         for item in ilist:
                             if not item in olist:
                                 modified = True
                                 olist.append(item)
                         for item in olist[:]:
                             if not item in ilist:
                                 del olist[olist.index(item)]
                                 modified = True
                 if modified:
                     session.add(role)
                     try:
                         session.commit()
                         reset_default_users_groups(role, role_users, role_groups)
                         request.session.flash(_('Role modified', 'info'))
                     except Exception, e:
                         try:
                             session.rollback()
                         except:
                             pass
                         request.session.flash(
                             _('Something went wrong'
                               'while modifying role: %s') % e)
                 params['form'] = form.render()
             except deform.exception.ValidationFailure, e:
                 params['form'] = e.render()