set_session

store the session id, and the CAS session ticket in Redis, for
single sign off.

uses the 'req' object to pull out the st and sessionid, and also to
determine the maxage set for the session
979339
function set_session(req,cb){

    // ttl stuff borrowed & modified from  visionmedia / connect-redis.js  source code
    // Copyright(c) 2012 TJ Holowaychuk <tj@vision-media.ca>  MIT Licensed

    try {
        var maxAge = req.session.cookie.maxAge
        var ttl = _ttl || ('number' == typeof maxAge
                          ? maxAge / 1000 | 0
                          : oneDay)
        redclient.setex(req.session.st, ttl, req.sessionID, function(err){
            if(!err){
                 logger.debug('SETEX session ticket, max age ' + ttl);
            }
            cb && cb(err)
        })
    } catch (err) {
        logger.error('saving session ticket to Redis threw an error')
        //throw new Error(err)
        cb && cb(err);
    }
}
306033
def session_rollback(self, session):
        
        # this may happen when there's nothing to rollback
        if not hasattr(session, 'meepo_unique_id'):
            self.logger.debug("skipped - session_rollback")
            return

        # del session meepo id after rollback
        self.logger.debug("%s - after_rollback" % session.meepo_unique_id)
        signal("session_rollback").send(session)
        self._session_del(session)
1252016
def init_get(self, request):
        
        self.request = request
        self.service = request.GET.get('service')
        self.renew = bool(request.GET.get('renew') and request.GET['renew'] != "False")
        self.gateway = request.GET.get('gateway')
        self.method = request.GET.get('method')
        self.ajax = settings.CAS_ENABLE_AJAX_AUTH and 'HTTP_X_AJAX' in request.META
        self.warn = request.GET.get('warn')
        if settings.CAS_FEDERATE:
            # here username and ticket are fetch from the session after a redirection from
            # FederateAuth.get
            self.username = request.session.get("federate_username")
            self.ticket = request.session.get("federate_ticket")
            if self.username:
                del request.session["federate_username"]
            if self.ticket:
                del request.session["federate_ticket"]
1301958
def logout(session_ids=Hash.new)
      result = SfBase.connection.binding.invalidateSessions(session_ids)
      if"invalidateSessionsResponse" == result.to_s
        return true
      else
        return false
      end
      #result this.connection.binding.logout(Hash.new)
    end
801044
def redis(self):
        
        redis_url = current_app.config.get("SSE_REDIS_URL")
        if not redis_url:
            redis_url = current_app.config.get("REDIS_URL")
        if not redis_url:
            raise KeyError("Must set a redis connection URL in app config.")
        return StrictRedis.from_url(redis_url)
616876
def _retry_with_session(self, retryable, func, session, bulk):
        
        retryable = (retryable and self.retry_writes
                     and session and not session._in_transaction)
        last_error = None
        retrying = False

        def is_retrying():
            return bulk.retrying if bulk else retrying
        # Increment the transaction id up front to ensure any retry attempt
        # will use the proper txnNumber, even if server or socket selection
        # fails before the command can be sent.
        if retryable:
            session._start_retryable_write()
            if bulk:
                bulk.started_retryable_write = True

        while True:
            try:
                server = self._select_server(writable_server_selector, session)
                supports_session = (
                    session is not None and
                    server.description.retryable_writes_supported)
                with self._get_socket(server, session) as sock_info:
                    if retryable and not supports_session:
                        if is_retrying():
                            # A retry is not possible because this server does
                            # not support sessions raise the last error.
                            raise last_error
                        retryable = False
                    return func(session, sock_info, retryable)
            except ServerSelectionTimeoutError:
                if is_retrying():
                    # The application may think the write was never attempted
                    # if we raise ServerSelectionTimeoutError on the retry
                    # attempt. Raise the original exception instead.
                    raise last_error
                # A ServerSelectionTimeoutError error indicates that there may
                # be a persistent outage. Attempting to retry in this case will
                # most likely be a waste of time.
                raise
            except ConnectionFailure as exc:
                if not retryable or is_retrying():
                    raise
                if bulk:
                    bulk.retrying = True
                else:
                    retrying = True
                last_error = exc
            except BulkWriteError as exc:
                if not retryable or is_retrying():
                    raise
                # Check the last writeConcernError to determine if this
                # BulkWriteError is retryable.
                wces = exc.details['writeConcernErrors']
                wce = wces[-1] if wces else {}
                if wce.get('code', 0) not in helpers._RETRYABLE_ERROR_CODES:
                    raise
                if bulk:
                    bulk.retrying = True
                else:
                    retrying = True
                last_error = exc
            except OperationFailure as exc:
                if not retryable or is_retrying():
                    raise
                if exc.code not in helpers._RETRYABLE_ERROR_CODES:
                    raise
                if bulk:
                    bulk.retrying = True
                else:
                    retrying = True
                last_error = exc
371126
def save_session(self, sid, session, namespace=None):
        
        return self.server.save_session(
            sid, session, namespace=namespace or self.namespace)
1283698
def set_autosession(self, value=None):
        
        if value is not None:
            self.rollback()
            self.autosession = value
        return self.autosession
878678
def do_get_session(self, session_key):
        
        session_id = session_key.session_id
        msg = ("do_get_session: Attempting to retrieve session with key " +
               str(session_id))
        logger.debug(msg)

        session = self._retrieve_session(session_key)

        if (session is not None):
            self.validate(session, session_key)

        return session
332813
def set_(key, value, profile=None):
    '''
    
    '''
    if not profile:
        return False
    redis_kwargs = profile.copy()
    redis_kwargs.pop('driver')
    redis_conn = redis.StrictRedis(**redis_kwargs)
    return redis_conn.set(key, value)
1105843
function shouldSave(req) {
      // cannot set cookie without a session ID
      if (typeof req.sessionID !== 'string') {
        debug('session ignored because of bogus req.sessionID %o', req.sessionID);
        return false;
      }

      return !saveUninitializedSession && cookieId !== req.sessionID
        ? isModified(req.session)
        : !isSaved(req.session)
    }
1246772
def _internal_verify_cas(ticket, service, suffix):
    

    params = {'ticket': ticket, 'service': service}
    if settings.CAS_PROXY_CALLBACK:
        params['pgtUrl'] = settings.CAS_PROXY_CALLBACK

    url = (urljoin(settings.CAS_SERVER_URL, suffix) + '?' +
           urlencode(params))

    page = urlopen(url)

    username = None

    try:
        response = page.read()
        tree = ElementTree.fromstring(response)
        document = minidom.parseString(response)

        if tree[0].tag.endswith('authenticationSuccess'):
            if settings.CAS_RESPONSE_CALLBACKS:
                cas_response_callbacks(tree)

            username = tree[0][0].text

            pgt_el = document.getElementsByTagName('cas:proxyGrantingTicket')

            if pgt_el:
                pgt = pgt_el[0].firstChild.nodeValue
                try:
                    pgtIou = _get_pgtiou(pgt)
                    tgt = Tgt.objects.get(username=username)
                    tgt.tgt = pgtIou.tgt
                    tgt.save()
                    pgtIou.delete()
                except Tgt.DoesNotExist:
                    Tgt.objects.create(username=username, tgt=pgtIou.tgt)
                    logger.info('Creating TGT ticket for {user}'.format(
                        user=username
                    ))
                    pgtIou.delete()
                except Exception as e:
                    logger.warning('Failed to do proxy authentication. {message}'.format(
                        message=e
                    ))

        else:
            failure = document.getElementsByTagName('cas:authenticationFailure')
            if failure:
                logger.warn('Authentication failed from CAS server: %s',
                            failure[0].firstChild.nodeValue)

    except Exception as e:
        logger.error('Failed to verify CAS authentication: {message}'.format(
            message=e
        ))

    finally:
        page.close()

    return username
1114935
function SessionManager(config) {
      this.start = __bind(this.start, this);
      this.storeKey = __bind(this.storeKey, this);
      this.config = extend(this.defaults.config, config);
      this.RedisClient = redis.createClient(config.redis.port, config.redis.host, config.redis);
    }
243794
def clear_session_value(self, name):
        """"""
        self.redis().hdel(self._session_key, name)
        self._update_session_expiration()
799574
def set_session_persistence(self, loadbalancer, val):
        
        val = val.upper()
        uri = "/loadbalancers/%s/sessionpersistence" % utils.get_id(loadbalancer)
        req_body = {"sessionPersistence": {
                "persistenceType": val,
                }}
        resp, body = self.api.method_put(uri, body=req_body)
        return body
727340
def get(self, request, provider=None):
        
        # if settings.CAS_FEDERATE is not True redirect to the login page
        if not settings.CAS_FEDERATE:
            logger.warning("CAS_FEDERATE is False, set it to True to use federation")
            return redirect("cas_server:login")
        renew = bool(request.GET.get('renew') and request.GET['renew'] != "False")
        # Is the user is already authenticated, no need to request authentication to the user
        # identity provider.
        if self.request.session.get("authenticated") and not renew:
            logger.warning("User already authenticated, dropping federated authentication request")
            return redirect("cas_server:login")
        try:
            # get the identity provider from its suffix
            provider = FederatedIendityProvider.objects.get(suffix=provider)
            # get a CAS client for the user identity provider
            auth = self.get_cas_client(request, provider, renew)
            # if no ticket submited, redirect to the identity provider CAS login page
            if 'ticket' not in request.GET:
                logger.info("Trying to authenticate %s again" % auth.provider.server_url)
                return HttpResponseRedirect(auth.get_login_url())
            else:
                ticket = request.GET['ticket']
                try:
                    # if the ticket validation succeed
                    if auth.verify_ticket(ticket):
                        logger.info(
                            "Got a valid ticket for %s from %s" % (
                                auth.username,
                                auth.provider.server_url
                            )
                        )
                        params = utils.copy_params(request.GET, ignore={"ticket", "remember"})
                        request.session["federate_username"] = auth.federated_username
                        request.session["federate_ticket"] = ticket
                        auth.register_slo(
                            auth.federated_username,
                            request.session.session_key,
                            ticket
                        )
                        # redirect to the the login page for the user to become authenticated
                        # thanks to the `federate_username` and `federate_ticket` session parameters
                        url = utils.reverse_params("cas_server:login", params)
                        response = HttpResponseRedirect(url)
                        # If the user has checked "remember my identity provider" store it in a
                        # cookie
                        if request.GET.get("remember"):
                            max_age = settings.CAS_FEDERATE_REMEMBER_TIMEOUT
                            utils.set_cookie(
                                response,
                                "remember_provider",
                                provider.suffix,
                                max_age
                            )
                        return response
                    # else redirect to the identity provider CAS login page
                    else:
                        logger.info(
                            (
                                "Got an invalid ticket %s from %s for service %s. "
                                "Retrying authentication"
                            ) % (
                                ticket,
                                auth.provider.server_url,
                                self.service_url
                            )
                        )
                        return HttpResponseRedirect(auth.get_login_url())
                # both xml.etree.ElementTree and lxml.etree exceptions inherit from SyntaxError
                except SyntaxError as error:
                    messages.add_message(
                        request,
                        messages.ERROR,
                        _(
                            u"Invalid response from your identity provider CAS upon "
                            u"ticket %(ticket)s validation: %(error)r"
                        ) % {'ticket': ticket, 'error': error}
                    )
                    response = redirect("cas_server:login")
                    response.delete_cookie("remember_provider")
                    return response
        except FederatedIendityProvider.DoesNotExist:
            logger.warning("Identity provider suffix %s not found" % provider)
            # if the identity provider is not found, redirect to the login page
            return redirect("cas_server:login")
1344765
def set_current_session(session_id) -> bool:
        
        try:
            g.session_id = session_id
            return True
        except (Exception, BaseException) as error:
            # catch all on config update
            if current_app.config['DEBUG']:
                print(error)
            return False