Verify Keystone Auth URL
18873
def is_url_ok(self):
        

        response = requests.head(settings.KEYSTONE_AUTH_URL)
        if response.status_code == 200:
            return True
        return False
590126
def get_keystone_endpoint(self, keystone_ip, api_version=None,
                              admin_port=False):
        """"""
        port = 5000
        if admin_port:
            port = 35357
        base_ep = "http://{}:{}".format(keystone_ip.strip().decode('utf-8'),
                                        port)
        if api_version == 2:
            ep = base_ep + "/v2.0"
        else:
            ep = base_ep + "/v3"
        return ep
38041
def verify_keys(self):
        """"""
        verify_keys_endpoint = Template("${rest_root}/site/${public_key}")
        url = verify_keys_endpoint.substitute(rest_root=self._rest_root, public_key=self._public_key)
        
        data = { "clientName": "mollom_python", "clientVersion": "1.0" }

        self._client.headers["Content-Type"] = "application/x-www-form-urlencoded"

        response = self._client.post(url, data, timeout=self._timeout)
        if response.status_code != 200:
            raise MollomAuthenticationError

        return True
986186
def init_api(self, instance_config, custom_tags):
        
        custom_tags = custom_tags or []
        keystone_server_url = instance_config.get("keystone_server_url")
        proxy_config = self.get_instance_proxy(instance_config, keystone_server_url)

        if self._api is None:
            # We are missing the entire instance scope either because it is the first time we initialize it or because
            # authentication previously failed and got removed from the cache
            # Let's populate it now
            try:
                self.log.debug("Fetch scope for instance {}".format(self.instance_name))
                # Set keystone api with proper token
                self._api = ApiFactory.create(self.log, proxy_config, instance_config)
                self.service_check(
                    self.IDENTITY_API_SC,
                    AgentCheck.OK,
                    tags=["keystone_server: {}".format(keystone_server_url)] + custom_tags,
                )
            except KeystoneUnreachable as e:
                self.warning(
                    "The agent could not contact the specified identity server at {} . "
                    "Are you sure it is up at that address?".format(keystone_server_url)
                )
                self.log.debug("Problem grabbing auth token: %s", e)
                self.service_check(
                    self.IDENTITY_API_SC,
                    AgentCheck.CRITICAL,
                    tags=["keystone_server: {}".format(keystone_server_url)] + custom_tags,
                )

                # If Keystone is down/unreachable, we default the
                # Nova and Neutron APIs to UNKNOWN since we cannot access the service catalog
                self.service_check(
                    self.NETWORK_API_SC,
                    AgentCheck.UNKNOWN,
                    tags=["keystone_server: {}".format(keystone_server_url)] + custom_tags,
                )
                self.service_check(
                    self.COMPUTE_API_SC,
                    AgentCheck.UNKNOWN,
                    tags=["keystone_server: {}".format(keystone_server_url)] + custom_tags,
                )

            except MissingNovaEndpoint as e:
                self.warning("The agent could not find a compatible Nova endpoint in your service catalog!")
                self.log.debug("Failed to get nova endpoint for response catalog: %s", e)
                self.service_check(
                    self.COMPUTE_API_SC,
                    AgentCheck.CRITICAL,
                    tags=["keystone_server: {}".format(keystone_server_url)] + custom_tags,
                )

            except MissingNeutronEndpoint:
                self.warning("The agent could not find a compatible Neutron endpoint in your service catalog!")
                self.service_check(
                    self.NETWORK_API_SC,
                    AgentCheck.CRITICAL,
                    tags=["keystone_server: {}".format(keystone_server_url)] + custom_tags,
                )

        if self._api is None:
            # Fast fail in the absence of an api
            raise IncompleteConfig()
781915
def auth(profile=None, **connection_args):
    '''
    
    '''
    __utils__['versions.warn_until'](
        'Neon',
        (
            'The keystone module has been deprecated and will be removed in {version}.  '
            'Please update to using the keystoneng module'
        ),
    )
    kwargs = _get_kwargs(profile=profile, **connection_args)

    disc = discover.Discover(auth_url=kwargs['auth_url'])
    v2_auth_url = disc.url_for('v2.0')
    v3_auth_url = disc.url_for('v3.0')
    if v3_auth_url:
        global _OS_IDENTITY_API_VERSION
        global _TENANTS
        _OS_IDENTITY_API_VERSION = 3
        _TENANTS = 'projects'
        kwargs['auth_url'] = v3_auth_url
    else:
        kwargs['auth_url'] = v2_auth_url
        kwargs.pop('user_domain_name')
        kwargs.pop('project_domain_name')
    auth = generic.Password(**kwargs)
    sess = session.Session(auth=auth)
    ks_cl = disc.create_client(session=sess)
    return ks_cl
461964
function checkCollabAuthenticated(req, res, next) {
		if (req.user) {
			req.user.workspaceDir = options.workspaceDir + (req.user.workspace ? "/" + req.user.workspace : "");
			next();
		} else if (req.headers['authorization'] && checkCollabServerToken(req.headers['authorization'])){
			next();
		} else {
			api.writeError(401, res, "Not authenticated");
		}
	}
203270
def _auth(profile=None, api_version=2, **connection_args):
    '''
    
    '''
    __utils__['versions.warn_until'](
        'Neon',
        (
            'The glance module has been deprecated and will be removed in {version}.  '
            'Please update to using the glanceng module'
        ),
    )

    if profile:
        prefix = profile + ":keystone."
    else:
        prefix = "keystone."

    def get(key, default=None):
        '''
        Checks connection_args, then salt-minion config,
        falls back to specified default value.
        '''
        return connection_args.get('connection_' + key,
            __salt__['config.get'](prefix + key, default))

    user = get('user', 'admin')
    password = get('password', None)
    tenant = get('tenant', 'admin')
    tenant_id = get('tenant_id')
    auth_url = get('auth_url', 'http://127.0.0.1:35357/v2.0')
    insecure = get('insecure', False)
    admin_token = get('token')
    region = get('region')
    ks_endpoint = get('endpoint', 'http://127.0.0.1:9292/')
    g_endpoint_url = __salt__['keystone.endpoint_get']('glance', profile)
    # The trailing 'v2' causes URLs like thise one:
    # http://127.0.0.1:9292/v2/v1/images
    g_endpoint_url = re.sub('/v2', '', g_endpoint_url['internalurl'])

    if admin_token and api_version != 1 and not password:
        # If we had a password we could just
        # ignore the admin-token and move on...
        raise SaltInvocationError('Only can use keystone admin token ' +
            'with Glance API v1')
    elif password:
        # Can't use the admin-token anyway
        kwargs = {'username': user,
                  'password': password,
                  'tenant_id': tenant_id,
                  'auth_url': auth_url,
                  'endpoint_url': g_endpoint_url,
                  'region_name': region,
                  'tenant_name': tenant}
        # 'insecure' keyword not supported by all v2.0 keystone clients
        #   this ensures it's only passed in when defined
        if insecure:
            kwargs['insecure'] = True
    elif api_version == 1 and admin_token:
        kwargs = {'token': admin_token,
                  'auth_url': auth_url,
                  'endpoint_url': g_endpoint_url}
    else:
        raise SaltInvocationError('No credentials to authenticate with.')

    if HAS_KEYSTONE:
        log.debug('Calling keystoneclient.v2_0.client.Client(%s, **%s)',
                  ks_endpoint, kwargs)
        keystone = kstone.Client(**kwargs)
        kwargs['token'] = keystone.get_token(keystone.session)
        # This doesn't realy prevent the password to show up
        # in the minion log as keystoneclient.session is
        # logging it anyway when in debug-mode
        kwargs.pop('password')
        log.debug('Calling glanceclient.client.Client(%s, %s, **%s)',
                  api_version, g_endpoint_url, kwargs)
        # may raise exc.HTTPUnauthorized, exc.HTTPNotFound
        # but we deal with those elsewhere
        return client.Client(api_version, g_endpoint_url, **kwargs)
    else:
        raise NotImplementedError(
            "Can't retrieve a auth_token without keystone")
1106624
def checkURL(cls, trust_root, url):
        """"""
        tr = cls.parse(trust_root)
        return tr is not None and tr.validateURL(url)
356171
def get_keystone_session(self, keystone_ip, username, password,
                             api_version=False, admin_port=False,
                             user_domain_name=None, domain_name=None,
                             project_domain_name=None, project_name=None):
        """"""
        ep = self.get_keystone_endpoint(keystone_ip,
                                        api_version=api_version,
                                        admin_port=admin_port)
        if api_version == 2:
            auth = v2.Password(
                username=username,
                password=password,
                tenant_name=project_name,
                auth_url=ep
            )
            sess = keystone_session.Session(auth=auth)
        else:
            auth = v3.Password(
                user_domain_name=user_domain_name,
                username=username,
                password=password,
                domain_name=domain_name,
                project_domain_name=project_domain_name,
                project_name=project_name,
                auth_url=ep
            )
            sess = keystone_session.Session(auth=auth)
        return (sess, auth)
20965
def verify_credentials(self, delegate=None):
        ""
        parser = txml.Users(delegate)
        return self.__downloadPage('/account/verify_credentials.xml', parser)
1107071
function isPrivateSessionAuth(req, res, next) {
        if (!res.isPrivateBlog) {
            return res.redirect(urlService.utils.urlFor('home', true));
        }

        let hash = req.session.token || '',
            salt = req.session.salt || '',
            isVerified = verifySessionHash(salt, hash);

        if (isVerified) {
            // redirect to home if user is already authenticated
            return res.redirect(urlService.utils.urlFor('home', true));
        } else {
            return next();
        }
    }
1114670
def ensure_auth_scope(self, instance):
        
        instance_scope = None

        custom_tags = instance.get('tags', [])
        if custom_tags is None:
            custom_tags = []
        try:
            instance_scope = self.get_scope_for_instance(instance)
        except KeyError:

            # We're missing a project scope for this instance
            # Let's populate it now
            try:
                if 'auth_scope' in instance:
                    instance_scope = OpenStackProjectScope.from_config(self.init_config, instance, self.proxy_config)
                else:
                    instance_scope = OpenStackUnscoped.from_config(self.init_config, instance, self.proxy_config)

                self.service_check(
                    self.IDENTITY_API_SC,
                    AgentCheck.OK,
                    tags=["server:%s" % self.init_config.get("keystone_server_url")] + custom_tags,
                )
            except KeystoneUnreachable as e:
                self.warning(
                    "The agent could not contact the specified identity server at %s . \
                    Are you sure it is up at that address?"
                    % self.init_config.get("keystone_server_url")
                )
                self.log.debug("Problem grabbing auth token: %s", e)
                self.service_check(
                    self.IDENTITY_API_SC,
                    AgentCheck.CRITICAL,
                    tags=["keystone_server:%s" % self.init_config.get("keystone_server_url")] + custom_tags,
                )

                # If Keystone is down/unreachable, we default the
                # Nova and Neutron APIs to UNKNOWN since we cannot access the service catalog
                self.service_check(
                    self.NETWORK_API_SC,
                    AgentCheck.UNKNOWN,
                    tags=["keystone_server:%s" % self.init_config.get("keystone_server_url")] + custom_tags,
                )
                self.service_check(
                    self.COMPUTE_API_SC,
                    AgentCheck.UNKNOWN,
                    tags=["keystone_server:%s" % self.init_config.get("keystone_server_url")] + custom_tags,
                )

            except MissingNovaEndpoint as e:
                self.warning("The agent could not find a compatible Nova endpoint in your service catalog!")
                self.log.debug("Failed to get nova endpoint for response catalog: %s", e)
                self.service_check(
                    self.COMPUTE_API_SC,
                    AgentCheck.CRITICAL,
                    tags=["keystone_server:%s" % self.init_config.get("keystone_server_url")] + custom_tags,
                )

            except MissingNeutronEndpoint:
                self.warning("The agent could not find a compatible Neutron endpoint in your service catalog!")
                self.service_check(
                    self.NETWORK_API_SC,
                    AgentCheck.CRITICAL,
                    tags=["keystone_server:%s" % self.init_config.get("keystone_server_url")] + custom_tags,
                )
            else:
                self.set_scope_for_instance(instance, instance_scope)

        return instance_scope
1324992
def authenticate_glance_admin(self, keystone, force_v1_client=False):
        """"""
        self.log.debug('Authenticating glance admin...')
        ep = keystone.service_catalog.url_for(service_type='image',
                                              interface='adminURL')
        if not force_v1_client and keystone.session:
            return glance_clientv2.Client("2", session=keystone.session)
        else:
            return glance_client.Client(ep, token=keystone.auth_token)
1023640
def authenticate_nova_user(self, keystone, user, password, tenant):
        """"""
        self.log.debug('Authenticating nova user ({})...'.format(user))
        ep = keystone.service_catalog.url_for(service_type='identity',
                                              interface='publicURL')
        if keystone.session:
            return nova_client.Client(NOVA_CLIENT_VERSION,
                                      session=keystone.session,
                                      auth_url=ep)
        elif novaclient.__version__[0] >= "7":
            return nova_client.Client(NOVA_CLIENT_VERSION,
                                      username=user, password=password,
                                      project_name=tenant, auth_url=ep)
        else:
            return nova_client.Client(NOVA_CLIENT_VERSION,
                                      username=user, api_key=password,
                                      project_id=tenant, auth_url=ep)
882464
def authentication_url_from_master(master_url, auth_params)
      client = Kontena::Client.new(master_url)
      vspinner "Sending authentication request to receive an authorization URL" do
        response = client.request(
          http_method: :get,
          path: authentication_path(auth_params),
          expects: [501, 400, 302, 403],
          auth: false
        )

        if client.last_response.status == 302
          client.last_response.headers['Location']
        elsif response.kind_of?(Hash)
          exit_with_error [response['error'], response['error_description']].compact.join(' : ')
        elsif response.kind_of?(String) && response.length > 1
          exit_with_error response
        else
          exit_with_error "Invalid response to authentication request : HTTP#{client.last_response.status} #{client.last_response.body if debug?}"
        end
      end
    end
1081418
def verify_key (self, acctname=None, tokenkey=None):
        ''' 
        '''
        if (re.match( r'^[A-Za-z0-9]+$', tokenkey)
                        and tokenkey is not None
                        and len(tokenkey) <= 64
                        and len(tokenkey) >= 16):
            pubkey = PrivateKey(tokenkey).pubkey or 0
            pubkey2 = self.account(acctname)
            if (str(pubkey) 
                    == str(pubkey2['posting']['key_auths'][0][0])):
                self.privatekey = tokenkey
                self.refreshtoken = None
                self.accesstoken = None
                return True
            else:
                return False
        elif (re.match( r'^[A-Za-z0-9\-\_\.]+$', tokenkey)
                        and tokenkey is not None
                        and len(tokenkey) > 64):
            self.privatekey = None
            self.accesstoken = self.connect.get_token(tokenkey)
            if self.accesstoken:
                self.username = self.connect.username
                self.refreshtoken = self.connect.refresh_token
                return True
            else:
                return False
        else:
            return False
202675
def _build_auth_request(self, verify=False, **kwargs):
        
        json = {
            'domain': self.domain
        }
        
        credential = self.credential
        params = {}
        
        if credential.provider_name.startswith('lms'):
            params = dict(
                login=credential._login,
                pwd=credential._pwd)
        else:
            json.update(authenticationkey=credential._api_key)
        
        if kwargs:
            json.update(**kwargs)
            self._extra_args.update(**kwargs) # Store in case we need to rebuild later
        
        request = dict(
            url=self.credential.get_provider_entry_point(self.url, self.api_version),
            json=json,
            params=params,
            headers={'content-type': 'application/json'},
            verify=verify)
        
        return request