Exemplo n.º 1
0
    def initialize(self):
        self.storeTokenContext()
        form = get_oauth_authorization(self.request)
        key = form.get('oauth_token')
        if key:
            self.token = getUtility(IOAuthRequestTokenSet).getByKey(key)

        callback = self.request.form.get('oauth_callback')
        if (self.token is not None
            and self.token.consumer.is_integrated_desktop):
            # Nip problems in the bud by appling special rules about
            # what desktop integrations are allowed to do.
            if callback is not None:
                # A desktop integration is not allowed to specify a callback.
                raise Unauthorized(
                    "A desktop integration may not specify an "
                    "OAuth callback URL.")
            # A desktop integration token can only have one of two
            # permission levels: "Desktop Integration" and
            # "Unauthorized". It shouldn't even be able to ask for any
            # other level.
            for action in self.visible_actions:
                if action.permission not in (
                    OAuthPermission.DESKTOP_INTEGRATION,
                    OAuthPermission.UNAUTHORIZED):
                    raise Unauthorized(
                        ("Desktop integration token requested a permission "
                         '("%s") not supported for desktop-wide use.')
                         % action.label)

        super(OAuthAuthorizeTokenView, self).initialize()
Exemplo n.º 2
0
    def __call__(self):
        app = ISchoolToolApplication(None)
        person = IPerson(self.request.principal, None)
        if not person:
            raise Unauthorized("Only logged in users can book resources.")
        cal = ISchoolToolCalendar(person)
        if self.request.has_key('event_id'):
            event = cal.find(self.request['event_id'])
        else:
            start_date = self.request.get('start_date')
            start_time = self.request.get('start_time')
            title = self.request.get('title')
            start_datetime = "%s %s" % (start_date, start_time)
            start_datetime = datetime(*strptime(start_datetime,
                                                "%Y-%m-%d %H:%M")[0:6])
            start_datetime = self.timezone.localize(start_datetime)
            start_datetime = start_datetime.astimezone(pytz.UTC)
            duration = timedelta(seconds=int(self.request.get('duration')))
            event = CalendarEvent(dtstart = start_datetime,
                                  duration = duration,
                                  title = title)
            cal.addEvent(event)

        if event:
            resource = app["resources"].get(self.request['resource_id'])
            if resource is not None:
                resource_calendar = ISchoolToolCalendar(resource)
                if not canAccess(resource_calendar, "addEvent"):
                    raise Unauthorized("You don't have the right to"
                                       " book this resource!")
                event.bookResource(resource)
        self.request.response.redirect(self.nextURL(event))
Exemplo n.º 3
0
    def _auth_with_ticket(self):
        """
        with flashupload authentication is done using a ticket
        """

        context = aq_inner(self.context)
        request = self.request
        url = context.absolute_url()

        ticket = getDataFromAllRequests(request, 'ticket')
        if ticket is None:
            raise Unauthorized('No ticket specified')

        logger.info('Authenticate using ticket, the ticket is "%s"' %
                    str(ticket))
        username = ticketmod.ticketOwner(url, ticket)
        if username is None:
            logger.info('Ticket "%s" was invalidated, cannot be used '
                        'any more.' % str(ticket))
            raise Unauthorized('Ticket is not valid')

        self.old_sm = SecurityManagement.getSecurityManager()
        user = find_user(context, username)
        SecurityManagement.newSecurityManager(self.request, user)
        logger.info('Switched to user "%s"' % username)
Exemplo n.º 4
0
    def check_setattr(self, obj, name):
        # Lookup or cached permission lookup
        portal_type = getattr(obj, 'portal_type', None)
        permission = self.setters.get((portal_type, name), _marker)

        # Lookup for the permission
        if permission is _marker:
            if name in _available_by_default:
                return
            permission = DEFAULT_WRITE_PERMISSION

        adapted = IResource(obj, None)

        if adapted is not None:
            for schema in iter_schemata(adapted):
                mapping = merged_tagged_value_dict(schema, write_permission.key)
                if name in mapping:
                    permission = mapping.get(name)
                    break
            self.setters[(portal_type, name)] = permission

        if IInteraction(self.request).checkPermission(permission, obj):
            return  # has permission

        __traceback_supplement__ = (TracebackSupplement, obj)
        raise Unauthorized(obj, name, permission)
Exemplo n.º 5
0
def model_to_dict(obj, use_titles=False, use_fields=False):
    data = OrderedDict()
    got_unauthorized = False

    error_attributes = []
    for key, field, schema in get_schema_fields(obj):
        if use_fields:
            key = field
        elif not use_titles:
            key = key.encode('utf8')
        else:
            key = field.title

        try:
            schema_d = schema(obj)
            data[key] = field.get(schema_d)
        except Unauthorized:
            # skip field
            got_unauthorized = True
            error_attributes.append(key)
            log.warning('Object %s (attribute %s of %s): access unauthorized!', obj, key, schema(obj),
                        exc_info=sys.exc_info())
            continue

    data['mtime'] = obj.mtime
    data['ctime'] = obj.ctime

    if got_unauthorized and not data:
        raise Unauthorized((obj, error_attributes, 'read'))
    return data
Exemplo n.º 6
0
 def authenticate(self, request):
     """See IAuthentication."""
     # To avoid confusion (hopefully), basic auth trumps cookie auth
     # totally, and all the time.  If there is any basic auth at all,
     # then cookie auth won't even be considered.
     # XXX daniels 2004-12-14: allow authentication scheme to be put into
     #     a view; for now, use basic auth by specifying ILoginPassword.
     try:
         credentials = ILoginPassword(request, None)
     except binascii.Error:
         # We have probably been sent Basic auth credentials that aren't
         # encoded properly. That's a client error, so we don't really
         # care, and we're done.
         raise Unauthorized("Bad Basic authentication.")
     if (config.launchpad.basic_auth_password and credentials is not None
             and credentials.getLogin() is not None):
         return self._authenticateUsingBasicAuth(credentials, request)
     else:
         # Hack to make us not even think of using a session if there
         # isn't already a cookie in the request, or one waiting to be
         # set in the response.
         cookie_name = config.launchpad_session.cookie
         if (request.cookies.get(cookie_name) is not None
                 or request.response.getCookie(cookie_name) is not None):
             return self._authenticateUsingCookieAuth(request)
         else:
             return None
Exemplo n.º 7
0
 def destroySelf(self):
     if not self.userCanDelete():
         raise Unauthorized(
             'Only the person who created the packaging and package '
             'maintainers can delete it.')
     notify(ObjectDeletedEvent(self))
     super(Packaging, self).destroySelf()
Exemplo n.º 8
0
    def traverse(self, name):
        """Traverse the paths of a feed.

        If a query string is provided it is normalized.  'bugs' paths and
        persons ('~') are special cased.
        """
        # Normalize the query string so caching is more effective.  This is
        # done by simply sorting the entries.

        # XXX bac 20071019, we would like to normalize with respect to case
        # too but cannot due to a problem with the bug search requiring status
        # values to be of a particular case.  See bug 154562.
        query_string = self.request.get('QUERY_STRING', '')
        fields = sorted(query_string.split('&'))
        normalized_query_string = '&'.join(fields)
        if query_string != normalized_query_string:
            # We must empty the traversal stack to prevent an error
            # when calling RedirectionView.publishTraverse().
            self.request.setTraversalStack([])
            target = "%s%s?%s" % (self.request.getApplicationURL(),
                                  self.request['PATH_INFO'],
                                  normalized_query_string)
            redirect = RedirectionView(target, self.request, 301)
            return redirect

        # Handle the two formats of urls:
        # http://feeds.launchpad.net/bugs/+bugs.atom?...
        # http://feeds.launchpad.net/bugs/1/bug.atom
        if name == 'bugs':
            stack = self.request.getTraversalStack()
            if len(stack) == 0:
                raise NotFound(self, '', self.request)
            bug_id = stack.pop()
            if bug_id.startswith('+'):
                if config.launchpad.is_bug_search_feed_active:
                    return getUtility(IBugTaskSet)
                else:
                    raise Unauthorized("Bug search feed deactivated")
            else:
                self.request.stepstogo.consume()
                return getUtility(IBugSet).getByNameOrID(bug_id)

        # Redirect to the canonical name before doing the lookup.
        if canonical_name(name) != name:
            return self.redirectSubTree(canonical_url(self.context) +
                                        canonical_name(name),
                                        status=301)

        try:
            if name.startswith('~'):
                # Handle persons and teams.
                # http://feeds.launchpad.net/~salgado/latest-bugs.html
                person = getUtility(IPersonSet).getByName(name[1:])
                return person
            else:
                # Otherwise, handle products, projects, and distros
                return getUtility(IPillarNameSet)[name]
        except NotFoundError:
            raise NotFound(self, name, self.request)
Exemplo n.º 9
0
    def fireTransition(self,
                       transition_id,
                       comment=None,
                       side_effect=None,
                       check_security=True):
        state = self.state(self.context)
        transition = self.wf.getTransition(state.getState(), transition_id)

        if check_security and transition.permission is not CheckerPublic:
            # check whether we may execute this workflow transition
            try:
                interaction = getInteraction()
            except NoInteraction:
                checkPermission = nullCheckPermission
            else:
                checkPermission = interaction.checkPermission
            if not checkPermission(transition.permission, self.context):
                raise Unauthorized(self.context,
                                   'transition: {}'.format(transition_id),
                                   transition.permission)

        # now make sure transition can still work in this context
        if not transition.condition(self, self.context):
            raise ConditionFailedError()

        # perform action, return any result as new version
        result = transition.action(self, self.context)
        if result is not None:
            if transition.source is None:
                self.state(result).initialize()
            # stamp it with version
            state = self.state(result)
            state.setId(self.state(self.context).getId())
            # execute any side effect:
            if side_effect is not None:
                side_effect(result)
            event = WorkflowVersionTransitionEvent(result, self.context,
                                                   transition.source,
                                                   transition.destination,
                                                   transition, comment)
        else:
            if transition.source is None:
                self.state(self.context).initialize()
            # execute any side effect
            if side_effect is not None:
                side_effect(self.context)
            event = WorkflowTransitionEvent(self.context, transition.source,
                                            transition.destination, transition,
                                            comment)
        # change state of context or new object
        state.setState(transition.destination)
        notify(event)
        # send modified event for original or new object
        if result is None:
            notify(ObjectModifiedEvent(self.context))
        else:
            notify(ObjectModifiedEvent(result))
        return result
Exemplo n.º 10
0
 def test_raising_unauthorized_without_request(self):
     """Unauthorized exceptions are logged when there's no request."""
     utility = ErrorReportingUtility()
     utility._oops_config.publisher = None
     try:
         raise Unauthorized('xyz')
     except Unauthorized:
         oops = utility.raising(sys.exc_info())
     self.assertNotEqual(None, oops)
Exemplo n.º 11
0
 def permission_checker(self, *args, **kwargs):
     if context_parameter in kwargs:
         context = kwargs[context_parameter]
     else:
         context = args[0]
     if not check_permission(permission, context):
         raise Unauthorized("Permission %s required on %s." %
                            (permission, context))
     return func(self, *args, **kwargs)
Exemplo n.º 12
0
 def test_raising_unauthorized_with_authenticated_principal(self):
     """Unauthorized exceptions are logged when the request has an
     authenticated principal."""
     utility = ErrorReportingUtility()
     utility._oops_config.publisher = None
     request = TestRequestWithPrincipal()
     try:
         raise Unauthorized('xyz')
     except Unauthorized:
         self.assertNotEqual(None, utility.raising(sys.exc_info(), request))
Exemplo n.º 13
0
 def test_raising_unauthorized_without_principal(self):
     """Unauthorized exceptions are logged when the request has no
     principal."""
     utility = ErrorReportingUtility()
     utility._oops_config.publisher = None
     request = ScriptRequest([('name2', 'value2')])
     try:
         raise Unauthorized('xyz')
     except Unauthorized:
         self.assertNotEqual(None, utility.raising(sys.exc_info(), request))
Exemplo n.º 14
0
 def unlinkBug(self, bug, user=None, check_permissions=True):
     """See IBugLinkTarget."""
     if check_permissions and not bug.userCanView(user):
         raise Unauthorized(
             "Cannot unlink a private bug you don't have access to")
     if bug not in self.bugs:
         return False
     self.deleteBugLink(bug)
     notify(ObjectUnlinkedEvent(bug, self, user=user))
     notify(ObjectUnlinkedEvent(self, bug, user=user))
     return True
Exemplo n.º 15
0
 def initialize(self):
     """Raise an Unauthorized exception if the user is not a member of this
     distribution's mirror_admin team.
     """
     # XXX: Guilherme Salgado 2006-06-16:
     # We don't want these pages to be public but we can't protect
     # them with launchpad.Edit because that would mean only people with
     # that permission on a Distribution would be able to see them. That's
     # why we have to do the permission check here.
     if not (self.user and self.user.inTeam(self.context.mirror_admin)):
         raise Unauthorized('Forbidden')
 def topic(self):
     # This is deliberately not a Lazy property
     if ((self.__topic is None) or self.status):
         self.__topic = self.messageQuery.topic_posts(self.topicId)
         if self.__topic[0]['group_id'] != self.groupInfo.id:
             m = 'You are not authorized to access this topic in the '\
                 'group %s' % self.groupInfo.name
             raise Unauthorized(m)
     assert type(self.__topic) == list
     assert len(self.__topic) >= 1, \
         "No posts in the topic %s" % self.topicId
     return self.__topic
Exemplo n.º 17
0
def issueTicket(ident):
    """ issues a timelimit ticket
    >>> type(issueTicket(object()))== type('')
    True
    """
    ticket = str(random.random())
    sm = AccessControl.getSecurityManager()
    user = sm.getUser()
    if user is None:
        raise Unauthorized('No currently authenticated user')
    ticketCache.set(user.getId(), ident, key=dict(ticket=ticket))
    return ticket
Exemplo n.º 18
0
 def _check(self, transition, check_security):
     """Check whether we may execute this workflow transition.
     """
     if check_security:
         checkPermission = self._get_checkPermission()
         if not checkPermission(transition.permission, self.context):
             raise Unauthorized(self.context,
                                "transition: %s" % transition.id,
                                transition.permission)
     # ensure transition can still work in this context, None always passes
     if transition.condition is not None:
         transition.condition(self.context)  # raises BungeniCustomError
Exemplo n.º 19
0
    def _checkPermission(self, obj, name, permission):
        if permission is None:
            __traceback_supplement__ = (TracebackSupplement, obj)
            raise ForbiddenAttribute(name, obj)

        if permission is CheckerPublic:
            return

        if self.interaction.checkPermission(permission, obj):
            return

        __traceback_supplement__ = (TracebackSupplement, obj)
        __traceback_supplement__
        raise Unauthorized(obj, name, permission, self.interaction)
Exemplo n.º 20
0
    def _register(self, obj=None):
        request = get_current_request()
        if hasattr(request, '_db_write_enabled') and not request._db_write_enabled:
            raise Unauthorized('Adding content not permited')

        try:
            assert request._txn_dm is not None
        except (AssertionError, AttributeError):
            if not SHARED_CONNECTION and hasattr(request, 'conn'):
                request._txn_dm = request.conn
            else:
                request._txn_dm = RequestDataManager(request, self)
            self.transaction_manager.get(request).join(request._txn_dm)

        if obj is not None:
            request._txn_dm._registered_objects.append(obj)
Exemplo n.º 21
0
    def traverse_files(self, filename):
        """Traverse on filename in the archive domain."""
        if not check_permission('launchpad.View', self.context):
            raise Unauthorized()
        library_file = self.context.getFileByName(filename)

        # Deleted library files result in NotFound-like error.
        if library_file.deleted:
            raise DeletedProxiedLibraryFileAlias(filename, self.context)

        # There can be no further path segments.
        if len(self.request.stepstogo) > 0:
            return None

        return RedirectionView(library_file.getURL(include_token=True),
                               self.request)
Exemplo n.º 22
0
 def linkBug(self, bug):
     """See IBugLinkTarget."""
     # XXX gmb 2007-12-11 bug=175545:
     #     We shouldn't be calling check_permission here. The user's
     #     permissions should have been checked before this method
     #     was called. Also, we shouldn't be relying on the logged-in
     #     user in this method; the method should accept a user
     #     parameter.
     if not check_permission('launchpad.View', bug):
         raise Unauthorized(
             "cannot link to a private bug you don't have access to")
     for buglink in self.bug_links:
         if buglink.bug.id == bug.id:
             return buglink
     buglink = self.createBugLink(bug)
     notify(ObjectCreatedEvent(buglink))
     return buglink
Exemplo n.º 23
0
    def check(self, obj, name):
        permission = self.get_permissions.get(name)
        if permission is not None:
            if permission is CheckerPublic:
                return  # Public
            request = get_current_request()
            if IInteraction(request).checkPermission(permission, obj):
                return
            else:
                __traceback_supplement__ = (TracebackSupplement, obj)
                raise Unauthorized(obj, name, permission)
        elif name in _available_by_default:
            return

        if name != '__iter__' or hasattr(obj, name):
            __traceback_supplement__ = (TracebackSupplement, obj)
            raise ForbiddenAttribute(name, obj)
Exemplo n.º 24
0
    def check(self, object, name):
        'See IChecker'
        permission = self.get_permissions.get(name)
        if permission is not None:
            if permission is CheckerPublic:
                return # Public
            if thread_local.interaction.checkPermission(permission, object):
                return
            else:
                __traceback_supplement__ = (TracebackSupplement, object)
                raise Unauthorized(object, name, permission)
        elif name in _available_by_default:
            return

        if name != '__iter__' or hasattr(object, name):
            __traceback_supplement__ = (TracebackSupplement, object)
            raise ForbiddenAttribute(name, object)
Exemplo n.º 25
0
    def check_setattr(self, object, name):
        'See IChecker'
        if self.set_permissions:
            permission = self.set_permissions.get(name)
        else:
            permission = None

        if permission is not None:
            if permission is CheckerPublic:
                return # Public
            if thread_local.interaction.checkPermission(permission, object):
                return # allowed
            else:
                __traceback_supplement__ = (TracebackSupplement, object)
                raise Unauthorized(object, name, permission)

        __traceback_supplement__ = (TracebackSupplement, object)
        raise ForbiddenAttribute(name, object)
Exemplo n.º 26
0
def _issueTicket(ident):
    """ issues a timelimit ticket 
    """
    ticket = str(random.random())
    sm = AccessControl.getSecurityManager()
    user = sm.getUser()
    if user is None:
        raise Unauthorized('No currently authenticated user')
    try:
        # see #28 — ticket handling: discrepancy in obtaining user's id
        # (issueTicket vs utils.find_user)
        uname = user.getName()
    except AttributeError:
        # <PropertiedUser 'admin'> has no getName(), thus we use getUserName()
        uname = user.getUserName()
    cache = _getCache()
    kw = {'ticket':ticket}
    cache.set(ident+ticket, uname)
    return ticket
Exemplo n.º 27
0
    def check_setattr(self, obj, name):
        if self.set_permissions:
            permission = self.set_permissions.get(name)
        else:
            permission = None

        if permission is not None:
            if permission is CheckerPublic:
                return  # Public

            request = get_current_request()
            if IInteraction(request).checkPermission(permission, obj):
                return  # allowed
            else:
                __traceback_supplement__ = (TracebackSupplement, obj)
                raise Unauthorized(obj, name, permission)

        __traceback_supplement__ = (TracebackSupplement, obj)
        raise ForbiddenAttribute(name, obj)
Exemplo n.º 28
0
 def userInfo(self):
     userId = self.userId
     if userId:
         user = self.context.acl_users.getUser(userId)
         # --=mpj17=-- Ask me no questions...
         interaction = zope.security.management.queryInteraction()
         if interaction is None:
             zope.security.management.newInteraction()
         # --=mpj17=-- ...I tell you no lies.
         if not zope.security.management.checkPermission(
                 "zope2.ManageProperties", user):
             m = "Not authorized to manage the settings of user {0}."
             msg = m.format(userId)
             raise Unauthorized(msg)
         retval = createObject('groupserver.UserFromId', self.context,
                               userId)
     else:
         retval = self.loggedInUser
     return retval
Exemplo n.º 29
0
    def unlinkBug(self, bug):
        """See IBugLinkTarget."""
        # XXX gmb 2007-12-11 bug=175545:
        #     We shouldn't be calling check_permission here. The user's
        #     permissions should have been checked before this method
        #     was called. Also, we shouldn't be relying on the logged-in
        #     user in this method; the method should accept a user
        #     parameter.
        if not check_permission('launchpad.View', bug):
            raise Unauthorized(
                "cannot unlink a private bug you don't have access to")

        # see if a relevant bug link exists, and if so, delete it
        for buglink in self.bug_links:
            if buglink.bug.id == bug.id:
                notify(ObjectDeletedEvent(buglink))
                self.buglinkClass.delete(buglink.id)
                # XXX: Bjorn Tillenius 2005-11-21: We shouldn't return the
                #      object that we just deleted from the db.
                return buglink
Exemplo n.º 30
0
    def update(self):
        self.person = IPerson(self.request.principal, None)
        if self.person is None:
            # XXX ignas: i had to do this to make the tests pass,
            # someone who knows what this code should do if the user
            # is unauthenticated should add the relevant code
            raise Unauthorized("You don't have the permission to do this.")

        if 'DELETE' in self.request:
            for name in self.request.get('delete', []):
                del self.context[name]
        elif 'form-submitted' in self.request:
            old_pos = 0
            for activity in self.context.values():
                old_pos += 1
                name = getName(activity)
                if 'pos.' + name not in self.request:
                    continue
                new_pos = int(self.request['pos.' + name])
                if new_pos != old_pos:
                    self.context.changePosition(name, new_pos - 1)