Exemplo n.º 1
0
    def on_get(self, req, resp, token_id):
        token = identity.token_id_driver().token_from_id(token_id)
        identity.token_driver().validate_access(token, tenant_id=req.get_param("belongsTo"))
        access = get_access(token_id, token)

        resp.status = 200
        resp.body = {"access": access}
Exemplo n.º 2
0
    def on_post(self, req, resp):
        body = req.stream.read().decode()
        credentials = json.loads(body)
        tokens = identity.token_driver()

        auth = identity.auth_driver().authenticate(credentials)
        if auth is None:
            raise exceptions.Unauthorized('Unauthorized credentials')
        token = tokens.create_token(credentials, auth)
        tok_id = identity.token_id_driver().create_token_id(token)
        access = get_access(tok_id, token)

        # Add catalog to the access data
        raw_catalog = self._get_catalog(tokens.tenant_id(token),
                                        tokens.user_id(token))
        catalog = []
        for services in raw_catalog.values():
            for service_type, service in services.items():
                d = {
                    'type': service_type,
                    'name': service.get('name', 'Unknown'),
                    'endpoints': [{
                        'region': service.get('region', 'RegionOne'),
                        'publicURL': service.get('publicURL'),
                        'privateURL': service.get('privateURL'),
                        'adminURL': service.get('adminURL'),
                    }],
                    'endpoint_links': [],
                }
                catalog.append(d)

        access['serviceCatalog'] = catalog

        resp.status = 200
        resp.body = {'access': access}
Exemplo n.º 3
0
    def on_get(self, req, resp):
        toks = [req.get_header('X-Auth-Token'),  # the token who sent request
                req.get_header('X-Subject-Token')]  # the token to be validated
        token_id_driver = identity.token_id_driver()
        tokens = identity.token_driver()
        validated_tokens = []
        for token_id in toks:
            token = token_id_driver.token_from_id(token_id)
            tokens.validate_token(token)
            validated_tokens.append(token)

        access = get_access_v3(toks[1], validated_tokens[1],
                               tokens.user_id(validated_tokens[1]),
                               tokens.username(validated_tokens[1]))

        if 'nocatalog' not in req.query_string:
            # Add catalog to the access data
            catalog = self._build_catalog(validated_tokens[1],
                                          tokens.user_id(validated_tokens[1]))
            access['token']['catalog'] = catalog

        resp.status = 200
        resp.set_header('X-Auth-Token', toks[0])
        resp.set_header('X-Subject-Token', toks[1])
        # V2 APIs return the body in 'access' keypair but V3 APIs do not
        # resp.body = {'access': access}
        resp.body = access
Exemplo n.º 4
0
	def authenticate(self, creds):
		username     = utils.lookup(creds,'auth','passwordCredentials','username')
		credential   = utils.lookup(creds,'auth','passwordCredentials','password')
		token_id     = utils.lookup(creds, 'auth', 'token', 'id')
		token_driver = identity.token_driver()
		token_auth   = None
		
		# If token_id exists, get UID/Password associated w/ this token.
		if token_id:
			token = identity.token_id_driver().token_from_id(token_id)
			token_driver.validate_token(token)  
			username   = token_driver.username(token)
			credential = token_driver.credential(token)
			token_auth = token['auth_type'] == 'token'
				
		headers = {"Accept": "application/json", "Content-Type": "application/json"}
		auth    = (username, credential)
		resp    = requests.get("https://cloud.skytap.com/users", headers=headers, auth=auth)
		
		if resp.status_code == 200:
			payload   = json.loads(resp.text)
			user_id   = utils.lookup(payload[0], 'id')
			auth_type = "token" if token_auth else "api_key"
			sys.stderr.write("auth_type: %s" % auth_type)
			return {'user': {"id": user_id, "username": username, "accountId": user_id}, 'credential': credential, 'auth_type': auth_type}
		
		return None
Exemplo n.º 5
0
    def authenticate(self, creds):
        username = lookup(creds, 'auth', 'passwordCredentials',
                          'username')
        credential = lookup(creds, 'auth', 'passwordCredentials',
                            'password')
        token_id = lookup(creds, 'auth', 'token', 'id')

        token_auth = None

        if token_id:
            token = identity.token_id_driver().token_from_id(token_id)
            token_driver = identity.token_driver()
            token_driver.validate_token(token)
            username = token_driver.username(token)
            credential = token_driver.credential(token)
            token_auth = token['auth_type'] == 'token'

        def assert_tenant(user):
            tenant = lookup(creds, 'auth', 'tenantId') or lookup(creds,
                                                                 'auth',
                                                                 'tenantName')
            if tenant and str(user['accountId']) != tenant:
                raise Unauthorized('Invalid username, password or tenant id')

        # If the 'password' is the right length, treat it as an API api_key
        if len(credential) == 64:
            client = Client(username=username, api_key=credential,
                            endpoint_url=cfg.CONF['softlayer']['endpoint'],
                            proxy=cfg.CONF['softlayer']['proxy'])
            user = client['Account'].getCurrentUser(mask=USER_MASK)
            assert_tenant(user)
            return {'user': user, 'credential': credential,
                    'auth_type': 'api_key'}
        else:
            client = Client(endpoint_url=cfg.CONF['softlayer']['endpoint'],
                            proxy=cfg.CONF['softlayer']['proxy'])
            client.auth = None
            try:
                if token_auth:
                    client.auth = TokenAuthentication(token['user_id'],
                                                      credential)
                else:
                    userId, tokenHash = client.\
                        authenticate_with_password(username, credential)

                user = client['Account'].getCurrentUser(mask=USER_MASK)
                assert_tenant(user)

                if token_auth:
                    tokenHash = credential

                return {'user': user, 'credential': tokenHash,
                        'auth_type': 'token'}
            except SoftLayerAPIError as e:
                if (e.faultCode == "SoftLayer_Exception_User_Customer"
                        "_LoginFailed"):
                    raise Unauthorized(e.faultString)
                raise
Exemplo n.º 6
0
    def on_get(self, req, resp, token_id):
        token = identity.token_id_driver().token_from_id(token_id)
        identity.token_driver().validate_access(token, tenant_id=req.get_param(
            'belongsTo'))
        access = get_access(token_id, token)

        # Add catalog to the access data
        self._add_catalog_to_access(access, token)

        resp.status = 200
        resp.body = {'access': access}
Exemplo n.º 7
0
def get_token_details(token, tenant_id=None):
    try:
        token_id_driver = identity.token_id_driver()
        token_details = token_id_driver.token_from_id(token)
    except (TypeError, ValueError):
        raise exceptions.Unauthorized('Invalid Key')

    if time.time() > token_details['expires']:
        raise exceptions.Unauthorized('Expired Key')

    if tenant_id and str(token_details['tenant_id']) != tenant_id:
        raise exceptions.Unauthorized('Tenant/token Mismatch')

    return token_details
Exemplo n.º 8
0
    def on_post(self, req, resp):
        body = req.stream.read().decode()
        credentials = json.loads(body)
        tokens = identity.token_driver()

        auth = identity.auth_driver().authenticate(credentials)
        if auth is None:
            raise exceptions.Unauthorized('Unauthorized credentials')
        token = tokens.create_token(credentials, auth)
        tok_id = identity.token_id_driver().create_token_id(token)
        access = get_access(tok_id, token)

        # Add catalog to the access data
        self._add_catalog_to_access(access, token)

        resp.status = 200
        resp.body = {'access': access}
Exemplo n.º 9
0
    def authenticate(self, creds):
        username = lookup(creds, 'auth', 'passwordCredentials',
                          'username')
        credential = lookup(creds, 'auth', 'passwordCredentials',
                            'password')
        token_id = lookup(creds, 'auth', 'token', 'id')
        if token_id:
            token = identity.token_id_driver().token_from_id(token_id)
            token_driver = identity.token_driver()
            token_driver.validate_token(token)
            username = token_driver.username(token)
            credential = token_driver.credential(token)

        def assert_tenant(user):
            tenant = lookup(creds, 'auth', 'tenantId') or lookup(creds,
                                                                 'auth',
                                                                 'tenantName')
            if tenant and str(user['accountId']) != tenant:
                raise Unauthorized('Invalid username, password or tenant id')

        # If the 'password' is the right length, treat it as an API api_key
        if len(credential) == 64:
            client = Client(username=username, api_key=credential,
                            endpoint_url=cfg.CONF['softlayer']['endpoint'],
                            proxy=cfg.CONF['softlayer']['proxy'])
            user = client['Account'].getCurrentUser(mask=USER_MASK)
            assert_tenant(user)
            return {'user': user, 'credential': credential,
                    'auth_type': 'api_key'}
        else:
            client = Client(endpoint_url=cfg.CONF['softlayer']['endpoint'],
                            proxy=cfg.CONF['softlayer']['proxy'])
            client.auth = None
            try:
                userId, tokenHash = client.\
                    authenticate_with_password(username, credential)
                user = client['Account'].getCurrentUser(mask=USER_MASK)
                assert_tenant(user)
                return {'user': user, 'credential': tokenHash,
                        'auth_type': 'token'}
            except SoftLayerAPIError as e:
                if (e.faultCode == "SoftLayer_Exception_User_Customer"
                        "_LoginFailed"):
                    raise Unauthorized(e.faultString)
                raise
Exemplo n.º 10
0
 def on_get(self, req, resp, token_id):
     tokens = identity.token_driver()
     token = identity.token_id_driver().token_from_id(token_id)
     identity.token_driver().validate_token(token)
     raw_endpoints = self._get_catalog(tokens.tenant_id(token), tokens.user_id(token))
     endpoints = []
     for services in raw_endpoints.values():
         for service_type, service in services.items():
             d = {
                 "adminURL": service.get("adminURL"),
                 "name": service.get("name", "Unknown"),
                 "publicURL": service.get("publicURL"),
                 "privateURL": service.get("privateURL"),
                 "region": service.get("region", "RegionOne"),
                 "tenantId": tokens.tenant_id(token),
                 "type": service_type,
             }
             endpoints.append(d)
     resp.status = 200
     resp.body = {"endpoints": endpoints, "endpoints_links": []}
Exemplo n.º 11
0
	def on_get(self, req, resp):
		token_id = req.headers.get('X-AUTH-TOKEN', None)
		tokens   = identity.token_driver()
		token    = identity.token_id_driver().token_from_id(token_id)
		identity.token_driver().validate_token(token)
		raw_endpoints = self._get_catalog(tokens.tenant_id(token), tokens.user_id(token))
		endpoints = []
		for services in raw_endpoints.values():
			for service_type, service in services.items():
				d = {
				  'adminURL': service.get('adminURL'),
				  'name': service.get('name', 'Unknown'),
				  'publicURL': service.get('publicURL'),
				  'privateURL': service.get('privateURL'),
				  'region': service.get('region', 'RegionOne'),
				  'tenantId': tokens.tenant_id(token),
				  'type': service_type,
				}
				endpoints.append(d)
		resp.status = 200
		resp.body = {'endpoints': endpoints, 'endpoints_links': []}
Exemplo n.º 12
0
def validate_token(req, resp, kwargs):
    tenant_id = req.env.get('tenant_id', None)
    token = req.headers.get('X-AUTH-TOKEN', None)

    if (req.env.get('REMOTE_USER', None) is not None or
            req.env.get('is_admin', False) or
            req.env.get('auth', None) is not None):
        # upstream authentication
        return

    if token is not None:
        if tenant_id is None:
            tenant_id = kwargs.get('tenant_id',
                                   req.headers.get('X-AUTH-PROJECT-ID'))
            req.env['tenant_id'] = tenant_id

        LOG.debug("Authenticating request token '%s'" % (token))
        identity.validate_token_id(token, tenant_id=tenant_id)
        req.env['auth'] = identity.token_id_driver().token_from_id(token)
    elif protected("%s:%s" % (req.method, req.path)):
        raise exceptions.Unauthorized('Authentication token required')
Exemplo n.º 13
0
 def on_get(self, req, resp, token_id):
     tokens = identity.token_driver()
     token = identity.token_id_driver().token_from_id(token_id)
     identity.token_driver().validate_token(token)
     raw_endpoints = self._get_catalog(tokens.tenant_id(token),
                                       tokens.user_id(token))
     endpoints = []
     for services in raw_endpoints.values():
         for service_type, service in services.items():
             d = {
                 'adminURL': service.get('adminURL'),
                 'name': service.get('name', 'Unknown'),
                 'publicURL': service.get('publicURL'),
                 'privateURL': service.get('privateURL'),
                 'region': service.get('region', 'RegionOne'),
                 'tenantId': tokens.tenant_id(token),
                 'type': service_type,
             }
             endpoints.append(d)
     resp.status = 200
     resp.body = {'endpoints': endpoints, 'endpoints_links': []}
Exemplo n.º 14
0
def validate_token(req, resp, kwargs):
    tenant_id = req.env.get('tenant_id', None)
    token = req.headers.get('X-AUTH-TOKEN', None)

    if (req.env.get('REMOTE_USER', None) is not None
            or req.env.get('is_admin', False)
            or req.env.get('auth', None) is not None):
        # upstream authentication
        return

    if token is not None:
        if tenant_id is None:
            tenant_id = kwargs.get('tenant_id',
                                   req.headers.get('X-AUTH-PROJECT-ID'))
            req.env['tenant_id'] = tenant_id

        LOG.debug("Authenticating request token '%s'" % (token))
        identity.validate_token_id(token, tenant_id=tenant_id)
        req.env['auth'] = identity.token_id_driver().token_from_id(token)
    elif protected("%s:%s" % (req.method, req.path)):
        raise exceptions.Unauthorized('Authentication token required')
Exemplo n.º 15
0
    def authenticate(self, creds):
        username = lookup(creds, "auth", "passwordCredentials", "username")
        credential = lookup(creds, "auth", "passwordCredentials", "password")
        token_id = lookup(creds, "auth", "token", "id")
        if token_id:
            token = identity.token_id_driver().token_from_id(token_id)
            token_driver = identity.token_driver()
            token_driver.validate_token(token)
            username = token_driver.username(token)
            credential = token_driver.credential(token)

        def assert_tenant(user):
            tenant = lookup(creds, "auth", "tenantId") or lookup(creds, "auth", "tenantName")
            if tenant and str(user["accountId"]) != tenant:
                raise Unauthorized("Invalid username, password or tenant id")

        # If the 'password' is the right length, treat it as an API api_key
        if len(credential) == 64:
            client = Client(
                username=username,
                api_key=credential,
                endpoint_url=cfg.CONF["softlayer"]["endpoint"],
                proxy=cfg.CONF["softlayer"]["proxy"],
            )
            user = client["Account"].getCurrentUser(mask=USER_MASK)
            assert_tenant(user)
            return {"user": user, "credential": credential, "auth_type": "api_key"}
        else:
            client = Client(endpoint_url=cfg.CONF["softlayer"]["endpoint"], proxy=cfg.CONF["softlayer"]["proxy"])
            client.auth = None
            try:
                userId, tokenHash = client.authenticate_with_password(username, credential)
                user = client["Account"].getCurrentUser(mask=USER_MASK)
                assert_tenant(user)
                return {"user": user, "credential": tokenHash, "auth_type": "token"}
            except SoftLayerAPIError as e:
                if e.faultCode == "SoftLayer_Exception_User_Customer" "_LoginFailed":
                    raise Unauthorized(e.faultString)
                raise
Exemplo n.º 16
0
    def on_post(self, req, resp):
        body = req.stream.read().decode()
        credentials = json.loads(body)
        tokens = identity.token_driver()

        auth = identity.auth_driver().authenticate(credentials)
        if auth is None:
            raise Unauthorized('Unauthorized credentials')
        token = tokens.create_token(credentials, auth)
        tok_id = identity.token_id_driver().create_token_id(token)
        access = get_access(tok_id, token)

        # Add catalog to the access data
        raw_catalog = self._get_catalog(tokens.tenant_id(token),
                                        tokens.user_id(token))
        catalog = []
        for services in raw_catalog.values():
            for service_type, service in services.items():
                d = {
                    'type':
                    service_type,
                    'name':
                    service.get('name', 'Unknown'),
                    'endpoints': [{
                        'region': service.get('region', 'RegionOne'),
                        'publicURL': service.get('publicURL'),
                        'privateURL': service.get('privateURL'),
                        'adminURL': service.get('adminURL'),
                    }],
                    'endpoint_links': [],
                }
                catalog.append(d)

        access['serviceCatalog'] = catalog

        resp.status = 200
        resp.body = {'access': access}
Exemplo n.º 17
0
    def on_post(self, req, resp):
        body = req.stream.read().decode()
        credentials = json.loads(body)
        tokens = identity.token_driver()

        auth = identity.auth_driver().authenticate(credentials)
        if auth is None:
            raise Unauthorized("Unauthorized credentials")
        token = tokens.create_token(credentials, auth)
        tok_id = identity.token_id_driver().create_token_id(token)
        access = get_access(tok_id, token)

        # Add catalog to the access data
        raw_catalog = self._get_catalog(tokens.tenant_id(token), tokens.user_id(token))
        catalog = []
        for services in raw_catalog.values():
            for service_type, service in services.items():
                d = {
                    "type": service_type,
                    "name": service.get("name", "Unknown"),
                    "endpoints": [
                        {
                            "region": service.get("region", "RegionOne"),
                            "publicURL": service.get("publicURL"),
                            "privateURL": service.get("privateURL"),
                            "adminURL": service.get("adminURL"),
                        }
                    ],
                    "endpoint_links": [],
                }
                catalog.append(d)

        access["serviceCatalog"] = catalog

        resp.status = 200
        resp.body = {"access": access}
Exemplo n.º 18
0
def get_new_token_v3(credentials):
    token_driver = identity.token_driver()
    token_id = utils.lookup(credentials, 'auth', 'identity', 'token', 'id')
    if token_id:
        token = identity.token_id_driver().token_from_id(token_id)
        LOG.debug("token details are: %s", str(token))

        token_driver.validate_token(token)
        username = token_driver.username(token)
        credential = token_driver.credential(token)
        userinfo = {'username': username,
                    'auth_type': str(token['auth_type']),
                    'tenant_id': str(token['tenant_id']),
                    'expires': token['expires']}
        if token['auth_type'] == 'token':
            userinfo['tokenHash'] = credential
        if token['auth_type'] == 'api_key':
            userinfo['api_key'] = credential
        user = {'id': token['user_id'],
                'username': username,
                'accountId': token['tenant_id']}
        return userinfo, user

    username = utils.lookup(credentials,
                            'auth',
                            'passwordCredentials',
                            'username')
    credential = utils.lookup(credentials,
                              'auth',
                              'passwordCredentials',
                              'password')

    # If the 'password' is the right length, treat it as an API api_key
    if len(credential) == 64:
        endpoint = cfg.CONF['softlayer']['endpoint']
        client = SoftLayer.Client(username=username,
                                  api_key=credential,
                                  endpoint_url=endpoint,
                                  proxy=cfg.CONF['softlayer']['proxy'])
        user = client['Account'].getCurrentUser(mask=USER_MASK)

        username = token_driver.username(user)

        return {'username': username,
                'api_key': credential,
                'auth_type': 'api_key',
                'tenant_id': str(user['accountId']),
                'expires': time.time() + (60 * 60 * 24)}, user

    else:
        endpoint = cfg.CONF['softlayer']['endpoint']
        client = SoftLayer.Client(endpoint_url=endpoint,
                                  proxy=cfg.CONF['softlayer']['proxy'])
        client.auth = None
        try:
            userId, tokenHash = client.authenticate_with_password(username,
                                                                  credential)
            user = client['Account'].getCurrentUser(mask=USER_MASK)
            username = token_driver.username(user)
            return {'userId': userId,
                    'username': username,
                    'tokenHash': tokenHash,
                    'auth_type': 'token',
                    'tenant_id': str(user['accountId']),
                    'expires': time.time() + (60 * 60 * 24)}, user

        except SoftLayer.SoftLayerAPIError as e:
            if e.faultCode == 'SoftLayer_Exception_User_Customer_LoginFailed':
                raise exceptions.Unauthorized(e.faultString)
            raise
Exemplo n.º 19
0
    def authenticate(self, creds):
        username = utils.lookup(creds, 'auth', 'passwordCredentials',
                                'username')
        credential = utils.lookup(creds, 'auth', 'passwordCredentials',
                                  'password')
        token_id = utils.lookup(creds, 'auth', 'token', 'id')
        token_driver = identity.token_driver()
        token_auth = None
        if token_id:
            token = identity.token_id_driver().token_from_id(token_id)
            token_driver.validate_token(token)
            username = token_driver.username(token)
            credential = token_driver.credential(token)
            token_auth = token['auth_type'] == 'token'

        def assert_tenant(user):
            tenant = (utils.lookup(creds, 'auth', 'tenantId')
                      or utils.lookup(creds, 'auth', 'tenantName'))
            if tenant and str(user['accountId']) != tenant:
                raise exceptions.Unauthorized(
                    'Invalid username, password or tenant id')

        endpoint = config.PARSER.get('softlayer', 'endpoint')
        proxy = config.PARSER.get('softlayer', 'proxy')
        # If the 'password' is the right length, treat it as an API api_key
        if len(credential) == 64:
            client = SoftLayer.Client(username=username,
                                      api_key=credential,
                                      endpoint_url=endpoint,
                                      proxy=proxy)
            user = client['Account'].getCurrentUser(mask=USER_MASK)
            assert_tenant(user)
            return {
                'user': user,
                'credential': credential,
                'auth_type': 'api_key'
            }

        else:
            client = SoftLayer.Client(endpoint_url=endpoint, proxy=proxy)
            client.auth = None
            try:
                if token_auth:
                    client.auth = SoftLayer.TokenAuthentication(
                        token['user_id'], credential)
                else:
                    userId, tokenHash = (client.authenticate_with_password(
                        username, credential))

                user = client['Account'].getCurrentUser(mask=USER_MASK)
                assert_tenant(user)

                if token_auth:
                    tokenHash = credential

                return {
                    'user': user,
                    'credential': tokenHash,
                    'auth_type': 'token'
                }
            except SoftLayer.SoftLayerAPIError as e:
                if (e.faultCode == "SoftLayer_Exception_User_Customer"
                        "_LoginFailed"):
                    raise exceptions.Unauthorized(e.faultString)
                raise