com.atlassian.usercontext.impl.UserContextProviderImpl Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of atlassian-user-context Show documentation
Show all versions of atlassian-user-context Show documentation
Java library that implements the User Context spec for passing user context information between services
package com.atlassian.usercontext.impl;
import com.atlassian.usercontext.api.AuthenticationRequest;
import com.atlassian.usercontext.api.UserContext;
import com.atlassian.usercontext.api.UserContextAuthenticator;
import com.atlassian.usercontext.api.UserContextProvider;
import com.atlassian.usercontext.api.UserContextSetter;
import com.atlassian.usercontext.api.UserContextTokenValidator;
import com.atlassian.workcontext.api.WorkContextLocal;
import com.atlassian.workcontext.exception.WorkContextException;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.annotation.Nullable;
import java.util.Optional;
import static java.util.Objects.requireNonNull;
public class UserContextProviderImpl implements UserContextProvider, UserContextSetter {
private static final Logger log = LoggerFactory.getLogger(UserContextProviderImpl.class);
private final UserContextTokenValidator validator;
private final UserContextAuthenticator generator;
private final WorkContextLocal> userContextWorkContextLocal = new WorkContextLocal<>(Optional::empty);
public UserContextProviderImpl(UserContextTokenValidator validator, UserContextAuthenticator generator) {
this.validator = requireNonNull(validator);
this.generator = requireNonNull(generator);
}
@Override
public Optional getUserContext() {
try {
return userContextWorkContextLocal.get();
} catch (WorkContextException ex) {
throw new IllegalStateException(ex);
}
}
@Override
public void setUserContext(@Nullable UserContext userContext) {
userContextWorkContextLocal.set(Optional.ofNullable(userContext));
}
@Override
public Optional setUserContextFromJwt(@Nullable String validUserContext) {
if (StringUtils.isEmpty(validUserContext)) {
userContextWorkContextLocal.set(Optional.empty());
return Optional.empty();
}
Optional userContext = validator.validate(validUserContext);
if (!userContext.isPresent()) {
log.error("Attempt to set invalid user context token {}", validUserContext);
}
setUserContext(userContext.orElse(null));
return userContext;
}
@Override
public Optional authenticateAndSetUserContext(AuthenticationRequest request) {
requireNonNull(request);
Optional result = generator.authenticate(request);
result.ifPresent(this::setUserContext);
return result;
}
}