Python pyramid.security.Allow() Examples

The following are 25 code examples of pyramid.security.Allow(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module pyramid.security , or try the search function .
Example #1
Source File: polymorphic.py    From nefertari with Apache License 2.0 6 votes vote down vote up
def _get_least_permissions_aces(self, resources):
        """ Get ACEs with the least permissions that fit all resources.

        To have access to polymorph on N collections, user MUST have
        access to all of them. If this is true, ACEs are returned, that
        allows 'view' permissions to current request principals.

        Otherwise None is returned thus blocking all permissions except
        those defined in `nefertari.acl.BaseACL`.

        :param resources:
        :type resources: list of Resource instances
        :return: Generated Pyramid ACEs or None
        :rtype: tuple or None
        """
        factories = [res.view._factory for res in resources]
        contexts = [factory(self.request) for factory in factories]
        for ctx in contexts:
            if not self.request.has_permission('view', ctx):
                return
        else:
            return [
                (Allow, principal, 'view')
                for principal in self.request.effective_principals
            ] 
Example #2
Source File: security.py    From pyvac with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_acl(self, request):
        """
        Get ACL.
        Initialize the __acl__ from the sql database once,
        then use the cached version.

        :param request: pyramid request
        :type login: :class:`pyramid.request.Request`

        :return: ACLs in pyramid format. (Allow, group name, permission name)
        :rtype: list of tupple
        """
        if RootFactory._acl is None:
            acl = []
            session = DBSession()
            groups = Group.all(session)
            for g in groups:
                acl.extend([(Allow, g.name, p.name) for p in g.permissions])
            RootFactory._acl = acl

        return RootFactory._acl 
Example #3
Source File: auth.py    From ramses with Apache License 2.0 6 votes vote down vote up
def create_system_user(config):
    log.info('Creating system user')
    crypt = cryptacular.bcrypt.BCRYPTPasswordManager()
    settings = config.registry.settings
    try:
        auth_model = config.registry.auth_model
        s_user = settings['system.user']
        s_pass = str(crypt.encode(settings['system.password']))
        s_email = settings['system.email']
        defaults = dict(
            password=s_pass,
            email=s_email,
            groups=['admin'],
        )
        if config.registry.database_acls:
            defaults['_acl'] = [(Allow, 'g:admin', ALL_PERMISSIONS)]

        user, created = auth_model.get_or_create(
            username=s_user, defaults=defaults)
        if created:
            transaction.commit()
    except KeyError as e:
        log.error('Failed to create system user. Missing config: %s' % e) 
Example #4
Source File: wsgi_security.py    From channelstream with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, request):
        self.__acl__ = []
        config = request.registry.settings
        req_url_secret = request.params.get("secret")
        req_secret = request.headers.get("x-channelstream-secret", req_url_secret)

        addr = request.environ["REMOTE_ADDR"]
        if not is_allowed_ip(addr, config):
            log.warning("IP: {} is not whitelisted".format(addr))
            return

        if req_secret:
            max_age = 60 if config["validate_requests"] else None
            request.registry.signature_checker.unsign(req_secret, max_age=max_age)
        else:
            return
        self.__acl__ = [(Allow, Everyone, ALL_PERMISSIONS)] 
Example #5
Source File: test_auth.py    From ramses with Apache License 2.0 6 votes vote down vote up
def test_create_system_user_created(self, mock_crypt, mock_trans):
        from ramses import auth
        encoder = mock_crypt.bcrypt.BCRYPTPasswordManager()
        encoder.encode.return_value = '654321'
        config = Mock()
        config.registry.settings = {
            'system.user': 'user12',
            'system.password': '123456',
            'system.email': 'user12@example.com',
        }
        config.registry.auth_model.get_or_create.return_value = (
            Mock(), True)
        auth.create_system_user(config)
        mock_trans.commit.assert_called_once_with()
        encoder.encode.assert_called_once_with('123456')
        config.registry.auth_model.get_or_create.assert_called_once_with(
            username='user12',
            defaults={
                'password': '654321',
                'email': 'user12@example.com',
                'groups': ['admin'],
                '_acl': [(Allow, 'g:admin', ALL_PERMISSIONS)],
            }
        ) 
Example #6
Source File: test_auth.py    From ramses with Apache License 2.0 6 votes vote down vote up
def test_create_system_user_exists(self, mock_crypt, mock_trans):
        from ramses import auth
        encoder = mock_crypt.bcrypt.BCRYPTPasswordManager()
        encoder.encode.return_value = '654321'
        config = Mock()
        config.registry.settings = {
            'system.user': 'user12',
            'system.password': '123456',
            'system.email': 'user12@example.com',
        }
        config.registry.auth_model.get_or_create.return_value = (1, False)
        auth.create_system_user(config)
        assert not mock_trans.commit.called
        encoder.encode.assert_called_once_with('123456')
        config.registry.auth_model.get_or_create.assert_called_once_with(
            username='user12',
            defaults={
                'password': '654321',
                'email': 'user12@example.com',
                'groups': ['admin'],
                '_acl': [(Allow, 'g:admin', ALL_PERMISSIONS)],
            }
        ) 
Example #7
Source File: context.py    From muesli with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, request):
        exercise_id = request.matchdict['exercise_id']
        self.exercise = request.db.query(Exercise).get(exercise_id)
        if self.exercise is None:
            raise HTTPNotFound(detail='Exercise not found')
        self.exam = self.exercise.exam
        if 'tutorial_ids' in request.matchdict:
            self.tutorial_ids = request.matchdict['tutorial_ids'].split(',')
            if len(self.tutorial_ids)==1 and self.tutorial_ids[0]=='':
                self.tutorial_ids = []
                self.tutorials = []
            else:
                self.tutorials = request.db.query(Tutorial).filter(Tutorial.id.in_(self.tutorial_ids)).all()
        self.__acl__ = [
                (Allow, Authenticated, 'view_points'),
                (Allow, 'group:administrators', ALL_PERMISSIONS),
                ]+[(Allow, 'user:{0}'.format(tutor.id), ('statistics')) for tutor in self.exam.lecture.tutors
                ]+[(Allow, 'user:{0}'.format(assistant.id), ('statistics')) for assistant in self.exam.lecture.assistants
                ] 
Example #8
Source File: main.py    From pyramid_sacrud with MIT License 5 votes vote down vote up
def __init__(self, request):
        self.__acl__ = [
            (Allow, Everyone, PYRAMID_SACRUD_HOME),
        ] 
Example #9
Source File: __init__.py    From learning-python with MIT License 5 votes vote down vote up
def __init__(self, request):
        groups = DBSession.query(Group).all()
        self.__acl__ = []
        for group in groups:
            for permission in group.permissions:
                self.__acl__.append(
                    (Allow, 'g:' + str(group.id), permission.name)
                ) 
Example #10
Source File: context.py    From muesli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request):
        exercise_id = request.matchdict['exercise_id']
        exercise_id = exercise_id.strip("/")
        user_id = request.matchdict.get('user_id', None)
        self.exercise = request.db.query(Exercise).get(exercise_id)
        if self.exercise is None:
            raise HTTPBadRequest("Die Angeforderte Übung existiert nicht!")
        self.lecture = self.exercise.exam.lecture
        student = None
        self.user = None
        if user_id is not None:
            user_id = user_id.strip("/")
            self.user = request.db.query(User).get(user_id)
            try:
                student = request.db.query(LectureStudent).filter(and_(LectureStudent.student_id == self.user.id, LectureStudent.lecture == self.lecture)).one()
            except SQLAlchemyError:
                student = None
        self.__acl__ = [(Allow, 'group:administrators', ALL_PERMISSIONS)]
        self.__acl__ += [(Allow, 'user:{0}'.format(request.user.id), ('view', 'viewAll', 'viewOwn'))] if request.user in self.lecture.assistants else []
        if request.user == self.user and request.user is not None:
            self.__acl__ += [(Allow, 'user:{0}'.format(request.user.id), ('view', 'viewOwn'))]
        if self.lecture.tutor_rights == editAllTutorials:
            self.__acl__ += [(Allow, 'user:{0}'.format(request.user.id), ('view', 'viewAll', 'viewOwn'))] if request.user == self.lecture.tutors else []
        else:
            self.__acl__ += [(Allow, 'user:{0}'.format(request.user.id), ('view'))] if request.user in self.lecture.tutors else []
        if student is not None:
            tutorial = student.tutorial
            self.__acl__ += [(Allow, 'user:{0}'.format(request.user.id), ('viewOwn'))] if request.user == tutorial.tutor else [] 
Example #11
Source File: context.py    From muesli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request):
        exam_id = request.matchdict['exam_id']
        self.exam = request.db.query(Exam).get(exam_id)
        if self.exam is None:
            raise HTTPNotFound(detail='Exam not found')
        lecture = self.exam.lecture
        lecture_students = lecture.students
        self.__acl__ = [(Allow, 'group:administrators', ALL_PERMISSIONS)]
        if request.user in lecture_students:
            self.__acl__ += [(Allow, 'user:{0}'.format(request.user.id), ('view'))]
        self.__acl__ += [(Allow, 'user:{0}'.format(request.user.id), ('view', 'edit'))] if request.user in lecture.assistants else []
        self.__acl__ += [(Allow, 'user:{0}'.format(request.user.id), ('view'))] if request.user in lecture.tutors else [] 
Example #12
Source File: context.py    From muesli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request):
        tutorial_id = request.matchdict.get('tutorial_id', None)
        self.__acl__ = [(Allow, Authenticated, ('viewOverview')),
                        (Allow, 'group:administrators', ALL_PERMISSIONS)]
        if tutorial_id is not None:
            tutorial = request.db.query(Tutorial).get(tutorial_id)
            if tutorial is not None:
                lecture = tutorial.lecture
                self.__acl__ += [(Allow, 'user:{0}'.format(request.user.id), ('viewAll', 'edit'))] if request.user in lecture.assistants else []
                if lecture.tutor_rights == editOwnTutorials:
                    self.__acl__ += [(Allow, 'user:{0}'.format(request.user.id), ('viewAll'))] if request.user == tutorial.tutor else []
                elif lecture.tutor_rights == editAllTutorials:
                    self.__acl__ += [(Allow, 'user:{0}'.format(request.user.id), ('viewAll'))] if request.user in lecture.tutors else [] 
Example #13
Source File: context.py    From muesli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request):
        source1 = request.GET['source1']
        source2 = request.GET['source2']
        ids1 = self.get_allowed_ids(source1, request)
        ids2 = self.get_allowed_ids(source2, request)
        ids = set(ids1).intersection(set(ids2))
        self.__acl__ = [
                (Allow, 'group:administrators', ALL_PERMISSIONS)
                ] + [(Allow, 'user:{0}'.format(id), ('correlation')) for id in ids] 
Example #14
Source File: context.py    From muesli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request):
        exam_id = request.matchdict['exam_id']
        self.exam = request.db.query(Exam).get(exam_id)
        if self.exam is None:
            raise HTTPNotFound(detail='Exam not found')
        self.tutorial_ids_str = request.matchdict.get('tutorial_ids', '')
        self.tutorials, self.tutorial_ids =  getTutorials(request)
        self.__acl__ = [
                #(Allow, Authenticated, 'view_own_points'),
                (Allow, 'group:administrators', ALL_PERMISSIONS),
                ]+[(Allow, 'user:{0}'.format(tutor.id), ('statistics')) for tutor in self.exam.lecture.tutors
                ]+[(Allow, 'user:{0}'.format(assistant.id), ('edit', 'view_points', 'enter_points', 'statistics')) for assistant in self.exam.lecture.assistants
                ]
        if self.exam.lecture.tutor_rights == editAllTutorials:
            self.__acl__ += [(Allow, 'user:{0}'.format(tutor.id), ('enter_points', 'view_points')) for tutor in self.exam.lecture.tutors]
        else:
            if self.tutorials:
                if self.exam.lecture.tutor_rights == editOwnTutorials:
                    self.__acl__ += [(Allow, 'user:{0}'.format(tutor.id), ('view_points', 'enter_points')) for tutor in getTutorForTutorials(self.tutorials)]
                elif self.exam.lecture.tutor_rights == editNoTutorials:
                    self.__acl__ += [(Allow, 'user:{0}'.format(tutor.id), ('view_points')) for tutor in getTutorForTutorials(self.tutorials)]
                elif self.exam.lecture.tutor_rights == editAllTutorials:
                    self.__acl__ += [(Allow, 'user:{0}'.format(tutor.id), ('view_points', 'enter_points')) for tutor in self.exam.lecture.tutors]
                else: raise ValueError('Tutorrights %s not known' % self.exam.lecture.tutor_rights)

        # add exam specific links
        if self.exam.lecture is None:
            return

        if request.has_permission('edit', self):
            lecture_root = NavigationTree(self.exam.lecture.name,
                    request.route_url('lecture_edit', lecture_id=self.exam.lecture.id))
        else:
            lecture_root = NavigationTree(self.exam.lecture.name,
                    request.route_url('lecture_view', lecture_id=self.exam.lecture.id))
        nodes = get_lecture_specific_nodes(request, self, self.exam.lecture.id)
        for node in nodes:
            lecture_root.append(node)

        request.navigationTree.prepend(lecture_root) 
Example #15
Source File: context.py    From muesli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request):
        student_id = request.POST['student']
        tutorial_id = request.POST['new_tutorial']
        self.student = request.db.query(User).get(student_id)
        self.tutorial = request.db.query(Tutorial).get(tutorial_id)
        if self.student is None:
            raise HTTPNotFound(detail='Student not found')
        if self.tutorial is None:
            raise HTTPNotFound(detail='tutorial not found')
        self.__acl__ = [
                (Allow, 'group:administrators', ALL_PERMISSIONS),
                ]+[
                        (Allow, 'user:{0}'.format(assistant.id), ('move')) for assistant in self.tutorial.lecture.assistants
                ] 
Example #16
Source File: context.py    From muesli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request):
        grading_id = request.matchdict['grading_id']
        self.grading = request.db.query(Grading).get(grading_id)
        if self.grading is None:
            raise HTTPNotFound(detail='Grading not found')
        self.__acl__ = [
                (Allow, 'group:administrators', ALL_PERMISSIONS),
                ]+[(Allow, 'user:{0}'.format(assistant.id), ('view', 'edit')) for assistant in self.grading.lecture.assistants] 
Example #17
Source File: context.py    From muesli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request):
        self.__acl__ = [
                (Allow, Authenticated, ('update', 'change_email', 'change_password','view_keys','remove_keys')),
                (Allow, 'group:administrators', ALL_PERMISSIONS),
                ]+[(Allow, 'user:{0}'.format(a.id), 'create_lecture') for a in request.db.query(User).filter(User.is_assistant==1).all()] 
Example #18
Source File: context.py    From muesli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request):
        self.__acl__ = [
            (Allow, Everyone, ('view')),
            (Allow, 'group:administrators', ALL_PERMISSIONS)
        ] 
Example #19
Source File: context.py    From muesli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request):
        confirmation_hash = request.matchdict['confirmation']
        self.confirmation = request.db.query(Confirmation).get(confirmation_hash)
        if self.confirmation is None:
            raise HTTPNotFound(detail='Confirmation not found')
        self.__acl__ = [
                (Allow, 'group:administrators', ALL_PERMISSIONS),
                ] 
Example #20
Source File: context.py    From muesli with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, request):
        user_id = request.matchdict['user_id']
        self.user = request.db.query(User).get(user_id)
        if self.user is None:
            raise HTTPNotFound(detail='User not found')
        self.__acl__ = [
                (Allow, 'user:{0}'.format(user_id), ('view')),
                (Allow, 'group:administrators', ALL_PERMISSIONS),
                ] 
Example #21
Source File: wsgi_security.py    From channelstream with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def __init__(self, request):
        self.__acl__ = []
        user = request.authenticated_userid
        if user:
            self.__acl__ = [(Allow, Everyone, ALL_PERMISSIONS)]
        else:
            # try the API auth factory too for server requests
            context_obj = APIFactory(request)
            self.__acl__ = context_obj.__acl__ 
Example #22
Source File: test_polymorphic.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def test_set_collections_acl_has_aces(self, mock_coll, mock_res,
                                          mock_aces):
        from pyramid.security import Allow, DENY_ALL
        aces = [(Allow, 'foobar', 'dostuff')]
        mock_aces.return_value = aces
        acl = polymorphic.PolymorphicACL(None)
        assert len(acl.__acl__) == 3
        assert DENY_ALL == acl.__acl__[-1]
        assert aces[0] in acl.__acl__
        assert mock_coll.call_count == 1
        assert mock_res.call_count == 1
        assert mock_aces.call_count == 1 
Example #23
Source File: test_polymorphic.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def test_get_least_permissions_aces_allowed(self, mock_meth):
        from pyramid.security import Allow
        request = Mock()
        request.has_permission.return_value = True
        request.effective_principals = ['user', 'admin']
        acl = polymorphic.PolymorphicACL(request)
        resource = Mock()
        resource.view._factory = Mock()
        aces = acl._get_least_permissions_aces([resource])
        resource.view._factory.assert_called_once_with(request)
        request.has_permission.assert_called_once_with(
            'view', resource.view._factory())
        assert len(aces) == 2
        assert (Allow, 'user', 'view') in aces
        assert (Allow, 'admin', 'view') in aces 
Example #24
Source File: polymorphic.py    From nefertari with Apache License 2.0 5 votes vote down vote up
def set_collections_acl(self):
        """ Calculate and set ACL valid for requested collections.

        DENY_ALL is added to ACL to make sure no access rules are
        inherited.
        """
        acl = [(Allow, 'g:admin', ALL_PERMISSIONS)]
        collections = self.get_collections()
        resources = self.get_resources(collections)
        aces = self._get_least_permissions_aces(resources)
        if aces is not None:
            for ace in aces:
                acl.append(ace)
        acl.append(DENY_ALL)
        self.__acl__ = tuple(acl) 
Example #25
Source File: context.py    From muesli with GNU General Public License v3.0 4 votes vote down vote up
def __init__(self, request):
        self.tutorial_ids_str = request.matchdict.get('tutorial_ids', request.matchdict.get('tutorial_id', ''))
        self.tutorials, self.tutorial_ids = getTutorials(request)
        if self.tutorials:
            self.lecture = self.tutorials[0].lecture
        else:
            lecture_id = request.matchdict.get('lecture_id', None)
            if lecture_id:
                self.lecture = request.db.query(Lecture).get(lecture_id)
            else:
                self.lecture = None
        self.__acl__ = [
                (Allow, 'group:administrators', ALL_PERMISSIONS),
                ]
        if self.lecture:
            self.__acl__ += [(Allow, 'user:{0}'.format(tutor.id), ('viewOverview', 'take_tutorial', 'mail_tutors')) for tutor in self.lecture.tutors]
            self.__acl__ += [((Allow, 'user:{0}'.format(assistant.id), ('viewOverview', 'viewAll', 'sendMail', 'edit', 'remove_student'))) for assistant in self.lecture.assistants]
        if self.tutorials:
            if self.lecture.tutor_rights == editOwnTutorials:
                self.__acl__ += [(Allow, 'user:{0}'.format(tutor.id), ('viewAll', 'remove_student')) for tutor in getTutorForTutorials(self.tutorials)]
            elif self.lecture.tutor_rights == editNoTutorials:
                #TODO: This has to be a bug?!
                self.__acl__ += [(Allow, 'user:{0}'.format(tutor.id), ('viewAll', 'remove_student')) for tutor in getTutorForTutorials(self.tutorials)]
            elif self.lecture.tutor_rights == editAllTutorials:
                self.__acl__ += [(Allow, 'user:{0}'.format(tutor.id), ('viewAll', 'remove_student')) for tutor in self.lecture.tutors]
            else: raise ValueError('Tutorrights %s not known' % self.lecture.tutor_rights)
            for tutor in getTutorForTutorials(self.tutorials):
                self.__acl__.append((Allow, 'user:{0}'.format(tutor.id), ('sendMail')))
            if self.tutorials[0].lecture.mode == 'direct':
                self.__acl__.append((Allow, Authenticated, ('subscribe')))
            if self.tutorials[0].lecture.mode in ['direct', 'off']:
                self.__acl__.append((Allow, Authenticated, ('unsubscribe')))

        # add tutorial specific links
        if self.lecture is None:
            return

        if request.has_permission('edit', self):
            lecture_root = NavigationTree('Vorlesung: {}'.format(self.lecture.name),
                    request.route_url('lecture_edit', lecture_id=self.lecture.id))
        else:
            lecture_root = NavigationTree('Vorlesung: {}'.format(self.lecture.name),
                    request.route_url('lecture_view', lecture_id=self.lecture.id))
        nodes = get_lecture_specific_nodes(request, self, self.lecture.id)
        for node in nodes:
            lecture_root.append(node)

        for tutorial in self.tutorials:
            tutorial_root = NavigationTree("{} ({})".format(tutorial.lecture.name, tutorial.time.__html__()),
                                           request.route_url('tutorial_view', tutorial_ids=tutorial.id))
            nodes = get_tutorial_specific_nodes(request, self, tutorial.id,
                    self.lecture.id)
            for node in nodes:
                tutorial_root.append(node)
            if tutorial_root.children:
                request.navigationTree.prepend(tutorial_root)

        if lecture_root.children:
            request.navigationTree.prepend(lecture_root)