def update(self): request = self.request nextURL = request.get("nextURL") if not IUnauthenticatedPrincipal.providedBy(request.principal): getUtility(IAuthentication).logout(request) if nextURL: self.redirect(nextURL) elif not IUnauthenticatedPrincipal.providedBy(request.principal): self.redirect("logout.html")
def get_user_context_roles(): """Get the list of user's roles (including whether admin or not)--this is the info needed (in addition to the field's modes) to further filter whether a field is visible or not for a given (user, mode). Wraps common.get_context_roles(context), with the following differcnes: - auto retrieves the context, needed param by common.get_context_roles() - handles case when user is not authenticated - handles case for when user is "admin" """ request = common.get_request() if request is None: context = None principal = None else: context = common.get_traversed_context(request) principal = request.principal if IUnauthenticatedPrincipal.providedBy(principal): roles = ["bungeni.Anonymous"] else: roles = common.get_context_roles(context) if common.is_admin(context): roles.append("bungeni.Admin") log.debug(""" [get_user_context_roles] PRINCIPAL: %s CONTEXT: %s ROLES: %s """ % (principal, context, roles)) return roles
def _maybePlacefullyAuthenticate(self, request, ob): if not IUnauthenticatedPrincipal.providedBy(request.principal): # We've already got an authenticated user. There's nothing to do. # Note that beforeTraversal guarentees that user is not None. return if not ISite.providedBy(ob): # We won't find an authentication utility here, so give up. return sm = removeSecurityProxy(ob).getSiteManager() auth = sm.queryUtility(IAuthentication) if auth is None: # No auth utility here return # Try to authenticate against the auth utility principal = auth.authenticate(request) if principal is None: principal = auth.unauthenticatedPrincipal() if principal is None: # nothing to do here return request.setPrincipal(principal)
def render(self): if not IUnauthenticatedPrincipal.providedBy(self.request.principal): auth = component.getUtility(IAuthentication) ILogout(auth).logout(self.request) self.flash(_(u'You are now logged out'), type=u'message') return self.redirect(self.application_url())
def publishTraverse(self, request, name): context = self.context view = queryMultiAdapter((context, request), name=name) if view is not None: return view if not IUnauthenticatedPrincipal.providedBy(request.principal): try: taskId = int(name) except: taskId = None if taskId: task = getUtility(IIntIds).queryObject(taskId) if task is not None: space = context.__parent__ if space.principalId != request.principal.id: space = IPersonalSpace(request.principal, None) if space is None: raise NotFound(context, name, request) else: request.response.redirect( '%s/mytasks/%s/'%( absoluteURL(space, request), name)) return LocationProxy(task, context, name) if name in context: return context[name] raise NotFound(context, name, request)
def get_request_context_roles(request): """Get the list of user's roles (including whether admin or not) relevant for this request layer. Wraps get_context_roles(context), with the following differences: - auto determines the context, a needed param for get_context_roles() - when within a public layer, always returns ["bungeni.Anonymous"] - handles case when user is not authenticated - handles case for when user is "admin" """ request = request or get_request() if request is None: context = None principal = None else: context = get_traversed_context(request) principal = request.principal # within a public layer, just proceed as "bungeni.Anonymous" if is_public_layer(request): return ["bungeni.Anonymous"] # other layers if IUnauthenticatedPrincipal.providedBy(principal): roles = ["bungeni.Anonymous"] else: roles = get_context_roles(context, principal) if is_admin(context): roles.append("bungeni.Admin") log.debug(""" [get_request_context_roles] PRINCIPAL: %s CONTEXT: %s ROLES: %s """ % (principal, context, roles)) return roles
def isAvailable(self): if IUnauthenticatedPrincipal.providedBy(self.request.principal): return False principal = self.context.__principal__ principalId = principal.id if self.request.principal.id == principalId: return False invitations = [ invitation.object.id for invitation in getUtility(IInvitations).getInvitationsByPrincipal( principalId, ('invitation.member',))] for group in getUtility(ICatalog).searchResults( type = {'any_of': ('content.group',)}, members = {'any_of': (self.request.principal.id,)}): if group.id in invitations: continue if principalId not in group.members and \ checkPermission('zojax.InviteGroupMember', group): return True return False
def isAvailable(self): if IUnauthenticatedPrincipal.providedBy(self.request.principal): return False if self.oid is None: return False else: return True
def __call__(self): request = self.request if not IUnauthenticatedPrincipal.providedBy(request.principal) and "worldcookery.Login" in request: camefrom = request.get("camefrom", ".") request.response.redirect(camefrom) else: return self.template()
def __call__(self, *args, **kw): request = self.request context = self.context siteURL = u'%s/'%absoluteURL(context, request) if not IUnauthenticatedPrincipal.providedBy(request.principal): self.redirect(siteURL) return u'' if not 'openid_form_submitted' in request: self.redirect(siteURL) return u'' identifier = request.get('openid_identifier') if not identifier or identifier == 'http://': IStatusMessage(request).add( _(u"Please specify your OpenID identifier.")) self.redirect(u'%slogin.html'%siteURL) return u'' authenticator = getUtility(IUsersPlugin) session = ISession(request)[SESSION_KEY] consumer = Consumer(session, authenticator.store) try: authRequest = consumer.begin(identifier) redirectURL = authRequest.redirectURL( siteURL, getReturnToURL(request)) except Exception, err: IStatusMessage(request).add(err, 'error') self.redirect(u'%slogin.html'%siteURL) return u''
def __call__(self): if IUnauthenticatedPrincipal.providedBy(self.request.principal): self.request.response.redirect( ui_utils.url.absoluteURL( getSite(), self.request)+"/login" ) return super(ChangePasswordForm, self).__call__()
def __call__(self): if not IUnauthenticatedPrincipal.providedBy(self.request.principal): app = getSite() workspace = app["workspace"] self.request.response.redirect( ui_utils.url.absoluteURL(workspace, self.request)) return super(Login, self).__call__()
def __call__(self): request = self.request siteURL = u'%s/'%absoluteURL(getSite(), request) if not IUnauthenticatedPrincipal.providedBy(request.principal): request.response.redirect(siteURL) return u'' if not 'openid_form_submitted' in request: request.response.redirect(siteURL) return u'' identifier = request.get('openid_identifier') if not identifier: IStatusMessage(request).add( _(u"Please specify your OpenID identifier.")) request.response.redirect(siteURL) return u'' authenticator = getUtility(IOpenIdAuthenticator) session = ISession(request)[SESSION_KEY] consumer = Consumer(session, authenticator.store) try: authRequest = consumer.begin(identifier) redirectURL = authRequest.redirectURL( siteURL, getReturnToURL(request)) except Exception, err: IStatusMessage(request).add(err, 'error') redirectURL = siteURL
def isAvailable(self): request = self.request principal = request.principal if not IUnauthenticatedPrincipal.providedBy(principal): return False auth = getUtility(IAuthentication) login = queryMultiAdapter((auth, request), ILoginService) if login is not None: if login.isChallenging(): return False if IPluggableAuthentication.providedBy(auth): for name, creds in auth.getCredentialsPlugins(): if IDefaultCredentialsPlugin.providedBy(creds): self.nextURL = login.nextURL() if self.hasOpenId: include("portlet-login") return True return False
def publishTraverse(self, request, name,view): if view is None: view = queryMultiAdapter((self.context, request), name='main.html') principal = request.principal if IUnauthenticatedPrincipal.providedBy(principal): alsoProvides(request,IAdvertLayer) return view
def test_context_roles(self, mode): """EXPERIMENTAL sample code to get a user's roles and whether is_admin or not -- this is the info needed (in addition to the field's modes) to further filter whether a field is visible or not for a given (user, mode). """ request = common.get_request() if request is None: context = None principal = None else: context = common.get_traversed_context(request) principal = request.principal if IUnauthenticatedPrincipal.providedBy(principal): roles = None else: roles = common.get_context_roles(context) print """!+ModelDescriptor TEST_CONTEXT_ROLES [%s] PRINCIPAL: %s CONTEXT: %s MODE: %s ROLES: %s IS ADMIN: %s""" % (self, principal, context, mode, roles, common.is_admin(context) )
def isAvailable(self): if not IUnauthenticatedPrincipal.providedBy(self.request.principal): return False configlet = component.getUtility(IConfiglet, name="product.zojax-authentication-twitter") if not configlet.consumerKey or not configlet.consumerSecret: return False return True
def getURL(self, type=""): principal = self.request.principal if IUnauthenticatedPrincipal.providedBy(principal): return homeFolder = IHomeFolder(principal).homeFolder homeFolder = grok.url(self.request, homeFolder, type) return homeFolder
def canAssignPrincipal(self, principal): if (not IUnauthenticatedPrincipal.providedBy(principal) and IPrincipal.providedBy(principal) and not IGroup.providedBy(principal) and checkPermissionForPrincipal(principal,'zojax.PersonalSpace',self)): return True return False
def isAvailable(self): if IUnauthenticatedPrincipal.providedBy(self.request.principal): return False if not self.context.members.isMember(self.request.principal.id): return super(JoinAction, self).isAvailable() return False
def handle_login(self, action, data): if IUnauthenticatedPrincipal.providedBy(self.request.principal): self.status = _(u"Invalid account credentials") else: site_url = ui_utils.url.absoluteURL(getSite(), self.request) camefrom = self.request.get('camefrom', site_url+'/') self.status = _("You are now logged in") self.request.response.redirect( camefrom )
def isAvailable(self): if IUnauthenticatedPrincipal.providedBy(self.request.principal): return False for name, adapter in getAdapters((self.context,), IContentNotification): return True return False
def handle_login(self, action, data): if IUnauthenticatedPrincipal.providedBy(self.request.principal): self.status = _(u"Invalid account credentials") else: if data.get("camefrom", None) and data.get("camefrom").strip(): camefrom = data["camefrom"].strip() else: camefrom = absoluteURL(get_application(), self.request) self.status = _("You are now logged in") self.request.response.redirect(camefrom)
def sayhello(self): """User authentication""" #We should kick off session component.getUtility(IClientIdManager).setRequestId(self.request, str(int(time.time()) - 1000000000) ) if not IUnauthenticatedPrincipal.providedBy(self.request.principal): return "Hello" else: return ""
def login(self, nextURL=None): # we don't want to keep challenging if we're authenticated if IUnauthenticatedPrincipal.providedBy(self.request.principal): component.getUtility(IAuthentication).unauthorized(self.request.principal.id, self.request) return self.failed() else: if nextURL is None: return self.confirmation() else: self.request.response.redirect(nextURL)
def getPersonalSpace(principal): """Get the home folder instance of the principal.""" if IUnauthenticatedPrincipal.providedBy(principal): return None manager = getSite().get('people') if IPersonalSpaceManager.providedBy(manager): return manager.getPersonalSpace(principal) return None
def logout(self, nextURL=None): if not IUnauthenticatedPrincipal.providedBy(self.request.principal): auth = component.getUtility(IAuthentication) ILogout(auth).logout(self.request) if nextURL: return self.redirect() if nextURL is None: return self.confirmation() else: return self.request.response.redirect(nextURL)
def update(self): context = self.context request = self.request self.noIcon = not bool(self.context.icon) principal = self.request.principal if not IUnauthenticatedPrincipal.providedBy(principal): self.menu = True self.submitTopic = \ checkPermission('zojax.forum.AddTopic', context) or \ checkPermission('zojax.forum.SubmitTopic', context) notifications = getAdapter(context, IContentNotification, 'forum') self.subscribed = notifications.isSubscribed(principal.id) if len(self.context) > 1: self.searching = True data = ISession(request)[SESSIONKEY] forum = removeAllProxies(context) key = getUtility(IIntIds).getId(forum) if 'form.button.search' in request: searchableText = request['form.searchforum'] data[key] = (searchableText, True) if 'form.button.clear' in request: searchableText = None if key in data: del data[key] else: searchtext, searching = data.get(key, (u'', False)) if searchtext and searching: searchableText = searchtext else: searchableText = None if searchableText: query = {'searchableText': searchableText, 'type': {'any_of': ('forum.message',)}, 'traversablePath': {'any_of': (forum,)}, 'noPublishing': True, 'noSecurityChecks': True} try: results = getUtility(ICatalog).searchResults(**query) except Exception, e: IStatusMessage(self.request).add(e, 'error') return self.total = len(results) self.searchableText = searchableText self.searchResults = Batch(results, size=20, request=request)
def getPreferences(site, request): rootGroup = getUtility(IPreferenceGroup) rootGroup = rootGroup.__bind__() if IUnauthenticatedPrincipal.providedBy(rootGroup.__principal__): raise Unauthorized('preferences') if rootGroup.isAvailable(): return rootGroup else: return None
def login(self, nextURL=None): # we don't want to keep challenging if we're authenticated if IUnauthenticatedPrincipal.providedBy(self.request.principal): # hard-code basic auth challenge self.request.unauthorized("basic realm='Zope'") return self.failed() else: if nextURL is None: return self.confirmation() else: self.request.response.redirect(nextURL)
def menu(self): """Return menu item entries in a TAL-friendly form.""" result = [] principal = getattr(self.request, 'principal', None) if not principal: return result if IUnauthenticatedPrincipal.providedBy(principal): return self.getUnauthenticatedMenu() else: return self.getAuthenticatedMenu()
def update(self): camefrom = self.request.get('camefrom', '.') if not IUnauthenticatedPrincipal.providedBy(self.request.principal): pau = zope.component.getUtility(IAuthentication) ILogout(pau).logout(self.request) if camefrom: return self.request.response.redirect(camefrom) if camefrom is None: ## get and use site instead of self.context? url = absoluteURL(self.context, self.request) return self.request.response.redirect(url) else: return self.request.response.redirect(camefrom)
def render(self): if not IUnauthenticatedPrincipal.providedBy(self.request.principal): formatter = getFormatter(self.request, 'dateTime', 'medium') result = getUtility(IAcknowledgements).verifyRecord( object=self.context, uid=self.request.principal.id) if result: return msg_success % dict(user=self.request.principal.title, date=formatter.format(result.date)) return msg_default
def on_before_traverse(event): """Subscriber to intercept traversal, and dispatch as needed to dedicated request pre-processors. We intercept centrally and then call processors explicitly to guarantee execution order. """ log.debug("IBeforeTraverseEvent:%s:%s:%s" % ( id(event.request), event.request.getURL(), event.object)) apply_request_layer_by_url(event) if not IUnauthenticatedPrincipal.providedBy(event.request.principal): interface.alsoProvides(event.request, interfaces.IBungeniAuthenticatedSkin) remember_traversed_context(event) if has_feature("devmode"): check_reload_localization(event)
def on_before_traverse(event): """Subscriber to intercept traversal, and dispatch as needed to dedicated request pre-processors. We intercept centrally and then call processors explicitly to guarantee execution order. """ # on "first" traversal, remember request "start" (approx) time... if not hasattr(event.request, "_BUNGENI_STARTTIME"): event.request._BUNGENI_STARTTIME = time() log.debug("IBeforeTraverseEvent:%s:%s:%s", hex(id(event.request)), event.request.getURL(), event.object) apply_request_layer_by_url(event) if not IUnauthenticatedPrincipal.providedBy(event.request.principal): interface.alsoProvides(event.request, interfaces.IBungeniAuthenticatedSkin) remember_traversed_context(event) if has_feature("devmode"): forms_localization_check_reload(event)
def __call__(self): try: parameters = self.process_parameters() except UnauthorizedClient as e: return ErrorPage(self.context, self.request, e)() except OAuthException as e: return redirect_error(self.context, self.request, e) if not IUnauthenticatedPrincipal.providedBy(self.request.principal): # authorize form return OAuthAuthorizeForm(self.context, self.request, parameters)() else: # redirect to login form, which will then redirect back to this # page site_url = url.absoluteURL(getSite(), self.request) redirect_url = "{0}?{1}".format( self.request.getURL(), urllib.urlencode(self.request.form)) self.request.response.redirect("{0}/login?camefrom={1}".format( site_url, urllib.quote(redirect_url)))
def test_context_roles(self, mode): """EXPERIMENTAL sample code to get a user's roles and whether is_admin or not -- this is the info needed (in addition to the field's modes) to further filter whether a field is visible or not for a given (user, mode). """ request = common.get_request() if request is None: context = None principal = None else: context = common.get_traversed_context(request) principal = request.principal if IUnauthenticatedPrincipal.providedBy(principal): roles = None else: roles = common.get_context_roles(context) print """!+ModelDescriptor TEST_CONTEXT_ROLES [%s] PRINCIPAL: %s CONTEXT: %s MODE: %s ROLES: %s IS ADMIN: %s""" % (self, principal, context, mode, roles, common.is_admin(context))
def body(self): nextUrl = self.topMenu.url if not IUnauthenticatedPrincipal.providedBy(self.request.principal): auth = component.getUtility(IAuthentication) ILogout(auth).logout(self.request) return self.request.response.redirect(nextUrl)
def available(self): available = IUnauthenticatedPrincipal.providedBy( self.request.principal) return available
def challenge(self, request): if not IUnauthenticatedPrincipal.providedBy(request.principal): return True return None
def update(self): if not IUnauthenticatedPrincipal.providedBy(self.request.principal): auth = getUtility(IAuthentication) ILogout(auth).logout(self.request)
def is_authenticated(self): """Check, wether we are authenticated. """ return not IUnauthenticatedPrincipal.providedBy(self.request.principal)
def handleLogin(self, action): if (not IUnauthenticatedPrincipal.providedBy(self.request.principal)): self.request.response.redirect(self.camefrom) else: self.status = _("Login unsuccessfull, please try again.")
def update(self, login=None, password=None, camefrom=None): request = self.request if (not IUnauthenticatedPrincipal.providedBy(request.principal)): camefrom = request.get('camefrom', '.') self.redirect(camefrom) return
def logged_in(self): # this is the canonical way to tell whether the user is authenticated # in Zope 3: check if the principal provides IUnauthenticatedPrincipal return not IUnauthenticatedPrincipal.providedBy(self.request.principal)
def available(self): return IUnauthenticatedPrincipal(self.request.principal, False)
def __call__(self): nextUrl = self.request.get('nextURL') or self.request.URL[-1] if not IUnauthenticatedPrincipal.providedBy(self.request.principal): auth = component.getUtility(IAuthentication) ILogout(auth).logout(self.request) return self.request.response.redirect(nextUrl)
def __call__(self): if IUnauthenticatedPrincipal.providedBy(self.request.principal): self.request.response.redirect( "%s/login" % (absoluteURL(get_application(), self.request))) return super(ChangePasswordForm, self).__call__()
def __call__(self): if not IUnauthenticatedPrincipal.providedBy(self.request.principal): workspace = get_application()["workspace"] self.request.response.redirect(absoluteURL(workspace, self.request)) return super(Login, self).__call__()