Exemple #1
0
def construct_schema_acls(request, permissions=None, roles=None):
    if not permissions: permissions = {}
    if not roles: roles = {}
    form_schema = colander.SchemaNode(colander.Mapping())
    roles_schema = widget.TableNode(colander.Mapping(), name='roles')
    append = True
    for i, pid in enumerate(permissions):
        p = permissions[pid]
        perm = widget.TrNode(colander.Mapping(),
                             name="%s"%p.id, title=p.description)
        for rlid in roles:
            rl = roles[rlid]
            if not rl.description in roles_schema.widget.headers:
                roles_schema.widget.headers.append(_(rl.description))
            role = colander.SchemaNode(
                colander.Boolean(),
                    name = "%s"%rl.id,
                    title = _(rl.description),
                    default=p in rl.global_permissions,
                    missing=None,
                )
            perm.add(role)
        append = False
        roles_schema.add(perm)
    form_schema.add(roles_schema)
    form = deform.Form(form_schema,
                       buttons=(_('Send'),),
                       use_ajax=True,
                       renderer=widget.renderer_factory(request))
    return form
Exemple #2
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'))
Exemple #3
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()
Exemple #4
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)
Exemple #5
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))
Exemple #6
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()
Exemple #7
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()
 def clean(self):
     """Aditionnal validations.
        - validate that self_registration is on
     """
     errors = []
     if not self_registration():
         errors.append(
             _(u'Self registration is turned off '
               'by the administrator on this portal.'))
     return errors
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')
 def __call__(self):
     c = self.request.context
     request = self.request
     params = {}
     params.update(get_base_params(self))
     projects = OrderedDict()
     projects['public'] = {
         'label':_('Public projects') ,
         'items':[c.find_context(project.Project.get_public_project())['item']]}
     def not_present(p):
         ids = []
         for k in projects:
             if p.id in [q.context.id for q in projects[k]['items']]:
                 return False
         return True
     # maybe we are admin and want to see projects from a particular user
     usr, id = None, -666
     anonym = not getattr(self.request, 'user', False)
     if not anonym:
         id = self.request.user.id
     is_project_manager = R['project_manager'] in self.effective_principals
     if 'id' in request.params and is_project_manager:
         try:
             id = int(request.params.get('id'))
             usr = user.User.by_id(id)
         except:
             pass
     if usr is None and not anonym:
         usr = user.User.by_id(self.request.user.id)
     if usr is not None:
         projects['own'] = {'label':_('My projects'), 'items': []}
         pr = project.Project.by_owner(usr)
         for p in pr:
             if not_present(p) and p is not None:
                 projects['own']['items'].append(c.find_context(p)['item'])
         projects['activity'] = {'label':_('Projects where i have activities'), 'items': []}
         pr = project.Project.by_participation(usr)
         for p in pr:
             if not_present(p) and p is not None:
                 projects['activity']['items'].append(c.find_context(p)['item'])
     params['projects_map'] = projects
     return render_to_response(self.template, params, self.request)
Exemple #11
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
 def __call__(self):
     form, request, context = None, self.request, self.request.context
     is_a_get = request.method == 'GET'
     is_a_post = request.method == 'POST'
     params = {'view': self}
     params.update(get_base_params(self))
     can_add = False
     can_add = has_permission(P['project_create'], self.request.root, self.request)
     is_project_manager = R['project_manager'] in self.effective_principals
     url = "%s@@ajax_users_list" % (self.request.resource_url(context))
     if is_project_manager:
         class UserSchema(colander.TupleSchema):
             id = colander.SchemaNode(colander.Int(), missing = '',)
             label = colander.SchemaNode(colander.String(), missing = '',)
         class UserWrap(colander.SequenceSchema):
             user = UserSchema(name="user", missing=tuple())
         class ProjectManagementSchema(colander.MappingSchema):
             userwrap = UserWrap(name="user", title=_("View projects of a member"),
                                 widget = widget.SingleChosenSelectWidget(url, width='400px'),
                                 default=[], validator = v.not_existing_user, missing=tuple(),)
         form = widget.Form(request,
                            ProjectManagementSchema(title=_("Project management")),
                            buttons=(_('Send'),), formid='view_member_projects')
         if is_a_get:
             params['form'] = form.render()
         if is_a_post:
             if is_project_manager:
                 try:
                     modified = False
                     controls = request.POST.items()
                     fdata  = form.validate(controls)
                     id = fdata['userwrap'][0][0]
                     url = "%s@@list?id=%s" % (
                         self.request.resource_url(self.request.context),
                         id
                     )
                     return HTTPFound(location=url)
                     params['form'] = form.render()
                 except deform.exception.ValidationFailure, e:
                     params['form'] = e.render()
 def items(self):
     default_p = Project.get_public_project()
     self._items = OrderedDict()
     for p in self.session.query(Project).all():
         if default_p == p:
             name = _("Public project")
             id = None
         else:
             name = p.name
             id = "%s" % p.id
         pr = ProjectResource(p, self, id=id, name=name)
         self._items[pr.__name__] = pr
     return self._items
Exemple #14
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()
 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()
 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)
 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()
Exemple #18
0
def forbidden(req):
    """ forbidden(request)
    No return value

    Called when user hits a resource that requires a permission and the
    user doesn't have the required permission. Will prompt for login.

    """
    flash(_('Access denied to this section'), 'error')
    came_from = req.resource_url(req.root)
    if req.user is None:
        came_from = req.url
    return HTTPFound(location='%s?came_from=%s' % (
            req.route_url('apex_login'), came_from
    ))
    def __init__(self, request):
        Base.__init__(self, request)

        class ProjectSchema(colander.MappingSchema):
            name = colander.SchemaNode(colander.String(),
                                       title=_('Name'),
                                       validator=v.not_empty_string)
            description = colander.SchemaNode(colander.String(),
                                              title=_('Backend description'),)
        self.sh_map = {'base': ProjectSchema}
        self.fmap = {'name': 'name', 'description': 'description'}

        def global_project_validator(form, value):
            pass
        self.sh = self.sh_map['base'](validator=global_project_validator)
        ctx = self.request.context
        if isinstance(ctx, project.ProjectResource):
            ab = ctx.project
            keys = {'name': 'name', 'description': 'description'}
            for k in keys:
                self.sh[keys[k]].default = getattr(ab, k)
        self.form = deform.Form(self.sh, buttons=(_('Send'),),
                                formid='add_project')
Exemple #20
0
 def construct(self):
    base_user = self.base_user
    if not len(self.projects):
         # we do not have yet an project even the default one, 
         # creating the user project
         will, tries, project = -1, 10 , None 
         message = ''
         while tries:
             tries -= 1
             will += 1
             try:
                 pname = 'Default project of %s' % base_user.username
                 if will:
                     pname = '%s (%s)' % (pname, will)
                 project = Project.create(pname, _('Default project created on sign in'), self)
                 break
             except Exception, e:
                 raise
                 message = '%s' % e
                 tries -= 1
         if message:
             error = 'Default project for %s cannot be created' % base_user.username
             if message: error += ' : %s' % message
             logging.getLogger('mobyle2.create_user').error(error)
def existing_validator(node, value, cls, label='item'):
    item, value = None, value.strip()
    try:
        item = session.query(cls).filter(cls.name == value).first()
    except Exception, e:
        raise Invalid(node, _('Unknown Error: %s' % e))
#!/usr/bin/env python
# -*- coding: utf-8 -*-
__docformat__ = 'restructuredtext en'

from colander import Invalid

from apex.models import AuthUser

from mobyle2.core.utils import _
from mobyle2.core.models.auth import Role
from mobyle2.core.models.user import User, Group
from mobyle2.core.models import DBSession as session

to_be_translated = [
    _('Those roleid do not exists: %s'),
    _('Those userid do not exists: %s'),
    _('This role already exists') ,
    _('This group already exists') , 
    _('Those groupid do not exists: %s'),
    _('This roleid does not exists: %s'),
    _('This userid does not exists: %s'),
    _('This groupid does not exists: %s'),
]
 
def not_empty_string(node, value):
    if not value.strip():
        raise Invalid(node, _('You must set a not null string'))

def existing_validator(node, value, cls, label='item'):
    item, value = None, value.strip()
    try:
def fail(node, value):
    raise Invalid(node, _('Fail'))
def not_empty_string(node, value):
    if not value.strip():
        raise Invalid(node, _('You must set a not null string'))
Exemple #25
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()
ANONYMOUS_ROLE = "mobyle2 > anonyme"

R = {
    "anonyme": ANONYMOUS_ROLE,
    "internal_user": "******",
    "external_user": "******",
    "project_owner": "mobyle2 > project_owner",
    "project_watcher": "mobyle2 > project_watcher",
    "project_contributor": "mobyle2 > project_contributor",
    "project_manager": "mobyle2 > project_manager",
    "portal_administrator": "mobyle2 > portal_administrator",
}


default_roles = {
    ANONYMOUS_ROLE: _("Anonym"),
    R["internal_user"]: _("Internal user"),
    R["external_user"]: _("External user"),
    R["project_owner"]: _("Project owner"),
    R["project_watcher"]: _("Project watcher"),
    R["project_contributor"]: _("Project contributor"),
    R["project_manager"]: _("Project manager"),
    R["portal_administrator"]: _("Portal administrator"),
}
# shortcuts
P = {
    "global_authadmin": "mobyle2 > global_authadmin",
    "servers_management": "mobyle2 > servers_management",
    "services_management": "mobyle2 > services_management",
    "global_useradmin": "mobyle2 > global_useradmin",
    "global_admin": "mobyle2 > global_admin",
Exemple #27
0
    def __init__(self, request):
        Base.__init__(self, request)
        at = auth.AUTH_BACKENDS.copy()
        existing_types = [a[0]
                          for a in session.query(
                              auth.AuthenticationBackend.backend_type
                          ).filter(
                              auth.AuthenticationBackend.enabled == True
                          ).group_by(
                              auth.AuthenticationBackend.backend_type).all()
                         ]
        for item in copy.deepcopy(at):
            if (item in existing_types) and (item in auth.ONLY_ONE_OF):
                del at[item]
        atv = [('', '')] + at.items()

        class AuthentSchema(colander.MappingSchema):
            name = colander.SchemaNode(colander.String(),
                                       title=_('Name'),
                                       validator=v.not_empty_string)
            description = colander.SchemaNode(colander.String(),
                                              title=_('Backend description'),)
            enabled = colander.SchemaNode(colander.Boolean(),
                                          default=True,
                                          title=_('Enabled'),
                                          description=_('Is this backend enabled ?'))
            auth_backend = colander.SchemaNode(colander.String(),
                                               widget=deform.widget.SelectWidget(
                                                   **{'values': atv}
                                               ),
                                               validator=colander.OneOf(at.keys()),
                                               title=_('Authentication backend')
                                              )

        class DBSchema(colander.MappingSchema):
            host = colander.SchemaNode(colander.String(), description=_('Host'))
            port = colander.SchemaNode(colander.String(), description=_('Port'))
            password = colander.SchemaNode(colander.String(), description=_('Password'))
            user = colander.SchemaNode(colander.String(), description=_('User'))
            db = colander.SchemaNode(colander.String(), description=_('Database'))

        class LDAPSchema(colander.MappingSchema):
            host = colander.SchemaNode(colander.String(), description=_('Host'))
            port = colander.SchemaNode(colander.String(), description=_('Port'))
            use_ssl = colander.SchemaNode(colander.Boolean(),
                                          description=_('Use SSL?'))
            #password = colander.SchemaNode(colander.String(), description=_('Password'))
            dn = colander.SchemaNode(colander.String(),
                                     description=_('Base dn mask to connect as in the '
                                                   'form "cn=USERID,ou=people", '
                                                   'ex: "cn=USERID,o=paster,dc=paris,dc=net. '
                                                   'USERID is the placeholder for the login '
                                                   'string the user will input.'))
            # users = colander.SchemaNode(colander.String(), description=_('LDAP filter to grab users'))
            # groups = colander.SchemaNode(colander.String(), description=_('LDAP filter to grab groups'))

        class SimpleOpenidSchema(colander.MappingSchema):
            key = colander.SchemaNode(colander.String(), description=_('API consumer'))
            secret = colander.SchemaNode(colander.String(), description=_('API consumer secret'))

        class OpenidSchema(colander.MappingSchema):
            realm = colander.SchemaNode(colander.String(), description=_('Openid Realm'), missing=None)

        class SimpleOauthSchema(SimpleOpenidSchema):
            authorize = colander.SchemaNode(colander.String(), description=_('API Scope'), missing=None)

        class FullOauthSchema(SimpleOauthSchema):
            realm = colander.SchemaNode(colander.String(), description=_('Service Realm'), validator=v.not_empty_string, missing=None)

        class FileSchema(colander.MappingSchema):
            passwd_file = colander.SchemaNode(colander.String(), description=_('Full path to the file'))

        self.sh_map = {
            'base': AuthentSchema,
            'db': DBSchema,
            'facebook': SimpleOauthSchema,
            'file': FileSchema,
            'github': SimpleOauthSchema,
            'google': SimpleOauthSchema,
            'ldap': LDAPSchema,
            'live': SimpleOauthSchema,
            'openid': OpenidSchema,
            'twitter':  SimpleOauthSchema,
            'yahoo': SimpleOpenidSchema,
        }
        self.fmap = {
            'auth_backend': 'backend_type',
            'enabled': 'enabled',
            'name': 'name',
            'description': 'description',
            'authorize': 'authorize',
            'key': 'username',
            'secret': 'password',
            'url': 'realm',
            'realm': 'realm',
            'db': 'database',
            'host': 'hostname',
            'port': 'port',
            'user': '******',
            'dn': 'ldap_dn',
            'file': 'file',
            'use_ssl': 'use_ssl',
            'users': 'ldap_users_filter',
            'groups': 'ldap_groups_filter',
        }
        request = self.request

        def global_auth_backend_validator(form, value):
            pass
            #if not value['title'].startswith(value['name']):
            #    exc = colander.Invalid(form, 'Title must start with name')
            #    exc['title'] = 'Must start with name %s' % value['name']
            #    raise exc

        def auth_schema_afterbind(node, kw):
            if kw.get('remove_ab'):
                del node['auth_backend']
        self.sh = self.sh_map['base'](
            validator=global_auth_backend_validator,
            after_bind=auth_schema_afterbind)
        ctx = self.request.context
        # if we are in the context of an auth backend, we cant change the type
        if isinstance(ctx, auth.AuthenticationBackendResource):
            self.sh = self.sh.bind(remove_ab=True)
        self.for_ajax_form = False
        # maybe we are in an ajax request to solve remaining fields for a particular authtype.
        at = ''
        details_added = False
        if request.method == 'POST':
            at = request.POST.get('load_auth_backend_details')
            if at in auth.AUTH_BACKENDS:
                self.sh['auth_backend'].default = at
                self.for_ajax_form = True
            if not at:
                at = request.POST.get('auth_backend')
            if at in auth.AUTH_BACKENDS:
                details_added = True
                ash = self.sh_map[at](name="auth_backend_infos", title=_('Authentication backend details'))
                self.sh.add(ash)
        # if we are in the context of an auth backend, filling edit properties
        if isinstance(ctx, auth.AuthenticationBackendResource):
            ab = ctx.ab
            if not details_added:
                ash = self.sh_map[ab.backend_type](name="auth_backend_infos", title=_('Authentication backend details'))
                self.sh.add(ash)
            keys = {'name': 'name', 'description': 'description', 'backend_type': 'auth_backend', 'enabled': 'enabled'}
            dkeys = {}
            if (ab.backend_type == at and at != '') or (at == ''):
                if ab.backend_type in ['facebook', 'live', 'yahoo', 'twitter', 'openid', 'google', 'github']:
                    dkeys.update({'username': '******', 'password': '******', 'authorize': 'authorize'})
                if ab.backend_type in ['file']:
                    dkeys.update({'file': 'file'})
                if ab.backend_type in ['openid']:
                    dkeys.update({'realm': 'realm'})
                if ab.backend_type in ['ldap']:
                    dkeys.update({'ldap_groups_filter': 'groups', 'ldap_users_filter': 'users',
                                  'ldap_dn': 'dn', 'hostname': 'host', 'port': 'port',
                                  #,'password':'******'
                                   'use_ssl': 'use_ssl'})
                if ab.backend_type in ['db']:
                    dkeys.update({'hostname': 'host', 'database': 'db', 'password': '******', 'port': 'port',
                                  'username': '******', 'password': '******'})
            for k in keys:
                if k in self.sh:
                    self.sh[keys[k]].default = getattr(ab, k)
            for k in dkeys:
                value = getattr(ab, k)
                if value:
                    self.sh['auth_backend_infos'][dkeys[k]].default = value
        self.form = w.Form(request, self.sh, buttons=(_('Send'),), formid = 'add_auth_backend')
Exemple #28
0
 def translate(self, string):
     localizer = get_localizer(self)
     return localizer.translate(_(string)) 
Exemple #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()
edit_service = "mobyle2 > edit_service"
del_service = "mobyle2 > del_service"

notebook_view = "mobyle2 > notebook_view"
notebook_add = "mobyle2 > notebook_add"
notebook_edit = "mobyle2 > notebook_edit"
notebook_del = "mobyle2 > notebook_del"

job_view = "mobyle2 > job_view"
job_run = "mobyle2 > job_run"
job_add = "mobyle2 > job_add"
job_edit = "mobyle2 > job_edit"
job_del = "mobyle2 > job_del"

global_permissions = {
    manage_portal: _("Manage portal"),
    user_add: _("Add an user"),
    user_edit: _("Edit an user"),
    user_del: _("Delete an user"),
    group_add: _("Add a group"),
    group_edit: _("Edit a group"),
    group_del: _("Delete a group"),
    manage_groups: _("Manage groups"),
    manage_roles: _("Manage roles"),
    manage_project_groups: _("Manage group project access"),
    manage_project_roles: _("Manage project roles"),
    root_project_edit: _("Edit the root project"),
    root_project_add: _("Add the root project"),
    root_project_view: _("View the root project"),
    root_project_del: _("Delete the root project"),
    services_view: _("View services"),