def guarded_import(mname, globals=None, locals=None, fromlist=None, level=import_default_level): if fromlist is None: fromlist = () if globals is None: globals = {} if locals is None: locals = {} # Refs https://bugs.launchpad.net/zope2/+bug/659968 if level != import_default_level: raise Unauthorized("Using import with a level specification isn't " "supported by AccessControl: %s" % mname) mnameparts = mname.split('.') validate = getSecurityManager().validate module = load_module(None, None, mnameparts, validate, globals, locals) if module is None: raise Unauthorized("import of '%s' is unauthorized" % mname) for name in fromlist: v = getattr(module, name, None) if v is None: v = load_module(module, mname, [name], validate, globals, locals) if not validate(module, module, name, v): raise Unauthorized else: return __import__(mname, globals, locals, fromlist)
def _modify(self, token, role, type_): if not token or not type_: raise BadRequest('No userid or type provided.') if role not in MANAGED_ROLES: raise Unauthorized('Inavlid role provided.') if token == api.user.get_current().id: raise Unauthorized('Not allowed to modify the current user.') if type_ == 'user': user_roles = api.user.get_roles(username=token, obj=self.context, inherit=False) if user_roles and 'WorkspaceOwner' not in user_roles: assignment = InvitationRoleAssignment(token, [role], self.context) RoleAssignmentManager( self.context).add_or_update_assignment(assignment) self.context.setModificationDate() self.context.reindexObject(idxs=['modified']) self.request.RESPONSE.setStatus(204) return True else: raise BadRequest('User does not have any local roles') elif type_ == 'invitation': storage = getUtility(IInvitationStorage) storage.update_invitation(token, role=role) else: raise BadRequest('Wrong type')
def unauthorized(self): exc = Unauthorized() exc.title = 'You are not authorized to access this resource.' if self.debug_mode: if self._auth: exc.detail = 'Username and password are not correct.' else: exc.detail = 'No Authorization header found.' raise exc
def unauthorized(self): message = 'You are not authorized to access this resource.' exc = Unauthorized(message) exc.title = message if self.debug_mode: if self._auth: exc.detail = 'Username and password are not correct.' else: exc.detail = 'No Authorization header found.' raise exc
def _verifyObjectPaste(self, object, validate_src=1): # Verify whether the current user is allowed to paste the # passed object into self. This is determined by checking # to see if the user could create a new object of the same # meta_type of the object passed in and checking that the # user actually is allowed to access the passed in object # in its existing context. # # Passing a false value for the validate_src argument will skip # checking the passed in object in its existing context. This is # mainly useful for situations where the passed in object has no # existing context, such as checking an object during an import # (the object will not yet have been connected to the acquisition # heirarchy). if not hasattr(object, 'meta_type'): raise CopyError('Not Supported') if not hasattr(self, 'all_meta_types'): raise CopyError('Cannot paste into this object.') mt_permission = None meta_types = absattr(self.all_meta_types) for d in meta_types: if d['name'] == object.meta_type: mt_permission = d.get('permission') break if mt_permission is not None: sm = getSecurityManager() if sm.checkPermission(mt_permission, self): if validate_src: # Ensure the user is allowed to access the object on the # clipboard. try: parent = aq_parent(aq_inner(object)) except Exception: parent = None if not sm.validate(None, parent, None, object): raise Unauthorized(absattr(object.id)) if validate_src == 2: # moving if not sm.checkPermission(delete_objects, parent): raise Unauthorized('Delete not allowed.') else: raise CopyError('Insufficient privileges') else: raise CopyError('Not Supported')
def validate(self): previous_question_id = self.previous_question_id if not previous_question_id: return training = self.get_or_create_training() try: answers = loads(training.answers) except ValueError: answers = {} if all([answer is None for answer in answers]): raise Unauthorized( _("You should start the training from the beginning")) if answers.get(previous_question_id) is None: raise Unauthorized(_("It seems you missed a slide"))
def create(container, type_, id_=None, title=None): """Create a new content item.""" # Generate a temporary id if the id is not given if not id_: now = DateTime() new_id = "{}.{}.{}{:04d}".format( type_.lower().replace(" ", "_"), now.strftime("%Y-%m-%d"), str(now.millis())[7:], randint(0, 9999), ) else: new_id = id_ portal_types = getToolByName(container, "portal_types") type_info = portal_types.getTypeInfo(type_) if not type_info: raise Unauthorized( "Invalid '@type' parameter. No content type with the name '%s' found" % type_) # Check for add permission if not type_info.isConstructionAllowed(container): raise Unauthorized("Cannot create %s" % type_info.getId()) # Check if allowed subobject type container_type_info = portal_types.getTypeInfo(container) if not container_type_info.allowType(type_): raise Unauthorized("Disallowed subobject type: %s" % type_) # Check for type constraints if type_ not in [fti.getId() for fti in container.allowedContentTypes()]: raise Unauthorized("Disallowed subobject type: %s" % type_) if type_info.product: # Oldstyle factory factory = type_info._getFactoryMethod(container, check_security=0) new_id = factory(new_id, title=title) obj = container._getOb(new_id) else: factory = getUtility(IFactory, type_info.factory) obj = factory(new_id, title=title) if base_hasattr(obj, "_setPortalTypeName"): obj._setPortalTypeName(type_info.getId()) return obj
def __call__(self): training = self.get_or_create_training() if training.status not in ("correct", "success"): raise Unauthorized("You do not own the certificate") if self.request.method == "POST": return self.post() return super(SlideQuestionSuccess, self).__call__()
def restrictedTraverse(object, path, securityManager, get=getattr, has=hasattr, N=None, M=[], TupleType=type(())): REQUEST = {'path': path} REQUEST['TraversalRequestNameStack'] = path = path[:] # Copy! path.reverse() validate = securityManager.validate __traceback_info__ = REQUEST done = [] while path: name = path.pop() __traceback_info__ = TraversalError(done, name) if isinstance(name, TupleType): object = object(*name) continue if not name: # Skip directly to item access o = object[name] # Check access to the item. if not validate(object, object, name, o): raise Unauthorized(name) object = o continue # Try an attribute. o = guarded_getattr(object, name, M) if o is M: # Try an item. try: # XXX maybe in Python 2.2 we can just check whether # the object has the attribute "__getitem__" # instead of blindly catching exceptions. o = object[name] except AttributeError as exc: if str(exc).find('__getitem__') >= 0: # The object does not support the item interface. # Try to re-raise the original attribute error. # XXX I think this only happens with # ExtensionClass instances. guarded_getattr(object, name) raise except TypeError as exc: if str(exc).find('unsubscriptable') >= 0: # The object does not support the item interface. # Try to re-raise the original attribute error. # XXX This is sooooo ugly. guarded_getattr(object, name) raise done.append((name, o)) object = o return object
def create_response(self, text): response_handler = ICommentResponseHandler(self.context) if not response_handler.is_allowed(): raise Unauthorized( "The current user is not allowed to add comments") return response_handler.add_response(text)
def modify(self): """ A traversable method to modify a users local roles""" CheckAuthenticator(self.request) token = self.request.get('token', None) role = self.request.get('role', None) type_ = self.request.get('type', None) if not token or not type_: raise BadRequest('No userid or type provided.') if role not in MANAGED_ROLES: raise Unauthorized('Inavlid role provided.') if type_ == 'user': user_roles = api.user.get_roles(username=token, obj=self.context, inherit=False) if user_roles and 'WorkspaceOwner' not in user_roles: self.context.manage_setLocalRoles(token, [role]) self.context.setModificationDate() self.context.reindexObject(idxs=['modified']) self.request.RESPONSE.setStatus(204) return '' else: raise BadRequest('User does not have any local roles') elif type_ == 'invitation': storage = getUtility(IInvitationStorage) storage.update_invitation(token, role=role) else: raise BadRequest('Wrong type')
def render(self): if self.is_already_done(): # Set correct content type for text response self.request.response.setHeader("Content-type", "text/plain") return 'OK' mtool = getToolByName(self.context, 'portal_membership') member = mtool.getAuthenticatedMember() if not member.checkPermission('Add portal content', self.context): raise Unauthorized() successor_oguid = self.request.get('successor_oguid') transition = self.request.get('transition') response_text = self.request.get('response_text') if transition: change_task_workflow_state(self.context, transition, text=response_text, successor_oguid=successor_oguid) IYearfolderStorer(self.context).store_in_yearfolder() # Set correct content type for text response self.request.response.setHeader("Content-type", "tex/plain") return 'OK'
def decide(self): """Decide the current agendaitem and move the meeting in the held state. """ meeting_state = self.meeting.get_state() if not self.context.model.is_editable(): raise Unauthorized("Editing is not allowed") self.agenda_item.decide() response = JSONResponse(self.request) if self.agenda_item.has_proposal: response.info( _(u'agenda_item_proposal_decided', default=u'Agenda Item decided and excerpt generated.')) else: response.info( _(u'agenda_item_decided', default=u'Agenda Item decided.')) if meeting_state != self.meeting.get_state(): response.redirect(self.context.absolute_url()) msg = _( u'agenda_item_meeting_held', default= u"Agendaitem has been decided and the meeting has been held.") api.portal.show_message(message=msg, request=self.request, type='info') return response.dump()
def edit(self): """Updates the title of the agendaitem, with the one given by the request parameter `title`. """ if not self.context.model.is_editable(): raise Unauthorized("Editing is not allowed") title = self.request.get('title') if not title: return JSONResponse(self.request).error( _('agenda_item_update_empty_string', default=u"Agenda Item title must not be empty.")).proceed( ).dump() title = title.decode('utf-8') if self.agenda_item.has_proposal: if len(title) > ISubmittedProposalModel['title'].max_length: return JSONResponse(self.request).error( _('agenda_item_update_too_long_title', default=u"Agenda Item title is too long.")).proceed( ).dump() self.agenda_item.set_title(title) return JSONResponse(self.request).info( _('agenda_item_updated', default=u"Agenda Item updated.")).proceed().dump()
def __call__(self): # first let's check if the authenticated member has permission pmt = getToolByName(self.context, 'portal_membership') member = pmt.getAuthenticatedMember() if not pmt.checkPermission('Modify portal content', self.context): raise Unauthorized( 'User %s does not have the required permissions ' 'to add content to %s.' % (member.getId(), self.context.getId())) content_type = getContentType(getHeader(self.request, 'content-type')) disposition = getHeader(self.request, 'content-disposition') slug = getHeader(self.request, 'slug') filename = None if slug is not None: filename = slug elif disposition is not None: try: filename = [x.strip() for x in disposition.split(';') \ if x.strip().startswith('filename=')][0][9:] except IndexError: pass filename = self.generateFilename(filename) if (disposition is not None or slug is not None) and \ filename in self.context.objectIds(): raise PreconditionFailed("%s is in use" % filename) obj = self.createObject(self.context, filename, content_type, self.request) obj = self.updateObject(obj, filename, self.request, self.response, content_type) return obj
def reply(self): if not self.comment_id: raise BadRequest("Comment id is a required part of the url") conversation = IConversation(self.context) if self.comment_id not in list(conversation): self.request.response.setStatus(404) return comment = conversation[self.comment_id] # Permission checks if not (edit_comment_allowed() and can_edit(comment)): raise Unauthorized() # Fake request data body = json_body(self.request) for key, value in body.items(): self.request.form["form.widgets." + key] = value form = EditCommentForm(comment, self.request) form.__parent__ = form.context.__parent__.__parent__ form.update() action = form.actions["comment"] data, errors = form.extractData() if errors: raise BadRequest({"errors": [err.error for err in errors]}) comment.modification_date = datetime.utcnow() form.handleComment(form=form, action=action) fix_location_header(self.context, self.request) return self.reply_no_content()
def render(self): if not self.context.is_submitted_document(): raise NoSubmittedDocument() if self.context.is_checked_out(): raise Unauthorized() with elevated_privileges(): transporter = Transporter() transporter.update(self.context, self.request) portal_path = '/'.join(api.portal.get().getPhysicalPath()) intids = getUtility(IIntIds) repository = api.portal.get_tool('portal_repository') comment = translate(_( u"Updated with a newer docment version from proposal's " "dossier."), context=self.request) repository.save(obj=self.context, comment=comment) data = { 'path': '/'.join(self.context.getPhysicalPath())[len(portal_path) + 1:], 'intid': intids.queryId(self.context) } # Set correct content type for JSON response self.request.response.setHeader("Content-type", "application/json") return json.dumps(data)
def update(self): mtool = getToolByName(self.context, 'portal_membership') user = mtool.getAuthenticatedMember() if not can_access_public_trial_edit_form(user, self.context): raise Unauthorized('You cannot access this resource.') super(EditPublicTrialForm, self).update()
def __call__(self): """Return the children of the <head> tag as a fragment. """ # Check for the registered view permission try: type_ = queryUtility(ITileType, self.context.__name__) permission = type_.view_permission except AttributeError: permission = None if permission: if not checkPermission(permission, self.context): raise Unauthorized() if self.request.getHeader(ESI_HEADER): del self.request.environ[ESI_HEADER_KEY] document = self.context() # render the tile # Disable the theme so we don't <html/>-wrapped self.request.response.setHeader('X-Theme-Disabled', '1') match = BODY_CHILDREN.search(document) if not match: return document return match.group(1).strip()
def create(container, type_, id_=None, title=None): """Create a new content item.""" # Generate a temporary id if the id is not given if not id_: now = DateTime() new_id = '{}.{}.{}{:04d}'.format(type_.lower().replace(' ', '_'), now.strftime('%Y-%m-%d'), str(now.millis())[7:], randint(0, 9999)) else: if isinstance(id_, unicode): new_id = id_.encode('utf8') else: new_id = id_ portal_types = getToolByName(container, 'portal_types') type_info = portal_types.getTypeInfo(type_) # Check for add permission if not type_info.isConstructionAllowed(container): raise Unauthorized('Cannot create %s' % type_info.getId()) # Check if allowed subobject type container_type_info = portal_types.getTypeInfo(container) if not container_type_info.allowType(type_): raise Unauthorized('Disallowed subobject type: %s' % type_) # Check for type constraints if type_ not in [fti.getId() for fti in container.allowedContentTypes()]: raise Unauthorized('Disallowed subobject type: %s' % type_) if type_info.product: # Oldstyle factory factory = type_info._getFactoryMethod(container, check_security=0) new_id = factory(new_id, title=title) obj = container._getOb(new_id) else: factory = getUtility(IFactory, type_info.factory) obj = factory(new_id, title=title) if base_hasattr(obj, '_setPortalTypeName'): obj._setPortalTypeName(type_info.getId()) return obj
def reply(self): data = json_body(self.request) if data.keys() != ['ordering']: if not api.user.has_permission('Modify portal content', obj=self.context): raise Unauthorized() return super(WorkspaceContentPatch, self).reply()
def as_json(self): """Return the table of contents data as JSON.""" if not self.is_manager(): raise Unauthorized() response = self.request.response response.setHeader('Content-Type', 'application/json') response.setHeader('X-Theme-Disabled', 'True') return self.get_json_data(pretty=True)
def unauthorized(self): m = "You are not authorized to access this resource." if self.debug_mode: if self._auth: m = m + '\nUsername and password are not correct.' else: m = m + '\nNo Authorization header found.' raise Unauthorized(m)
def _assert_current_user_owns_key(self, key_id): """Verify that the currently logged in user owns the given key. """ current_user = api.user.get_current() service_key = self.get_service_key(key_id, unrestricted=True) if not service_key or service_key['user_id'] != current_user.id: raise Unauthorized()
def unauthorized(self): m = "<strong>You are not authorized to access this resource.</strong>" if self.debug_mode: if self._auth: m = m + '<p>\nUsername and password are not correct.</p>' else: m = m + '<p>\nNo Authorization header found.</p>' raise Unauthorized(m)
def test_exception_calls_unauthorized(self): from zExceptions import Unauthorized response = self._makeOne() _unauthorized = DummyCallable() response._unauthorized = _unauthorized with self.assertRaises(Unauthorized): response.exception(info=(Unauthorized, Unauthorized('fail'), None)) self.assertEqual(_unauthorized._called_with, ((), {}))
def _metaclass(name, bases, dict): for k, v in dict.items(): if k.endswith('__roles__') and k[:len('__roles__')] not in dict: raise Unauthorized("Can't override security: %s" % k) ob = type(name, bases, dict) ob.__allow_access_to_unprotected_subobjects__ = 1 ob._guarded_writes = 1 return ob
def testHandleErrorsFalseBypassesExceptionResponse(self): from AccessControl import Unauthorized environ = self._makeEnviron(**{ 'x-wsgiorg.throw_errors': True, }) start_response = DummyCallable() _publish = DummyCallable() _publish._raise = Unauthorized('argg') with self.assertRaises(Unauthorized): self._callFUT(environ, start_response, _publish)
def reply(self): current_user_id = api.user.get_current().id if current_user_id != self.read_params(): raise Unauthorized() results = { 'checked_out': self._get_checked_out(current_user_id), 'recently_touched': self._get_recently_touched(current_user_id), } return results
def get_notification(self, userid, notification_id): notification = self.center.get_notification(notification_id) if not notification: raise NotFound if not notification.userid == userid: raise Unauthorized( "It's not allowed to access notifications of other users.") return self.serialize(notification)
def reply(self): userid, notification_id = self.read_params() if userid != api.user.get_current().getId(): raise Unauthorized( "It's not allowed to access notifications of other users.") if notification_id: return self.get_notification(userid, notification_id) return self.get_user_notifications()