All Downloads are FREE. Search and download functionalities are using the official Maven repository.

com.sap.cloud.sdk.cloudplatform.tenant.ScpCfTenant Maven / Gradle / Ivy

/*
 * Copyright (c) 2018 SAP SE or an SAP affiliate company. All rights reserved.
 */

package com.sap.cloud.sdk.cloudplatform.tenant;

import java.util.Optional;

import javax.annotation.Nonnull;
import javax.annotation.Nullable;

import com.auth0.jwt.interfaces.DecodedJWT;
import com.auth0.jwt.interfaces.Payload;
import com.sap.cloud.sdk.cloudplatform.security.AuthToken;
import com.sap.cloud.sdk.cloudplatform.security.AuthTokenAccessor;
import com.sap.cloud.sdk.cloudplatform.security.exception.AuthTokenAccessException;
import com.sap.cloud.sdk.cloudplatform.tenant.exception.TenantAccessException;

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 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}.
     *
     * @throws TenantAccessException
     *             If there is an issue while accessing the tenant from the current {@link AuthToken}.
     */
    @Nullable
    static ScpCfTenant ofCurrentTenant()
        throws TenantAccessException
    {
        final Optional authToken;
        try {
            authToken = AuthTokenAccessor.getCurrentToken();
        }
        catch( final AuthTokenAccessException e ) {
            throw new TenantAccessException("Failed to get tenant from current authorization token.", e);
        }

        if( !authToken.isPresent() ) {
            return null;
        }

        final DecodedJWT jwt = authToken.get().getJwt();

        @Nullable
        final String tenantId = getTenantId(jwt);

        if( tenantId == null ) {
            return null;
        }

        return new ScpCfTenant(tenantId);
    }

    /**
     * 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