Skip to content

Instantly share code, notes, and snippets.

@onurcill
Created February 28, 2022 20:27
Show Gist options
  • Save onurcill/7ab1cf795f603c3f1b26bf95f1f779aa to your computer and use it in GitHub Desktop.
Save onurcill/7ab1cf795f603c3f1b26bf95f1f779aa to your computer and use it in GitHub Desktop.
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public final class TenantAssistance {
private static final String CLAIM_ORGANIZATION = "organization";
public static String resolveCurrentTenantIdentifier() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.filter(authentication -> authentication instanceof JwtAuthenticationToken)
.map(authentication -> (JwtAuthenticationToken) authentication)
.map(JwtAuthenticationToken::getPrincipal)
.filter(jwt -> jwt instanceof Jwt)
.map(jwt -> (Jwt) jwt)
.map(Jwt::getClaims)
.orElseThrow(() -> new NullPointerException("Claims are empty"))
.entrySet()
.stream()
.filter(k -> k.getKey().equals(CLAIM_ORGANIZATION))
.map(Map.Entry::getValue)
.findFirst()
.orElseThrow(() -> new UnknownTenantException("Tenant is empty")).toString();
}
public static String resolveCurrentUser() {
return Optional.ofNullable(SecurityContextHolder.getContext().getAuthentication())
.filter(JwtAuthenticationToken.class::isInstance)
.map(JwtAuthenticationToken.class::cast)
.map(JwtAuthenticationToken::getName)
.orElseThrow(() -> new NullPointerException("Sub is empty"));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment