
com.sap.cloud.sdk.cloudplatform.tenant.ScpCfTenant Maven / Gradle / Ivy
/*
* Copyright (c) 2019 SAP SE or an SAP affiliate company. All rights reserved.
*/
package com.sap.cloud.sdk.cloudplatform.tenant;
import java.util.Optional;
import java.util.function.Function;
import javax.annotation.Nonnull;
import javax.annotation.Nullable;
import org.slf4j.Logger;
import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Payload;
import com.sap.cloud.sdk.cloudplatform.logging.CloudLoggerFactory;
import com.sap.cloud.sdk.cloudplatform.security.AuthToken;
import com.sap.cloud.sdk.cloudplatform.security.AuthTokenAccessor;
import com.sap.cloud.sdk.cloudplatform.tenant.exception.TenantAccessException;
import io.vavr.control.Try;
import lombok.Data;
import lombok.EqualsAndHashCode;
import lombok.ToString;
/**
* Implementation of {@link Tenant} for SAP Cloud Platform Cloud Foundry.
*/
@EqualsAndHashCode( callSuper = true )
@ToString( callSuper = true )
@Data
public class ScpCfTenant extends AbstractTenant
{
private static final Logger logger = CloudLoggerFactory.getLogger(ScpCfTenant.class);
private static final String JWT_TENANT_ID = "zid";
@Nullable
private static String getTenantId( @Nonnull final Payload jwt )
throws TenantAccessException
{
return jwt.getClaim(JWT_TENANT_ID).asString();
}
/**
* Creates a new {@link ScpCfTenant}.
*
* @param tenantId
* The identifier of the tenant.
*/
public ScpCfTenant( @Nonnull final String tenantId )
{
super(tenantId);
}
/**
* Creates a new {@link ScpCfTenant} based on the current {@link AuthToken}. If the current context contains no
* {@code AuthToken}, an {@code AuthToken} from the bound XSUAA service is used.
*
* @throws TenantAccessException
* If there is an issue while accessing the tenant from the current {@link AuthToken}.
*/
@Nullable
static ScpCfTenant ofCurrentTenant()
throws TenantAccessException
{
final Optional maybeAuthToken =
Try.of(AuthTokenAccessor::getCurrentToken).getOrElseThrow(tenantAccessException());
final AuthToken authToken;
authToken = maybeAuthToken.orElseGet(() -> Try.of(AuthTokenAccessor::getXsuaaServiceToken).getOrNull());
if( authToken == null ) {
return null;
}
final DecodedJWT jwt = authToken.getJwt();
@Nullable
final String tenantId = getTenantId(jwt);
if( tenantId == null ) {
return null;
}
return new ScpCfTenant(tenantId);
}
private static Function tenantAccessException()
{
return TenantAccessException::new;
}
/**
* Creates a mocked {@link ScpCfTenant} returning an empty tenant identifier.
*/
@Nonnull
static ScpCfTenant ofMockedTenant()
{
return new ScpCfTenant();
}
/**
* Creates a mocked {@link ScpCfTenant} returning an empty tenant identifier.
*/
private ScpCfTenant()
{
this("");
}
}
© 2015 - 2025 Weber Informatics LLC | Privacy Policy