def extractCredentials(self, request): """Extracts credentials from a session if they exist.""" if not IHTTPRequest.providedBy(request): return None session = ISession(request, None) sessionData = session.get('z3c.authenticator.credential.session') login = request.get(self.loginfield, None) password = request.get(self.passwordfield, None) # support z3c.form prefixes for prefix in self.prefixes: login = request.get(prefix + self.loginfield, login) password = request.get(prefix + self.passwordfield, password) credentials = None if login and password: credentials = SessionCredentials(login, password) elif not sessionData: return None sessionData = session['z3c.authenticator.credential.session'] if credentials: sessionData['credentials'] = credentials else: credentials = sessionData.get('credentials', None) if not credentials: return None return {'login': credentials.getLogin(), 'password': credentials.getPassword()}
def add(self, event): self.context.addEvent(event) uid = event.unique_id self._event_name = event.__name__ session_data = ISession(self.request)['schooltool.calendar'] session_data.setdefault('added_event_uids', set()).add(uid) return event
def extractCredentials(self, request): if not IHTTPRequest.providedBy(request): return None login = request.get(self.loginfield, None) password = request.get(self.passwordfield, None) session = ISession(request) sessionData = session.get('zope.pluggableauth.browserplugins') traversalStack = request.getTraversalStack() authMethod = 'standard' credentials = None if sessionData: credentials = sessionData.get('credentials') if isinstance(sessionData, TwoFactorSessionCredentials): authMethod = '2factor' if (authMethod == 'standard' and traversalStack and traversalStack[-1].startswith('++auth++')): authMethod = traversalStack[-1][8:] viewAnnotations = request.annotations.setdefault('loops.view', {}) viewAnnotations['auth_method'] = authMethod #log.info('authentication method: %s.' % authMethod) if authMethod == 'standard': return self.extractStandardCredentials(request, login, password, session, credentials) elif authMethod == '2factor': return self.extract2FactorCredentials(request, login, password, session, credentials) else: return None
def extractCredentials(self, request): if not IHTTPRequest.providedBy(request): return None login = request.get(self.loginfield, None) password = request.get(self.passwordfield, None) session = ISession(request) sessionData = session.get('zope.pluggableauth.browserplugins') traversalStack = request.getTraversalStack() authMethod = 'standard' credentials = None if sessionData: credentials = sessionData.get('credentials') if isinstance(sessionData, TwoFactorSessionCredentials): authMethod = '2factor' if (authMethod == 'standard' and traversalStack and traversalStack[-1].startswith('++auth++')): authMethod = traversalStack[-1][8:] viewAnnotations = request.annotations.setdefault('loops.view', {}) viewAnnotations['auth_method'] = authMethod #log.info('authentication method: %s.' % authMethod) if authMethod == 'standard': return self.extractStandardCredentials( request, login, password, session, credentials) elif authMethod == '2factor': return self.extract2FactorCredentials( request, login, password, session, credentials) else: return None
def logout(self, request): if not IHTTPRequest.providedBy(request): return request.response.expireCookie(self.cookie_name, path="/") session = ISession(request, None) if session is not None: session.delete()
def uninstall(self): """See `IDatabasePolicy`. If the request just handled was not read_only, we need to store this fact and the timestamp in the session. Subsequent requests can then keep using the master until they are sure any changes made have been propagated. """ if not self.read_only: # We need to further distinguish whether it's safe to write # to the session. This will be true if the principal is # authenticated or if there is already a session cookie # hanging around. if not IUnauthenticatedPrincipal.providedBy( self.request.principal) or self._hasSession(): # A non-readonly request has been made. Store this fact # in the session. Precision is hard coded at 1 minute # (so we don't update the timestamp if it is no more # than 1 minute out of date to avoid unnecessary and # expensive write operations). Feeds are always read # only, and since they run over http, browsers won't # send their session key that was set over https, so we # don't want to access the session which will overwrite # the cookie and log the user out. session_data = ISession(self.request)['lp.dbpolicy'] last_write = session_data.get('last_write', None) now = _now() if (last_write is None or last_write < now - timedelta(minutes=1)): # set value session_data['last_write'] = now
def authenticateCredentials(self, credentials): """ Check if username and password match get the credentials from the IUserManagement Utility """ request = zope.security.management.getInteraction().participations[0] session = ISession(request)["adhoc.authentication"] authenticated = session.get(USER_SESSION_KEY) if authenticated is None: if not (credentials and "login" in credentials and "password" in credentials): return login, password = credentials["login"], credentials["password"] utility = IAdHocManagement(request.principal) if not utility.checkRule(login): return user = utility.getData(login) if not user: return if not utility.validatePassword(password, user.get("password")): return user_id = login authenticated = session[USER_SESSION_KEY] = dict(id=user_id, title=login, description=login, login=login) return PrincipalInfo(**authenticated)
def extractCredentials(self, request): """Extracts credentials from a session if they exist.""" if not IHTTPRequest.providedBy(request): return None session = ISession(request) sessionData = session.get( 'zope.pluggableauth.browserplugins') login = request.get(self.loginfield, None) password = request.get(self.passwordfield, None) credentials = None if login and password: credentials = self._makeCredentials(login, password) elif not sessionData: return None sessionData = session[ 'zope.pluggableauth.browserplugins'] if credentials: sessionData['credentials'] = credentials else: credentials = sessionData.get('credentials', None) if not credentials: return None return {'login': credentials.getLogin(), 'password': credentials.getPassword()}
def __init__(self, *args, **kw): # Figure out sorting situation kw['ignore_request'] = True request = args[1] prefix = kw.get('prefix') session = ISession(request)[self.sortKey] if 'sort-on' in request: name = request['sort-on'] if prefix and name.startswith(prefix): name = name[len(prefix):] oldName, oldReverse = session.get(prefix, (None, None)) if oldName == name: session[prefix] = (name, not oldReverse) else: session[prefix] = (name, False) # Now get the sort-on data from the session if prefix in session: kw['sort_on'] = [session[prefix]] super(ListFormatter, self).__init__(*args, **kw) self.columnCSS = {} self.sortOn = (None, None) if 'sort_on' in kw: for name, reverse in kw['sort_on']: self.columnCSS[name] = 'sorted-on' self.sortOn = kw['sort_on'][0]
def authenticateCredentials(self, credentials): """ Check if username and password match get the credentials from the IUserManagement Utility """ request = zope.security.management.getInteraction().participations[0] session = ISession(request)['adhoc.authentication'] authenticated = session.get(USER_SESSION_KEY) if authenticated is None: if not (credentials and 'login' in credentials and 'password' in credentials): return login, password = credentials['login'], credentials['password'] utility = IAdHocManagement(request.principal) if not utility.checkRule(login): return user = utility.getData(login) if not user: return if not utility.validatePassword(password, user.get('password')): return user_id = login authenticated = session[USER_SESSION_KEY] = dict( id=user_id, title=login, description=login, login=login) return PrincipalInfo(**authenticated)
def extractCredentials(self, request, overrides=None): """Extracts credentials from a session if they exist.""" if not IHTTPRequest.providedBy(request): return None session = ISession(request) sessionData = session.get('zope.app.authentication.browserplugins') (login, password, domain, ip) = (None, None, None, None) credentials = None logging_in = False if overrides: login = overrides.get('login', None) password = overrides.get('password', None) ip = overrides.get('ip', None) domain = overrides.get('domain', None) login = login or request.get(self.loginfield, None) password = password or request.get(self.passwordfield, None) domain = domain or request.get(self.domainfield, None) ip = ip or request.environment.get('HTTP_X_FORWARDED_FOR', None) ip = ip or request.environment.get('REMOTE_ADDR', None) if login and password: credentials = SessionCredentials( login, password, ip=ip, domain=domain, request_annotations=request.annotations, passwordManager=self.passwordManager) if IHTTPRequest.providedBy(request): self._update_cookie(request, credentials) logging_in = True elif not sessionData: return None sessionData = session['zope.app.authentication.browserplugins'] if credentials: sessionData['credentials'] = credentials else: credentials = sessionData.get('credentials', None) if not credentials: return None if credentials.isExpired(self.idleExpiry): return None return { 'login': credentials.getLogin(), 'password': credentials.getPassword(), 'ip': credentials.getIP(), 'domain': credentials.getDomain(), 'logging_in': logging_in, 'request-annotations': credentials.getRequestAnnotations(), 'extractTime': credentials.getExtractTime(), 'accessTime': credentials.getAccessTime(), 'passwordManager': credentials.getPasswordManager(), }
def handleLogin(self, action): """Handle the subscribe action will register and login a user.""" if not IUnauthenticatedPrincipal.providedBy(self.request.principal): session = ISession(self.request, None) sessionData = session.get('z3c.authenticator.credential.session') if sessionData is not None and sessionData.get('camefrom'): self.nextURL = sessionData['camefrom'] sessionData['camefrom'] = None
def update(self): self.form = None sn = ISession(self.request)['OAuth2'] if sn is not None and 'form' in sn.keys(): if sn['form']: ctx, view = sn['form'] self.form = component.queryMultiAdapter((ctx, self.request), name=view)
def restorePOSTData(self, request): form = getattr(request, "form", None) if form: form_id = request.form.get('post_form') if form_id: session = ISession(request)[self.session_name] form = session.get(form_id, None) if form is not None: request.form = form del session[form_id]
def traverse(self, path): if path == 'profile': if IUnauthenticatedPrincipal.providedBy(self.request.principal): return self.context else: session = ISession(self.request)['OAuth2'] if 'principal' in session.keys(): user = session['principal'] return IUserProfile(user)
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 extractCredentials(self, request): """Ties to extract credentials from a request. A return value of None indicates that no credentials could be found. Any other return value is treated as valid credentials. """ session = ISession(request)[SESSION_KEY] requestToken = session.get(REQUEST_TOKEN_KEY) accessToken = session.get(ACCESS_TOKEN_KEY) if not requestToken and not accessToken: return None return TwitterCredentials(requestToken, accessToken)
def getCurrentStep(self): """See interfaces.IWizard""" session = ISession(self.request)[self.sessionKey] if 'step' in self.request: name = self.request['step'] step = name, dict(self.steps).get(name) else: step = session.get('step', self.steps[0]) session['step'] = step name, klass = step inst = klass(self.getContent(), self.request, self) inst.name = name return inst
def install(self): """See `IDatabasePolicy`.""" default_flavor = None # If this is a Retry attempt, force use of the master database. if getattr(self.request, '_retry_count', 0) > 0: default_flavor = MASTER_FLAVOR # Select if the DEFAULT_FLAVOR Store will be the master or a # slave. We select slave if this is a readonly request, and # only readonly requests have been made by this user recently. # This ensures that a user will see any changes they just made # on the master, despite the fact it might take a while for # those changes to propagate to the slave databases. elif self.read_only: lag = self.getReplicationLag() if (lag is not None and lag > timedelta(seconds=config.database.max_usable_lag)): # Don't use the slave at all if lag is greater than the # configured threshold. This reduces replication oddities # noticed by users, as well as reducing load on the # slave allowing it to catch up quicker. default_flavor = MASTER_FLAVOR else: # We don't want to even make a DB query to read the session # if we can tell that it is not around. This can be # important for fast and reliable performance for pages like # +opstats. if self._hasSession(): session_data = ISession(self.request)['lp.dbpolicy'] last_write = session_data.get('last_write', None) else: last_write = None now = _now() # 'recently' is 2 minutes plus the replication lag. recently = timedelta(minutes=2) if lag is None: recently = timedelta(minutes=2) else: recently = timedelta(minutes=2) + lag if last_write is None or last_write < now - recently: default_flavor = SLAVE_FLAVOR else: default_flavor = MASTER_FLAVOR else: default_flavor = MASTER_FLAVOR assert default_flavor is not None, 'default_flavor not set!' self.default_flavor = default_flavor
def extract(self, default=NOVALUE): # noqa action = self.request.get('{0}.action'.format(self.name), None) if self.request.get('PATH_INFO', '').endswith('kss_z3cform_inline_validation'): action = 'nochange' if action == 'remove': return None elif action == 'nochange': session = ISession(self.request)[SESSION_PKG_KEY] token = self.uploaded_token if token is None: token = self.request.get('{0}.token'.format(self.name), None) if token in session: self.uploaded_token = token return session.get(token) if self.value is not None: return self.value if self.ignoreContext: return default dm = getMultiAdapter((self.context, self.field), IDataManager) value = dm.query() if isinstance(value, Proxy): value = removeSecurityProxy(value) return value elif action == 'replace': # set the action back to 'nochange' so that the button is # preselected. Only applicable when form is reloaded with errors self.request.form['{0}.action'.format(self.name)] = 'nochange' # empty unnamed FileUploads should not count as a value value = super(NamedFileWidget, self).extract(default) if isinstance(value, FileUpload): value.seek(0, SEEK_END) empty = value.tell() == 0 value.seek(0) if empty and not value.filename: return default value.seek(0) session = ISession(self.request)[SESSION_PKG_KEY] if self.unique_token not in session: self.uploaded_token = self.unique_token value = IDataConverter(self).toFieldValue(value) session[self.unique_token] = value elif not value: return default return value
def test_logging_in_and_logging_out(self): # A test showing that we can authenticate the request after # logInPrincipal() is called, and after logoutPerson() we can no # longer authenticate it. # This is to setup an interaction so that we can call logInPrincipal # below. login('*****@*****.**') logInPrincipal(self.request, self.principal, '*****@*****.**') session = ISession(self.request) # logInPrincipal() stores the account ID in a variable named # 'accountid'. self.assertEqual( session['launchpad.authenticateduser']['accountid'], int(self.principal.id)) # Ensure we are using cookie auth. self.assertIsNotNone( self.request.response.getCookie(config.launchpad_session.cookie) ) principal = getUtility(IPlacelessAuthUtility).authenticate( self.request) self.assertEqual(self.principal.id, principal.id) logoutPerson(self.request) principal = getUtility(IPlacelessAuthUtility).authenticate( self.request) self.assertIsNone(principal)
def clearCredentials(self, request): session = ISession(request)[self.session_name] try: del session['password'] del session['username'] except KeyError: pass
def test_logging_in_and_logging_out_the_old_way(self): # A test showing that we can authenticate a request that had the # person/account ID stored in the 'personid' session variable instead # of 'accountid' -- where it's stored by logInPrincipal(). Also shows # that after logoutPerson() we can no longer authenticate it. # This is just for backwards compatibility. # This is to setup an interaction so that we can do the same thing # that's done by logInPrincipal() below. login('*****@*****.**') session = ISession(self.request) authdata = session['launchpad.authenticateduser'] self.request.setPrincipal(self.principal) authdata['personid'] = self.principal.person.id authdata['logintime'] = datetime.utcnow() authdata['login'] = '******' notify(CookieAuthLoggedInEvent(self.request, '*****@*****.**')) # This is so that the authenticate() call below uses cookie auth. self.request.response.setCookie( config.launchpad_session.cookie, 'xxx') principal = getUtility(IPlacelessAuthUtility).authenticate( self.request) self.assertEqual(self.principal.id, principal.id) self.assertEqual(self.principal.person, principal.person) logoutPerson(self.request) principal = getUtility(IPlacelessAuthUtility).authenticate( self.request) self.assertIsNone(principal)
def render(self, redirect_uri=None, state=None, response_type="code", client_id=None, scope=None): if client_id is None: pass if scope is None: pass if response_type != 'code': pass if client_id in self.context.keys(): code = hashlib.sha256(os.urandom(1024)).hexdigest() session = ISession(self.request)['oauth2serve'] session = session['client_id'] session['redirect_uri'] = redirect_uri session['state'] = state session['code'] = code session['issued'] = dt.now() data = dict(state=state, code=code) if redirect_uri is not None: uri = "{}?{}".format(redirect_uri, urlencode(data)) self.redirect(uri) else: self.redirect(self.url(self.context, name='as_json', data=data)) else: pass
def logoutPerson(request): """Log the user out.""" session = ISession(request) authdata = session['launchpad.authenticateduser'] account_variable_name = 'accountid' previous_login = authdata.get(account_variable_name) if previous_login is None: # This is for backwards compatibility, when we used to store the # person's ID in the 'personid' session variable. account_variable_name = 'personid' previous_login = authdata.get(account_variable_name) if previous_login is not None: authdata[account_variable_name] = None authdata['logintime'] = datetime.utcnow() auth_utility = getUtility(IPlacelessAuthUtility) principal = auth_utility.unauthenticatedPrincipal() request.setPrincipal(principal) # We want to clear the session cookie so anonymous users can get # cached pages again. We need to do this after setting the session # values (e.g., ``authdata['personid'] = None``, above), because that # code will itself try to set the cookie in the browser. We need to # provide a bit of time before the cookie clears (10 minutes at the # moment) so that, if code wants to send a notification (such as "your # account has been deactivated"), the session will still be available # long enough to give the message to the now-unauthenticated user. # The time period could probably be 5 or 10 seconds, if everyone were # on NTP, but...they're not, so we use a pretty high fudge factor of # ten minutes. expireSessionCookie(request) notify(LoggedOutEvent(request))
def notifications(self): # If we have already retrieved our INotificationList this request, # just return it if self._notifications is not None: return self._notifications cookie_name = config.launchpad_session.cookie request = self._request response = self # Do some getattr sniffing so that the doctests in this module # still pass. Doing this rather than improving the Mock classes # that the mixins are used with, as we'll be moving this hack to # the sesions machinery in due course. if (not (getattr(request, 'cookies', None) and getattr(response, 'getCookie', None)) or (request.cookies.get(cookie_name) is not None or response.getCookie(cookie_name) is not None)): session = ISession(self)[SESSION_KEY] try: # Use notifications stored in the session. self._notifications = session['notifications'] # Remove them from the session so they don't propogate to # subsequent pages, unless redirect() is called which will # push the notifications back into the session. del session['notifications'] except KeyError: # No stored notifications - create a new NotificationList self._notifications = NotificationList() else: self._notifications = NotificationList() return self._notifications
def _authenticateUsingCookieAuth(self, request): session = ISession(request) authdata = session['launchpad.authenticateduser'] id = authdata.get('accountid') if id is None: # XXX: salgado, 2009-02-17: This is for backwards compatibility, # when we used to store the person's ID in the session. person_id = authdata.get('personid') if person_id is not None: person = getUtility(IPersonSet).get(person_id) if person is not None and person.accountID is not None: id = person.accountID if id is None: return None login_src = getUtility(IPlacelessLoginSource) principal = login_src.getPrincipal(id) # Note, not notifying a LoggedInEvent here as for session-based # auth the login occurs when the login form is submitted, not # on each request. if principal is None: # XXX Stuart Bishop 2006-05-26 bug=33427: # User is authenticated in session, but principal is not" # available in login source. This happens when account has # become invalid for some reason, such as being merged. return None elif principal.person.is_valid_person: login = authdata['login'] assert login, 'login is %s!' % repr(login) notify( CookieAuthPrincipalIdentifiedEvent(principal, request, login)) return principal else: return None
def setCredentials(self, request, username, password): # avoid circular imports from schooltool.person.person import hash_password if not self._checkPlainTextPassword(username, password): raise ValueError('bad credentials') session = ISession(request)[self.session_name] session['username'] = username session['password'] = hash_password(password)
def update(self, code=None, state=None, **args): ''' Either code or error is defined here if this is in response to Authorization ''' super(V2TokenView, self).update(**args) oauth = self.context.__parent__.__parent__ self.context.__parent__.__parent__.error_msg = None if self.error is None: if code is not None: token = self.context.__parent__ if token.state == state: self.context.code = code data = urlencode(self.context.parms) print "----------------------------------------------------" print "url=[%s]; data=[%s]" % (self.context.uri, data) req = Request(self.context.uri) req.add_header( 'User-Agent', 'Python urlib2 (grok.zopefoundation.org, Python 2.7)') req.add_header('Content-Type', 'application/x-www-form-urlencoded') req.add_header('Accept', 'application/json') req.add_data(data) try: res = urlopen(req).read() # should be doing a post self.context.info = json.loads(res) try: # Update session information with auth info session = ISession(self.request)['OAuth2'] session['info'] = self.context.info service = self.context.__parent__.service principal = component.queryAdapter(self.context, IOAuthPrincipal, name=service) session[ 'principal'] = principal if principal else None # If we get here, we can notify subscribers. grok.notify( OAuthenticatedEvent(session['principal'])) self.redirect(self.url(grok.getApplication())) except Exception as e: print "Problem in adapter for service: {}".format( str(e)) self.error = str(e) except HTTPError as e: print "Error while exchanging tokens: {}".format( str(e)) self.error = str(e) else: self.error = 'State Mismatch' else: self.error = 'Invalid code' if type(self.error) is str and len(self.error): print "-------------------------------------------------" print "Error [%s] in token exchange" % self.error oauth.error_msg = self._render_template() self.redirect(self.url(grok.getApplication()))
def authenticateCredentials(self, credentials): USER_SESSION_KEY = "adhoc.authentication" request = uvcsite.getRequest() session = ISession(request)['adhoc.authentication'] authenticated = session.get(USER_SESSION_KEY) if authenticated is None: if not isinstance(credentials, dict): return account = self.getAccount(credentials["login"]) if account is None: return None if not account.checkPassword( credentials["password"], credentials.get("gebdate", '99.99.9999')): return None else: authenticated = session[USER_SESSION_KEY] = dict(id=account.az) return PrincipalInfo(**authenticated)
def getSession(self): """Get the session data container that stores the OpenID request.""" if IUnauthenticatedPrincipal.providedBy(self.request.principal): # A dance to assert that we want to break the rules about no # unauthenticated sessions. Only after this next line is it # safe to set session values. allowUnauthenticatedSession(self.request, duration=timedelta(minutes=60)) return ISession(self.request)[SESSION_PKG_KEY]
def isFreshLogin(request): """Return True if the principal login happened in the last 120 seconds.""" session = ISession(request) authdata = session['launchpad.authenticateduser'] logintime = authdata.get('logintime', None) if logintime is not None: now = datetime.utcnow() return logintime > now - timedelta(seconds=120) return False
def handle_book_action(self, action, data): sessionWrapper = ISession(self.request) session = sessionWrapper['schooltool.resource'] session['bookingSelection'] = [ ''.join(key.split('.')[1:]) for key in self.request if key.startswith('delete.') ] url = absoluteURL(IBookingCalendar(self.context), self.request) return self.request.response.redirect(url)
def processPositiveAssertion(self): """Process an OpenID response containing a positive assertion. We'll get the person and account with the given OpenID identifier (creating one if necessary), and then login using that account. If the account is suspended, we stop and render an error page. We also update the 'last_write' key in the session if we've done any DB writes, to ensure subsequent requests use the master DB and see the changes we just did. """ identifier = self.openid_response.identity_url.split('/')[-1] identifier = identifier.decode('ascii') should_update_last_write = False # Force the use of the master database to make sure a lagged slave # doesn't fool us into creating a Person/Account when one already # exists. person_set = getUtility(IPersonSet) email_address, full_name = self._getEmailAddressAndFullName() try: person, db_updated = person_set.getOrCreateByOpenIDIdentifier( identifier, email_address, full_name, comment='when logging in to Launchpad.', creation_rationale=( PersonCreationRationale.OWNER_CREATED_LAUNCHPAD)) should_update_last_write = db_updated except AccountSuspendedError: return self.suspended_account_template() except TeamEmailAddressError: return self.team_email_address_template() if self.params.get('discharge_macaroon_field'): if self.macaroon_response.discharge_macaroon_raw is None: raise HTTPBadRequest( "OP didn't include a macaroon extension in the response.") self.discharge_macaroon_raw = ( self.macaroon_response.discharge_macaroon_raw) with MasterDatabasePolicy(): self.login(person) if self.params.get('discharge_macaroon_field'): return self.discharge_macaroon_template() if should_update_last_write: # This is a GET request but we changed the database, so update # session_data['last_write'] to make sure further requests use # the master DB and thus see the changes we've just made. session_data = ISession(self.request)['lp.dbpolicy'] session_data['last_write'] = datetime.utcnow() self._redirect() # No need to return anything as we redirect above. return None
def handleCancel(self, action): """cancel was pressed""" session = ISession(self.request)[self._session_key] try: del session['state'] except KeyError: pass url = absoluteURL(self.context, self.request) self.request.response.redirect(url)
def __call__(self, *args, **kw): self.data = ISession(self.request)[SESSION_KEY] if not self.data.get('reqregister', False): self.redirect( u'%s/successOpenIdSignIn?processed=1'%absoluteURL( self.context, self.request)) return u'' return super(CompleteOpenIdSignIn, self).__call__(*args, **kw)
def authenticateCredentials(self, credentials): """ Check if username and password match get the credentials from the IUserManagement Utility """ request = zope.security.management.getInteraction().participations[0] session = ISession(request)['uvcsite.authentication'] authenticated = session.get(USER_SESSION_KEY) if authenticated is None: if not (credentials and 'login' in credentials and 'password' in credentials): return login, password = credentials['login'], credentials['password'] utility = getUtility(IUserManagement) if hasattr(utility, 'changeLogin'): login = utility.changeLogin(login) if not utility.checkRule(login): return if '@' in login: user = utility.getUserByEMail(login) else: user = utility.getUser(login) if not user: return if hasattr(utility, 'checkPW'): if not utility.checkPW(password, user.get('passwort')): return else: if password != user.get('passwort'): return user_id = user['mnr'] if user['az'] != '00': user_id = "%s-%s" % (user['mnr'], user['az']) authenticated = session[USER_SESSION_KEY] = dict( id=user_id, title=login, description=login, login=login) return PrincipalInfo(**authenticated)
def logout(self, request): """Performs logout by clearing session data credentials.""" if not IHTTPRequest.providedBy(request): return False sessionData = ISession( request)['zope.app.authentication.browserplugins'] sessionData['credentials'] = None transaction.commit() return True
def authenticateCredentials(self, credentials): """ Check if username and password match get the credentials from the IUserManagement Utility """ request = zope.security.management.getInteraction().participations[0] session = ISession(request)['uvcsite.authentication'] authenticated = session.get(USER_SESSION_KEY) if authenticated is None: if not (credentials and 'login' in credentials and 'password' in credentials): return login, password = credentials['login'], credentials['password'] utility = getUtility(IUserManagement) if hasattr(utility, 'changeLogin'): login = utility.changeLogin(login) if not utility.checkRule(login): return if '@' in login: user = utility.getUserByEMail(login) else: user = utility.getUser(login) if not user: return if hasattr(utility, 'checkPW'): if not utility.checkPW(password, user.get('passwort')): return else: if password != user.get('passwort'): return user_id = user['mnr'] if user['az'] != '00': user_id = "%s-%s" % (user['mnr'], user['az']) authenticated = session[USER_SESSION_KEY] = dict(id=user_id, title=login, description=login, login=login) return PrincipalInfo(**authenticated)
def do_login(self, **data): login = Login() self.applyData(login, **data) principals = IOAuthPrincipalSource(grok.getApplication()) account = principals.find(login=login.login, domain=principals.domain) if account: # check password, and authenticate if match from zope.password.password import SSHAPasswordManager mgr = SSHAPasswordManager() if mgr.checkPassword(account.secret, login.secret): session = ISession(self.request)['OAuth2'] session['principal'] = account # Found the principal
def __init__(self, sequence, start=0, size=20, batches=None, context=None, request=None, prefix='', queryparams={}): self.context = context self.request = request self.prefix = prefix if request is not None: rkey = self.prefix + 'bstart' if context is None: key = rkey else: key = '%s:%s'%(getPath(context), rkey) if rkey in request: try: rstart = int(request.get(rkey, start)) data = ISession(request)[SESSIONKEY] data[key] = rstart start = rstart except: pass else: data = ISession(request)[SESSIONKEY] start = data.get(key, start) if start >= len(sequence): start = 0 super(SessionBatch, self).__init__(sequence, start, size, batches) if batches is None: self.batches = Batches(self) self.queryparams = queryparams
def get(self): session = ISession(self.request)[SESSION_KEY] return session.get('selectedContact')
def getCredentials(request): session = ISession(request) sessionData = session.get('zope.pluggableauth.browserplugins') if not sessionData: return None return sessionData.get('credentials')
def getContent(self): session = ISession(self.request)[PersonWizard.sessionKey] return session.get('content')
def getContent(self): session = ISession(self.request)[self.sessionKey] obj = session.get('content') if obj is None: obj = session['content'] = content.Person() return obj
def __get__(self, inst, klass): session = ISession(inst.request)[SESSION_KEY] return session.get(self.name, self.default)
def update(self): name = self.name request = self.request context = self.form.context self.auth = getUtility(IAuthentication) key = u'%s:%s'%(getPath(context), name) self.sessionKey = key self.selectedName = u'%s-selectedItem'%name super(BasePrincipalWidget, self).update() tp = [] if IUserField.providedBy(self.field): tp = ('user',) elif IGroupField.providedBy(self.field): tp = ('group',) else: tp = ('user', 'group') # search text data = ISession(request)[SESSIONKEY] if '%s-empty-marker'%name not in request and key in data: del data[key] if u'%s.searchButton'%name in request: searching = True searchtext = request.get(u'%s.searchText'%name, u'') data[key] = (searchtext, True) if searchtext: try: principals = searchPrincipals( tp, searchableText = searchtext) except: principals = [] else: principals = [] elif u'%s.searchClear'%name in request: if key in data: del data[key] searchtext = u'' searching = False principals = searchPrincipals(tp) else: searchtext, searching = data.get(key, (u'', False)) if searchtext: try: principals = searchPrincipals( tp, searchableText = searchtext) except: principals = [] else: principals = searchPrincipals(tp) self.searching = searching self.searchtext = searchtext self.principals = SessionBatch( principals, size=self.pageSize, context=context, request=request, prefix=name, queryparams = {'%s-empty-marker'%self.name: '1'})
class CompleteOpenIdSignIn(PageletForm): interface.implements(IPrincipalPasswordForm, IMailAuthorizationAware) label = _("Register new user") ignoreContext = True fields = Fields(IRegistrationForm, IPrincipalPasswordForm) registeredPrincipal = None def update(self): self.registration = getUtility(IPortalRegistration) super(CompleteOpenIdSignIn, self).update() request = self.request self.portalURL = u'%s/'%absoluteURL(self.context, request) self.loginURL = u'%s@@completeOpenIdSignIn'%self.portalURL if 'form.zojax-auth-login' in request: principal = request.principal if IUnauthenticatedPrincipal.providedBy(principal): IStatusMessage(request).add(_('Login failed.'), 'warning') else: principal = IPrincipal(principal) principal.identifiers = \ principal.identifiers + (self.data['identifier'],) del self.data['reqregister'] del self.data['identifier'] IStatusMessage(request).add(_('You successfully logged in.')) self.redirect('./') @button.buttonAndHandler(_(u"Register"), provides=IMemberRegisterAction) def handle_register(self, action): request = self.request data, errors = self.extractData() if errors: IStatusMessage(request).add(self.formErrorsMessage, 'error') return plugin = queryUtility(IUsersPlugin) login = data['login'].lower() # create principal principal = Principal(login, data['firstname'], data['lastname'], '') # set password passwordtool = getUtility(IPasswordTool) principal.password = passwordtool.encodePassword(data['password']) event.notify(ObjectCreatedEvent(principal)) # save principal to folder name = INameChooser(plugin).chooseName('', principal) plugin[name] = principal # register principal in registration tool auth = getUtility(IAuthentication) authprincipal = auth.getPrincipal(auth.prefix + plugin.prefix + name) status = self.registration.registerPrincipal(authprincipal, request) if status == STATUS_CONTINUE: updateCredentials(request, login, data['password']) principal.identifiers = \ principal.identifiers + (self.data['identifier'],) del self.data['reqregister'] del self.data['identifier'] IStatusMessage(request).add( _('You have been successfully registered.')) self.redirect(absoluteURL(getSite(), request)) # IMemberRegistrationForm attribute self.registeredPrincipal = authprincipal def __call__(self, *args, **kw): self.data = ISession(self.request)[SESSION_KEY] if not self.data.get('reqregister', False): self.redirect( u'%s/successOpenIdSignIn?processed=1'%absoluteURL( self.context, self.request)) return u'' return super(CompleteOpenIdSignIn, self).__call__(*args, **kw)