/*
process_login

Called by todo.login_user. Creates a cookie with the session_token we got back from CloudMine
and calls for this user's data for their to-do list.
Parameter:
response: response data from the server, passed in by todo.login_user
12888
function(response){
      if(window.localStorage){
        var save = JSON.stringify({token: response.session_token});
        localStorage.setItem('cloudmineTodoSession', save);
      }
      else {
        document.cookie = 'cloudmineTodoSession=' + response.session_token + '; expires=' + response.expires + '; path=/';
      }
      todo.get_items();
    }
1159144
function (login_id, session, data) {

	// acknowledge as 'logined'	
	l_loginID[login_id] = data.account;
	
	// init session
	session['_account'] = data.account;
	
	// TODO: needs to fix this, should read "groups" from DB
	session['_groups'] = data.groups;
	session['_permissions'] = data.permissions;
	session['lastStatus'] = data.lastStatus;
	
	// TODO: centralize handling of logined users?
	//SR.User.addGroup(user_data.account, ['user', 'admin']);
}
1349810
def _process_response(self, response: Response):
        ''''''
        _logger.debug('Handling response')

        self._redirect_tracker.load(response)

        if self._redirect_tracker.is_redirect():
            self._process_redirect()
            self._loop_type = LoopType.redirect
        elif response.status_code == http.client.UNAUTHORIZED and self._next_request.password:
            self._process_authentication(response)
        else:
            self._next_request = None
            self._loop_type = LoopType.normal

        if self._cookie_jar:
            self._extract_cookies(response)

            if self._next_request:
                self._add_cookies(self._next_request)
467912
def login(user, password)
      @user = user
      @password = password

      response = call_remote(:login, [:username, user, :password, password])

      raise "Incorrect user name / password [#{response.fault}]" unless response.loginResponse

      result = response[:loginResponse][:result]
      @session_id = result[:sessionId]

      init_server(result[:serverUrl])

      response
    end
1116007
function writeCookie (response, cookiePath) {
  try {
    debug('got response')
    var cookies = cookie.parse(response.headers['set-cookie'][0])
    debug('connect.sid', cookies['connect.sid'])
    fs.writeFileSync(cookiePath, JSON.stringify(cookies))
  } catch (e) {
    debug(e)
  }
}
663433
function(){
    if(window.localStorage){
      var saved = localStorage['cloudmineTodoSession'];
      if(!saved)
        return null;
      var prefs = JSON.parse(saved);
      return prefs.token;
    } else {
      var cookies = document.cookie.split(';');
      for (var i in cookies){
        var cookie = cookies[i].split('=');
        if (cookie[0] == 'cloudmineTodoSession' && cookie[1] != 'none'){
          $('#login').hide();
          $('#restoring_session').show();
          return cookie[1];
        }
      }
    }
    return null;
  }
353706
def login(self, user, passwd):
        
        def do_login(self, user, passwd, token=None):
            """
            Login function that handles CSRF protection (see `MediaWiki bug
            23076`_). Returns ``True`` on successful login.

            .. _`MediaWiki bug 23076`:
                https://bugzilla.wikimedia.org/show_bug.cgi?id=23076
            """
            data = {'action': 'login',
                    'lgname': user,
                    'lgpassword': passwd}
            if token:
                data['lgtoken'] = token
            result = self.call(data)
            if result['login']['result'] == 'Success':
                self._high_limits = None
                return True
            elif result['login']['result'] == 'NeedToken' and not token:
                return do_login(self, user, passwd, result['login']['token'])
            else:
                return False

        return do_login(self, user, passwd)
1168149
def process_response(self, req, resp, resource):
        
        if 'result' not in req.context:
            return
        req.context['result']['is_login'] = 'user_id' in req.env['session']
        if settings.DEBUG:
            req.context['result']['_debug_queries'] = sys._debug_db_queries
            sys._debug_db_queries = []
        if resp.body is None and req.context['result']:
            resp.body = json.dumps(req.context['result'])

        try:
            log.debug("RESPONSE: %s" % resp.body)
        except:
            log.exception("ERR: RESPONSE CANT BE LOGGED ")
1058884
def session(user, password)
      fname = File.join(ENV['HOME'], '.ruby-bugzilla-cookie.yml')
      if File.exist?(fname) && File.lstat(fname).mode & 0600 == 0600 then
        conf = YAML.load(File.open(fname).read)
        host = @iface.instance_variable_get(:@xmlrpc).instance_variable_get(:@host)
        cookie = conf[host]
        unless cookie.nil? then
          @iface.cookie = cookie
          print "Using cookie\n"
          yield
          conf[host] = @iface.cookie
          File.open(fname, 'w') {|f| f.chmod(0600); f.write(conf.to_yaml)}
          return
        end
      end
      if user.nil? || password.nil? then
        yield
      else
        login({'login'=>user, 'password'=>password, 'remember'=>true})
        yield
        logout
      end
      
    end
138621
def login(self):
        
        resp = super(CookieSession, self).request(
            'POST',
            self._session_url,
            data={'name': self._username, 'password': self._password},
        )
        resp.raise_for_status()
806957
def cr_login(self, response):
        
        self._state_params['auth'] = response['auth']
        self._user_data = response['user']
        if not self.logged_in:
            raise ApiLoginFailure(response)
972829
def login(options)
      out = nil
      post('/auth/login', options) do |resp|
        @access_token = resp.body['auth_token']
        out = Cryptoprocessing::User.new self, resp.data
        yield(resp) if block_given?
      end
      out
    end
923266
async def process_response(
        self,
        response: Response,
        request_context: Optional[RequestContext]=None,
    ) -> Response:
        
        request_ = (request_context or _request_ctx_stack.top).request
        functions = (request_context or _request_ctx_stack.top)._after_request_functions
        blueprint = request_.blueprint
        if blueprint is not None:
            functions = chain(functions, self.after_request_funcs[blueprint])
        functions = chain(functions, self.after_request_funcs[None])

        for function in functions:
            response = await function(response)

        session_ = (request_context or _request_ctx_stack.top).session
        if not self.session_interface.is_null_session(session_):
            await self.save_session(session_, response)
        return response
1100169
def process_request(self, request=None, cookie=None, **kwargs):
        
        _cntx = self.endpoint_context
        _sdb = _cntx.sdb

        if 'post_logout_redirect_uri' in request:
            if 'id_token_hint' not in request:
                raise InvalidRequest(
                    "If post_logout_redirect_uri then id_token_hint is a MUST")
        _cookie_name = self.endpoint_context.cookie_name['session']
        try:
            part = self.endpoint_context.cookie_dealer.get_cookie_value(
                cookie, cookie_name=_cookie_name)
        except IndexError:
            raise InvalidRequest('Cookie error')
        except KeyError:
            part = None

        if part:
            # value is a base64 encoded JSON document
            _cookie_info = json.loads(as_unicode(b64d(as_bytes(part[0]))))
            logger.debug('Cookie info: {}'.format(_cookie_info))
            _sid = _cookie_info['sid']
        else:
            logger.debug('No relevant cookie')
            _sid = ''
            _cookie_info = {}

        if 'id_token_hint' in request:
            logger.debug(
                'ID token hint: {}'.format(
                    request[verified_claim_name("id_token_hint")]))

            auds = request[verified_claim_name("id_token_hint")]['aud']
            _ith_sid = ''
            _sids = _sdb.sso_db.get_sids_by_sub(
                request[verified_claim_name("id_token_hint")]['sub'])

            if _sids is None:
                raise ValueError('Unknown subject identifier')

            for _isid in _sids:
                if _sdb[_isid]['authn_req']['client_id'] in auds:
                    _ith_sid = _isid
                    break

            if not _ith_sid:
                raise ValueError('Unknown subject')

            if _sid:
                if _ith_sid != _sid:  # someone's messing with me
                    raise ValueError('Wrong ID Token hint')
            else:
                _sid = _ith_sid
        else:
            auds = []

        try:
            session = _sdb[_sid]
        except KeyError:
            raise ValueError("Can't find any corresponding session")

        client_id = session['authn_req']['client_id']
        # Does this match what's in the cookie ?
        if _cookie_info:
            if client_id != _cookie_info['client_id']:
                logger.warning(
                    'Client ID in authz request and in cookie does not match')
                raise ValueError("Wrong Client")

        if auds:
            if client_id not in auds:
                raise ValueError('Incorrect ID Token hint')

        _cinfo = _cntx.cdb[client_id]

        # verify that the post_logout_redirect_uri if present are among the ones
        # registered

        try:
            _uri = request['post_logout_redirect_uri']
        except KeyError:
            if _cntx.issuer.endswith('/'):
                _uri = "{}{}".format(_cntx.issuer,
                                     self.kwargs['post_logout_uri_path'])
            else:
                _uri = "{}/{}".format(_cntx.issuer,
                                      self.kwargs['post_logout_uri_path'])
            plur = False
        else:
            plur = True
            verify_uri(_cntx, request, 'post_logout_redirect_uri',
                       client_id=client_id)

        payload = {
            'sid': _sid, 'client_id': client_id,
            'user': session['authn_event']['uid']
        }

        # redirect user to OP logout verification page
        if plur and 'state' in request:
            _uri = '{}?{}'.format(_uri, urlencode({'state': request['state']}))
            payload['state'] = request['state']

        payload['redirect_uri'] = _uri

        logger.debug('JWS payload: {}'.format(payload))
        # From me to me
        _jws = JWT(_cntx.keyjar, iss=_cntx.issuer, lifetime=86400,
                   sign_alg=self.kwargs['signing_alg'])
        sjwt = _jws.pack(payload=payload, recv=_cntx.issuer)

        location = '{}?{}'.format(self.kwargs['logout_verify_url'],
                                  urlencode({'sjwt': sjwt}))
        return {'redirect_location': location}
244521
@POST
    @Produces(MediaType.APPLICATION_JSON)
    @Consumes(MediaType.APPLICATION_JSON)
    @Description("Authenticates a user principal.")
    @Path("/login")
    public Response login(@Context UriInfo uriInfo, final CredentialsDto creds) {
    	Response response = Response.temporaryRedirect(UriBuilder.fromUri(uriInfo.getBaseUri() + "v2/auth/login").build()).build();
    	return response;
    }
904637
function handleLogin(user, req, res, next) {


    var token;
    var profile;
    var tokenExpiresInMinutes;
    var envelope = {
      data: user,
      isAuthenticated: true,
      meta: {}
    };

    // First handle the case where the user was not logged in.
    if (!user) {
      if (authConfig.maintenance === 'cookie') {
        req.logout();
      }
      return res.status(401).send('Wrong password or no such user.');
    }
    // user_id is how it is in the schema
    /* jshint ignore:start */
    // Now handle the case where we did get a user record.
    if (authConfig.maintenance === 'token') {
      // For token authentication we want to add a token.
      profile = {
        username: user.username,
        email: user.email,
        userdata_id: user.userdata_id
      };
      /* jshint ignore:end */
      tokenExpiresInMinutes = authConfig.expiresInMinutes || 60;
      envelope.meta.token = generateToken(profile, tokenExpiresInMinutes,
        secrets.authTokenSecret);

      envelope.meta.expires = getExpirationTime(tokenExpiresInMinutes);
      return res.status(200).send(envelope);
    } else if (authConfig.maintenance === 'cookie') {
      // For cookie authentication we want to login the user.
      req.login(user, function (err) {
        if (err) {
          return next(err);
        } else {
          return res.status(200).send(envelope);
        }
      });
    }
  }
1289130
def login_with_oauth
      result = @server.post @oauth[:login_url], '', {}

      case result
      when Net::HTTPSuccess
        doc = REXML::Document.new result.body
        @session_id = doc.elements['*/sessionId'].text
        server_url  = doc.elements['*/serverUrl'].text
        init_server server_url

        return {:sessionId => @sessionId, :serverUrl => server_url}
      when Net::HTTPUnauthorized
        raise 'Invalid OAuth tokens'
      else
        raise 'Unexpected error: #{response.inspect}'
      end
    end