TSK-1277: removed circular dependency between taskana-common and taskana-core

This commit is contained in:
Mustapha Zorgati 2020-10-07 08:43:41 +02:00
parent 47aa60033f
commit 44cb21b5ae
35 changed files with 315 additions and 261 deletions

View File

@ -36,8 +36,8 @@ import org.junit.platform.commons.JUnitException;
import org.junit.platform.commons.support.AnnotationSupport; import org.junit.platform.commons.support.AnnotationSupport;
import pro.taskana.common.api.exceptions.SystemException; import pro.taskana.common.api.exceptions.SystemException;
import pro.taskana.common.internal.security.GroupPrincipal; import pro.taskana.common.api.security.GroupPrincipal;
import pro.taskana.common.internal.security.UserPrincipal; import pro.taskana.common.api.security.UserPrincipal;
/** Runner for integration tests that enables JAAS subject. */ /** Runner for integration tests that enables JAAS subject. */
public class JaasExtension implements InvocationInterceptor, TestTemplateInvocationContextProvider { public class JaasExtension implements InvocationInterceptor, TestTemplateInvocationContextProvider {

View File

@ -23,39 +23,42 @@ import org.junit.jupiter.api.TestFactory;
import org.junit.jupiter.api.TestTemplate; import org.junit.jupiter.api.TestTemplate;
import org.junit.jupiter.api.extension.ExtendWith; import org.junit.jupiter.api.extension.ExtendWith;
import pro.taskana.common.internal.security.CurrentUserContext; import pro.taskana.common.api.security.CurrentUserContext;
import pro.taskana.common.internal.security.CurrentUserContextImpl;
@ExtendWith(JaasExtension.class) @ExtendWith(JaasExtension.class)
class JaasExtensionTest { class JaasExtensionTest {
private static final String INSIDE_DYNAMIC_TEST_USER = "insidedynamictest"; private static final String INSIDE_DYNAMIC_TEST_USER = "insidedynamictest";
private static final CurrentUserContext CURRENT_USER_CONTEXT = new CurrentUserContextImpl(true);
private static final DynamicTest NOT_NULL_DYNAMIC_TEST = private static final DynamicTest NOT_NULL_DYNAMIC_TEST =
dynamicTest("dynamic test", () -> assertThat(CurrentUserContext.getUserid()).isNotNull()); dynamicTest("dynamic test", () -> assertThat(CURRENT_USER_CONTEXT.getUserid()).isNotNull());
private static final DynamicTest NULL_DYNAMIC_TEST = private static final DynamicTest NULL_DYNAMIC_TEST =
dynamicTest("dynamic test", () -> assertThat(CurrentUserContext.getUserid()).isEqualTo(null)); dynamicTest(
"dynamic test", () -> assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null));
private static final DynamicTest DYNAMIC_TEST_USER_DYNAMIC_TEST = private static final DynamicTest DYNAMIC_TEST_USER_DYNAMIC_TEST =
dynamicTest( dynamicTest(
"dynamic test", "dynamic test",
() -> assertThat(CurrentUserContext.getUserid()).isEqualTo(INSIDE_DYNAMIC_TEST_USER)); () -> assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(INSIDE_DYNAMIC_TEST_USER));
// region JaasExtension#interceptBeforeAllMethod // region JaasExtension#interceptBeforeAllMethod
@BeforeAll @BeforeAll
static void should_NotSetJaasSubject_When_AnnotationIsMissing_On_BeforeAll() { static void should_NotSetJaasSubject_When_AnnotationIsMissing_On_BeforeAll() {
assertThat(CurrentUserContext.getUserid()).isEqualTo(null); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null);
} }
@WithAccessId(user = "beforeall") @WithAccessId(user = "beforeall")
@BeforeAll @BeforeAll
static void should_SetJaasSubject_When_AnnotationExists_On_BeforeAll() { static void should_SetJaasSubject_When_AnnotationExists_On_BeforeAll() {
assertThat(CurrentUserContext.getUserid()).isEqualTo("beforeall"); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo("beforeall");
} }
@WithAccessId(user = "beforeall") @WithAccessId(user = "beforeall")
@WithAccessId(user = "beforeall2") @WithAccessId(user = "beforeall2")
@BeforeAll @BeforeAll
static void should_NotSetJaasSubject_When_MultipleAnnotationsExist_On_BeforeAll() { static void should_NotSetJaasSubject_When_MultipleAnnotationsExist_On_BeforeAll() {
assertThat(CurrentUserContext.getUserid()).isEqualTo(null); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null);
} }
// endregion // endregion
@ -64,20 +67,20 @@ class JaasExtensionTest {
@BeforeEach @BeforeEach
void should_NotSetJaasSubject_When_AnnotationIsMissing_On_BeforeEach() { void should_NotSetJaasSubject_When_AnnotationIsMissing_On_BeforeEach() {
assertThat(CurrentUserContext.getUserid()).isEqualTo(null); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null);
} }
@WithAccessId(user = "beforeeach") @WithAccessId(user = "beforeeach")
@BeforeEach @BeforeEach
void should_SetJaasSubject_When_AnnotationExists_On_BeforeEach() { void should_SetJaasSubject_When_AnnotationExists_On_BeforeEach() {
assertThat(CurrentUserContext.getUserid()).isEqualTo("beforeeach"); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo("beforeeach");
} }
@WithAccessId(user = "beforeeach") @WithAccessId(user = "beforeeach")
@WithAccessId(user = "beforeeach2") @WithAccessId(user = "beforeeach2")
@BeforeEach @BeforeEach
void should_NotSetJaasSubject_When_MultipleAnnotationsExist_On_BeforeEach() { void should_NotSetJaasSubject_When_MultipleAnnotationsExist_On_BeforeEach() {
assertThat(CurrentUserContext.getUserid()).isEqualTo(null); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null);
} }
// endregion // endregion
@ -86,20 +89,20 @@ class JaasExtensionTest {
@AfterEach @AfterEach
void should_NotSetJaasSubject_When_AnnotationIsMissing_On_AfterEach() { void should_NotSetJaasSubject_When_AnnotationIsMissing_On_AfterEach() {
assertThat(CurrentUserContext.getUserid()).isEqualTo(null); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null);
} }
@WithAccessId(user = "aftereach") @WithAccessId(user = "aftereach")
@AfterEach @AfterEach
void should_SetJaasSubject_When_AnnotationExists_On_AfterEach() { void should_SetJaasSubject_When_AnnotationExists_On_AfterEach() {
assertThat(CurrentUserContext.getUserid()).isEqualTo("aftereach"); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo("aftereach");
} }
@WithAccessId(user = "aftereach") @WithAccessId(user = "aftereach")
@WithAccessId(user = "afterach2") @WithAccessId(user = "afterach2")
@AfterEach @AfterEach
void should_NotSetJaasSubject_When_MultipleAnnotationsExist_On_AfterEach() { void should_NotSetJaasSubject_When_MultipleAnnotationsExist_On_AfterEach() {
assertThat(CurrentUserContext.getUserid()).isEqualTo(null); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null);
} }
// endregion // endregion
@ -108,20 +111,20 @@ class JaasExtensionTest {
@AfterAll @AfterAll
static void should_NotSetJaasSubject_When_AnnotationIsMissing_On_AfterAll() { static void should_NotSetJaasSubject_When_AnnotationIsMissing_On_AfterAll() {
assertThat(CurrentUserContext.getUserid()).isEqualTo(null); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null);
} }
@WithAccessId(user = "afterall") @WithAccessId(user = "afterall")
@AfterAll @AfterAll
static void should_SetJaasSubject_When_AnnotationExists_On_AfterAll() { static void should_SetJaasSubject_When_AnnotationExists_On_AfterAll() {
assertThat(CurrentUserContext.getUserid()).isEqualTo("afterall"); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo("afterall");
} }
@WithAccessId(user = "afterall") @WithAccessId(user = "afterall")
@WithAccessId(user = "afterall2") @WithAccessId(user = "afterall2")
@AfterAll @AfterAll
static void should_NotSetJaasSubject_When_MultipleAnnotationsExist_On_AfterAll() { static void should_NotSetJaasSubject_When_MultipleAnnotationsExist_On_AfterAll() {
assertThat(CurrentUserContext.getUserid()).isEqualTo(null); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null);
} }
// endregion // endregion
@ -130,14 +133,14 @@ class JaasExtensionTest {
@Test @Test
void should_NotSetJaasSubject_When_AnnotationIsMissing_On_Test() { void should_NotSetJaasSubject_When_AnnotationIsMissing_On_Test() {
assertThat(CurrentUserContext.getUserid()).isEqualTo(null); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null);
} }
@WithAccessId(user = "user") @WithAccessId(user = "user")
@Test @Test
void should_SetJaasSubject_When_AnnotationExists_On_Test() { void should_SetJaasSubject_When_AnnotationExists_On_Test() {
assertThat(CurrentUserContext.getUserid()).isEqualTo("user"); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo("user");
assertThat(CurrentUserContext.getGroupIds()).isEmpty(); assertThat(CURRENT_USER_CONTEXT.getGroupIds()).isEmpty();
} }
@WithAccessId( @WithAccessId(
@ -145,15 +148,15 @@ class JaasExtensionTest {
groups = {"group1", "group2"}) groups = {"group1", "group2"})
@Test @Test
void should_SetJaasSubjectWithGroups_When_AnnotationExistsWithGroups_On_Test() { void should_SetJaasSubjectWithGroups_When_AnnotationExistsWithGroups_On_Test() {
assertThat(CurrentUserContext.getUserid()).isEqualTo("user"); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo("user");
assertThat(CurrentUserContext.getGroupIds()).containsExactlyInAnyOrder("group1", "group2"); assertThat(CURRENT_USER_CONTEXT.getGroupIds()).containsExactlyInAnyOrder("group1", "group2");
} }
@WithAccessId(user = "user") @WithAccessId(user = "user")
@Test @Test
@Disabled("this can be tested with a org.junit.platform.launcher.TestExecutionListener") @Disabled("this can be tested with a org.junit.platform.launcher.TestExecutionListener")
void should_NotInjectParameter_When_ParameterIsPresent_On_Test(WithAccessId accessId) { void should_NotInjectParameter_When_ParameterIsPresent_On_Test(WithAccessId accessId) {
assertThat(CurrentUserContext.getUserid()).isEqualTo("user"); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo("user");
} }
@WithAccessId(user = "user") @WithAccessId(user = "user")
@ -161,7 +164,7 @@ class JaasExtensionTest {
@Test @Test
@Disabled("this can be tested with a org.junit.platform.launcher.TestExecutionListener") @Disabled("this can be tested with a org.junit.platform.launcher.TestExecutionListener")
void should_ThrowException_When_MultipleAnnotationsExist_On_Test() { void should_ThrowException_When_MultipleAnnotationsExist_On_Test() {
assertThat(CurrentUserContext.getUserid()).isEqualTo(null); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null);
} }
// endregion // endregion
@ -170,14 +173,14 @@ class JaasExtensionTest {
@TestFactory @TestFactory
List<DynamicTest> should_NotSetJaasSubject_When_AnnotationIsMissing_On_TestFactory() { List<DynamicTest> should_NotSetJaasSubject_When_AnnotationIsMissing_On_TestFactory() {
assertThat(CurrentUserContext.getUserid()).isEqualTo(null); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null);
return Collections.emptyList(); return Collections.emptyList();
} }
@WithAccessId(user = "testfactory") @WithAccessId(user = "testfactory")
@TestFactory @TestFactory
List<DynamicTest> should_SetJaasSubject_When_AnnotationExists_On_TestFactory() { List<DynamicTest> should_SetJaasSubject_When_AnnotationExists_On_TestFactory() {
assertThat(CurrentUserContext.getUserid()).isEqualTo("testfactory"); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo("testfactory");
return Collections.emptyList(); return Collections.emptyList();
} }
@ -186,7 +189,7 @@ class JaasExtensionTest {
@TestFactory @TestFactory
List<DynamicTest> List<DynamicTest>
should_SetJaasSubjectFromFirstAnnotation_When_MultipleAnnotationsExists_On_TestFactory() { should_SetJaasSubjectFromFirstAnnotation_When_MultipleAnnotationsExists_On_TestFactory() {
assertThat(CurrentUserContext.getUserid()).isEqualTo("testfactory1"); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo("testfactory1");
return Collections.emptyList(); return Collections.emptyList();
} }
@ -197,13 +200,13 @@ class JaasExtensionTest {
@TestTemplate @TestTemplate
@Disabled("this can be tested with a org.junit.platform.launcher.TestExecutionListener") @Disabled("this can be tested with a org.junit.platform.launcher.TestExecutionListener")
void should_NotFindContextProvider_When_AnnotationIsMissing_On_TestTemplate() { void should_NotFindContextProvider_When_AnnotationIsMissing_On_TestTemplate() {
assertThat(CurrentUserContext.getUserid()).isNotNull(); assertThat(CURRENT_USER_CONTEXT.getUserid()).isNotNull();
} }
@WithAccessId(user = "testtemplate") @WithAccessId(user = "testtemplate")
@TestTemplate @TestTemplate
void should_SetJaasSubject_When_AnnotationExists_On_TestTemplate() { void should_SetJaasSubject_When_AnnotationExists_On_TestTemplate() {
assertThat(CurrentUserContext.getUserid()).isEqualTo("testtemplate"); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo("testtemplate");
} }
@WithAccessId(user = "testtemplate1") @WithAccessId(user = "testtemplate1")
@ -212,7 +215,7 @@ class JaasExtensionTest {
@TestTemplate @TestTemplate
void should_SetMultipleJaasSubjects_When_MultipleAnnotationsExist_On_TestTemplate( void should_SetMultipleJaasSubjects_When_MultipleAnnotationsExist_On_TestTemplate(
WithAccessId accessId) { WithAccessId accessId) {
assertThat(CurrentUserContext.getUserid()).isEqualTo(accessId.user()); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(accessId.user());
} }
@WithAccessId(user = "testtemplate1", groups = "abc") @WithAccessId(user = "testtemplate1", groups = "abc")
@ -705,12 +708,12 @@ class JaasExtensionTest {
@Nested @Nested
class ConstructorWithoutAccessId { class ConstructorWithoutAccessId {
ConstructorWithoutAccessId() { ConstructorWithoutAccessId() {
assertThat(CurrentUserContext.getUserid()).isEqualTo(null); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo(null);
} }
@Test @Test
void should_NotSetJaasSubject_When_AnnotationIsMissing_On_Constructor() { void should_NotSetJaasSubject_When_AnnotationIsMissing_On_Constructor() {
assertThat(CurrentUserContext.getUserid()).isNull(); assertThat(CURRENT_USER_CONTEXT.getUserid()).isNull();
} }
} }
@ -718,12 +721,12 @@ class JaasExtensionTest {
class ConstructorWithAccessId { class ConstructorWithAccessId {
@WithAccessId(user = "constructor") @WithAccessId(user = "constructor")
ConstructorWithAccessId() { ConstructorWithAccessId() {
assertThat(CurrentUserContext.getUserid()).isEqualTo("constructor"); assertThat(CURRENT_USER_CONTEXT.getUserid()).isEqualTo("constructor");
} }
@Test @Test
void should_SetJaasSubject_When_AnnotationExists_On_Constructor() { void should_SetJaasSubject_When_AnnotationExists_On_Constructor() {
assertThat(CurrentUserContext.getUserid()).isNull(); assertThat(CURRENT_USER_CONTEXT.getUserid()).isNull();
} }
} }

View File

@ -0,0 +1,33 @@
package pro.taskana.common.api.security;
import java.util.List;
/**
* Provides the context information about the current (calling) user. The context is gathered from
* the JAAS subject.
*/
public interface CurrentUserContext {
/**
* Returns the userid of the current user.
*
* @return String the userid. null if there is no JAAS subject.
*/
public String getUserid();
/**
* Returns all groupIds of the current user.
*
* @return list containing all groupIds of the current user. Empty if the current user belongs to
* no groups or no JAAS Subject set.
*/
public List<String> getGroupIds();
/**
* Returns all accessIds of the current user. This combines the userId and all groupIds of the
* current user.
*
* @return list containing all accessIds of the current user. Empty if there is no JAAS subject.
*/
public List<String> getAccessIds();
}

View File

@ -1,4 +1,4 @@
package pro.taskana.common.internal.security; package pro.taskana.common.api.security;
import java.security.Principal; import java.security.Principal;
import java.security.acl.Group; import java.security.acl.Group;

View File

@ -1,4 +1,4 @@
package pro.taskana.common.internal.security; package pro.taskana.common.api.security;
import java.security.Principal; import java.security.Principal;

View File

@ -16,38 +16,37 @@ import javax.security.auth.Subject;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** import pro.taskana.common.api.security.CurrentUserContext;
* Provides the context information about the current (calling) user. The context is gathered from
* the JAAS subject. public class CurrentUserContextImpl implements CurrentUserContext {
*
* @author Holger Hagen
*/
public final class CurrentUserContext {
private static final String GET_UNIQUE_SECURITY_NAME_METHOD = "getUniqueSecurityName"; private static final String GET_UNIQUE_SECURITY_NAME_METHOD = "getUniqueSecurityName";
private static final String GET_CALLER_SUBJECT_METHOD = "getCallerSubject"; private static final String GET_CALLER_SUBJECT_METHOD = "getCallerSubject";
private static final String WSSUBJECT_CLASSNAME = "com.ibm.websphere.security.auth.WSSubject"; private static final String WSSUBJECT_CLASSNAME = "com.ibm.websphere.security.auth.WSSubject";
private static final Logger LOGGER = LoggerFactory.getLogger(CurrentUserContext.class); private static final Logger LOGGER = LoggerFactory.getLogger(CurrentUserContext.class);
private final boolean shouldUseLowerCaseForAccessIds;
private boolean runningOnWebSphere;
private static Boolean runningOnWebSphere = null; public CurrentUserContextImpl(boolean shouldUseLowerCaseForAccessIds) {
this.shouldUseLowerCaseForAccessIds = shouldUseLowerCaseForAccessIds;
private CurrentUserContext() {} try {
Class.forName(WSSUBJECT_CLASSNAME);
/** LOGGER.debug("WSSubject detected. Assuming that Taskana runs on IBM WebSphere.");
* Returns the userid of the current user. runningOnWebSphere = true;
* } catch (ClassNotFoundException e) {
* @return String the userid. null if there is no JAAS subject. LOGGER.debug("No WSSubject detected. Using JAAS subject further on.");
*/ runningOnWebSphere = false;
public static String getUserid() {
if (runningOnWebSphere()) {
return getUserIdFromWsSubject();
} else {
return getUserIdFromJaasSubject();
} }
} }
public static List<String> getGroupIds() { @Override
public String getUserid() {
return runningOnWebSphere ? getUserIdFromWsSubject() : getUserIdFromJaasSubject();
}
@Override
public List<String> getGroupIds() {
Subject subject = Subject.getSubject(AccessController.getContext()); Subject subject = Subject.getSubject(AccessController.getContext());
LOGGER.trace("Subject of caller: {}", subject); LOGGER.trace("Subject of caller: {}", subject);
if (subject != null) { if (subject != null) {
@ -56,14 +55,15 @@ public final class CurrentUserContext {
return groups.stream() return groups.stream()
.map(Principal::getName) .map(Principal::getName)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.map(CurrentUserContext::convertAccessId) .map(this::convertAccessId)
.collect(Collectors.toList()); .collect(Collectors.toList());
} }
LOGGER.trace("No groupIds found in subject!"); LOGGER.trace("No groupIds found in subject!");
return Collections.emptyList(); return Collections.emptyList();
} }
public static List<String> getAccessIds() { @Override
public List<String> getAccessIds() {
List<String> accessIds = new ArrayList<>(getGroupIds()); List<String> accessIds = new ArrayList<>(getGroupIds());
accessIds.add(getUserid()); accessIds.add(getUserid());
return accessIds; return accessIds;
@ -75,7 +75,7 @@ public final class CurrentUserContext {
* *
* @return the userid of the caller. If the userid could not be obtained, null is returned. * @return the userid of the caller. If the userid could not be obtained, null is returned.
*/ */
private static String getUserIdFromWsSubject() { private String getUserIdFromWsSubject() {
try { try {
Class<?> wsSubjectClass = Class.forName(WSSUBJECT_CLASSNAME); Class<?> wsSubjectClass = Class.forName(WSSUBJECT_CLASSNAME);
Method getCallerSubjectMethod = Method getCallerSubjectMethod =
@ -98,7 +98,7 @@ public final class CurrentUserContext {
LOGGER.debug( LOGGER.debug(
"Returning the unique security name of first public credential: {}", o)) "Returning the unique security name of first public credential: {}", o))
.map(Object::toString) .map(Object::toString)
.map(CurrentUserContext::convertAccessId) .map(this::convertAccessId)
.findFirst() .findFirst()
.orElse(null); .orElse(null);
} }
@ -108,26 +108,7 @@ public final class CurrentUserContext {
return null; return null;
} }
/** private String getUserIdFromJaasSubject() {
* Checks, whether Taskana is running on IBM WebSphere.
*
* @return true, if it is running on IBM WebSphere
*/
private static boolean runningOnWebSphere() {
if (runningOnWebSphere == null) {
try {
Class.forName(WSSUBJECT_CLASSNAME);
LOGGER.debug("WSSubject detected. Assuming that Taskana runs on IBM WebSphere.");
runningOnWebSphere = true;
} catch (ClassNotFoundException e) {
LOGGER.debug("No WSSubject detected. Using JAAS subject further on.");
runningOnWebSphere = false;
}
}
return runningOnWebSphere;
}
private static String getUserIdFromJaasSubject() {
Subject subject = Subject.getSubject(AccessController.getContext()); Subject subject = Subject.getSubject(AccessController.getContext());
LOGGER.trace("Subject of caller: {}", subject); LOGGER.trace("Subject of caller: {}", subject);
if (subject != null) { if (subject != null) {
@ -137,7 +118,7 @@ public final class CurrentUserContext {
.filter(principal -> !(principal instanceof Group)) .filter(principal -> !(principal instanceof Group))
.map(Principal::getName) .map(Principal::getName)
.filter(Objects::nonNull) .filter(Objects::nonNull)
.map(CurrentUserContext::convertAccessId) .map(this::convertAccessId)
.findFirst() .findFirst()
.orElse(null); .orElse(null);
} }
@ -145,12 +126,11 @@ public final class CurrentUserContext {
return null; return null;
} }
private static String convertAccessId(String accessId) { private String convertAccessId(String accessId) {
String toReturn = accessId; String toReturn = accessId;
// TODO: DAS IST DOOF if (shouldUseLowerCaseForAccessIds) {
// if (shouldUseLowerCaseForAccessIds()) { toReturn = accessId.toLowerCase();
// toReturn = accessId.toLowerCase(); }
// }
LOGGER.trace("Found AccessId '{}'. Returning AccessId '{}' ", accessId, toReturn); LOGGER.trace("Found AccessId '{}'. Returning AccessId '{}' ", accessId, toReturn);
return toReturn; return toReturn;
} }

View File

@ -6,7 +6,6 @@ import java.util.List;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import pro.taskana.TaskanaEngineConfiguration;
import pro.taskana.common.api.TaskanaEngine; import pro.taskana.common.api.TaskanaEngine;
import pro.taskana.common.api.TaskanaRole; import pro.taskana.common.api.TaskanaRole;
import pro.taskana.common.api.exceptions.InvalidArgumentException; import pro.taskana.common.api.exceptions.InvalidArgumentException;
@ -34,7 +33,7 @@ public class SimpleHistoryServiceImpl implements TaskanaHistory {
public void initialize(TaskanaEngine taskanaEngine) { public void initialize(TaskanaEngine taskanaEngine) {
this.taskanaHistoryEngine = getTaskanaEngine(taskanaEngine.getConfiguration()); this.taskanaHistoryEngine = getTaskanaEngine(taskanaEngine);
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug( LOGGER.debug(
@ -169,7 +168,7 @@ public class SimpleHistoryServiceImpl implements TaskanaHistory {
/* /*
* ATTENTION: This method exists for testing purposes. * ATTENTION: This method exists for testing purposes.
*/ */
TaskanaHistoryEngineImpl getTaskanaEngine(TaskanaEngineConfiguration taskanaEngineConfiguration) { TaskanaHistoryEngineImpl getTaskanaEngine(TaskanaEngine taskanaEngine) {
return TaskanaHistoryEngineImpl.createTaskanaEngine(taskanaEngineConfiguration); return TaskanaHistoryEngineImpl.createTaskanaEngine(taskanaEngine);
} }
} }

View File

@ -19,9 +19,9 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import pro.taskana.TaskanaEngineConfiguration; import pro.taskana.TaskanaEngineConfiguration;
import pro.taskana.common.api.TaskanaEngine;
import pro.taskana.common.api.TaskanaRole; import pro.taskana.common.api.TaskanaRole;
import pro.taskana.common.api.exceptions.NotAuthorizedException; import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.simplehistory.TaskanaHistoryEngine; import pro.taskana.simplehistory.TaskanaHistoryEngine;
import pro.taskana.simplehistory.impl.classification.ClassificationHistoryEventMapper; import pro.taskana.simplehistory.impl.classification.ClassificationHistoryEventMapper;
import pro.taskana.simplehistory.impl.classification.ClassificationHistoryQueryMapper; import pro.taskana.simplehistory.impl.classification.ClassificationHistoryQueryMapper;
@ -37,28 +37,30 @@ public class TaskanaHistoryEngineImpl implements TaskanaHistoryEngine {
protected static final ThreadLocal<Deque<SqlSessionManager>> SESSION_STACK = new ThreadLocal<>(); protected static final ThreadLocal<Deque<SqlSessionManager>> SESSION_STACK = new ThreadLocal<>();
private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaHistoryEngineImpl.class); private static final Logger LOGGER = LoggerFactory.getLogger(TaskanaHistoryEngineImpl.class);
private static final String DEFAULT = "default"; private static final String DEFAULT = "default";
protected SqlSessionManager sessionManager; private final SqlSessionManager sessionManager;
protected TransactionFactory transactionFactory; private final TaskanaEngineConfiguration taskanaEngineConfiguration;
protected TaskanaHistory taskanaHistoryService; private final TaskanaEngine taskanaEngine;
TaskanaEngineConfiguration taskanaEngineConfiguration; private TransactionFactory transactionFactory;
private TaskanaHistory taskanaHistoryService;
protected TaskanaHistoryEngineImpl(TaskanaEngineConfiguration taskanaEngineConfiguration) { protected TaskanaHistoryEngineImpl(TaskanaEngine taskanaEngine) {
this.taskanaEngineConfiguration = taskanaEngineConfiguration; this.taskanaEngineConfiguration = taskanaEngine.getConfiguration();
this.taskanaEngine = taskanaEngine;
createTransactionFactory(this.taskanaEngineConfiguration.getUseManagedTransactions()); createTransactionFactory(taskanaEngineConfiguration.getUseManagedTransactions());
this.sessionManager = createSqlSessionManager(); sessionManager = createSqlSessionManager();
} }
public static TaskanaHistoryEngineImpl createTaskanaEngine( public static TaskanaHistoryEngineImpl createTaskanaEngine(
TaskanaEngineConfiguration taskanaEngineConfiguration) { TaskanaEngine taskanaEngine) {
return new TaskanaHistoryEngineImpl(taskanaEngineConfiguration); return new TaskanaHistoryEngineImpl(taskanaEngine);
} }
@Override @Override
public TaskanaHistory getTaskanaHistoryService() { public TaskanaHistory getTaskanaHistoryService() {
if (taskanaHistoryService == null) { if (taskanaHistoryService == null) {
SimpleHistoryServiceImpl historyService = new SimpleHistoryServiceImpl(); SimpleHistoryServiceImpl historyService = new SimpleHistoryServiceImpl();
historyService.initialize(taskanaEngineConfiguration.buildTaskanaEngine()); historyService.initialize(taskanaEngine);
this.taskanaHistoryService = historyService; this.taskanaHistoryService = historyService;
} }
return this.taskanaHistoryService; return this.taskanaHistoryService;
@ -74,7 +76,8 @@ public class TaskanaHistoryEngineImpl implements TaskanaHistoryEngine {
.map(role -> getConfiguration().getRoleMap().get(role)) .map(role -> getConfiguration().getRoleMap().get(role))
.collect(HashSet::new, Set::addAll, Set::addAll); .collect(HashSet::new, Set::addAll, Set::addAll);
return CurrentUserContext.getAccessIds().stream().anyMatch(rolesMembers::contains); return taskanaEngine.getCurrentUserContext().getAccessIds().stream()
.anyMatch(rolesMembers::contains);
} }
public void checkRoleMembership(TaskanaRole... roles) throws NotAuthorizedException { public void checkRoleMembership(TaskanaRole... roles) throws NotAuthorizedException {
@ -82,12 +85,12 @@ public class TaskanaHistoryEngineImpl implements TaskanaHistoryEngine {
if (LOGGER.isDebugEnabled()) { if (LOGGER.isDebugEnabled()) {
LOGGER.debug( LOGGER.debug(
"Throwing NotAuthorizedException because accessIds {} are not member of roles {}", "Throwing NotAuthorizedException because accessIds {} are not member of roles {}",
CurrentUserContext.getAccessIds(), taskanaEngine.getCurrentUserContext().getAccessIds(),
Arrays.toString(roles)); Arrays.toString(roles));
} }
throw new NotAuthorizedException( throw new NotAuthorizedException(
"current user is not member of role(s) " + Arrays.toString(roles), "current user is not member of role(s) " + Arrays.toString(roles),
CurrentUserContext.getUserid()); taskanaEngine.getCurrentUserContext().getUserid());
} }
} }

View File

@ -55,7 +55,7 @@ public class HistoryCleanupJob extends AbstractTaskanaJob {
private final boolean allCompletedSameParentBusiness; private final boolean allCompletedSameParentBusiness;
TaskanaHistoryEngineImpl taskanaHistoryEngine = TaskanaHistoryEngineImpl taskanaHistoryEngine =
TaskanaHistoryEngineImpl.createTaskanaEngine(taskanaEngineImpl.getConfiguration()); TaskanaHistoryEngineImpl.createTaskanaEngine(taskanaEngineImpl);
private Instant firstRun = Instant.parse("2018-01-01T00:00:00Z"); private Instant firstRun = Instant.parse("2018-01-01T00:00:00Z");
private Duration runEvery = Duration.parse("P1D"); private Duration runEvery = Duration.parse("P1D");

View File

@ -114,9 +114,9 @@ public abstract class AbstractAccTest {
dataSource, dataSource,
false, false,
schemaName != null && !schemaName.isEmpty() ? schemaName : getSchemaName()); schemaName != null && !schemaName.isEmpty() ? schemaName : getSchemaName());
taskanaHistoryEngine = TaskanaHistoryEngineImpl.createTaskanaEngine(taskanaEngineConfiguration);
taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine(); taskanaEngine = taskanaEngineConfiguration.buildTaskanaEngine();
taskanaEngine.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT); taskanaEngine.setConnectionManagementMode(ConnectionManagementMode.AUTOCOMMIT);
taskanaHistoryEngine = TaskanaHistoryEngineImpl.createTaskanaEngine(taskanaEngine);
historyService = new SimpleHistoryServiceImpl(); historyService = new SimpleHistoryServiceImpl();
historyService.initialize(taskanaEngineConfiguration.buildTaskanaEngine()); historyService.initialize(taskanaEngineConfiguration.buildTaskanaEngine());

View File

@ -60,10 +60,8 @@ class SimpleHistoryServiceImplTest {
when(sqlSessionManagerMock.getMapper(WorkbasketHistoryEventMapper.class)) when(sqlSessionManagerMock.getMapper(WorkbasketHistoryEventMapper.class))
.thenReturn(workbasketHistoryEventMapperMock); .thenReturn(workbasketHistoryEventMapperMock);
when(taskanaHistoryEngineMock.getSqlSession()).thenReturn(sqlSessionManagerMock); when(taskanaHistoryEngineMock.getSqlSession()).thenReturn(sqlSessionManagerMock);
doReturn(taskanaHistoryEngineMock).when(cutSpy).getTaskanaEngine(taskanaEngineConfiguration); doReturn(taskanaHistoryEngineMock).when(cutSpy).getTaskanaEngine(taskanaEngine);
doReturn(taskanaEngine).when(taskanaEngineConfiguration).buildTaskanaEngine(); doReturn(taskanaEngine).when(taskanaEngineConfiguration).buildTaskanaEngine();
doReturn(taskanaEngineConfiguration).when(taskanaEngine).getConfiguration();
cutSpy.initialize(taskanaEngineConfiguration.buildTaskanaEngine()); cutSpy.initialize(taskanaEngineConfiguration.buildTaskanaEngine());
verify(sqlSessionManagerMock, times(3)).getMapper(any()); verify(sqlSessionManagerMock, times(3)).getMapper(any());

View File

@ -29,7 +29,6 @@ import pro.taskana.common.api.exceptions.DomainNotFoundException;
import pro.taskana.common.api.exceptions.InvalidArgumentException; import pro.taskana.common.api.exceptions.InvalidArgumentException;
import pro.taskana.common.api.exceptions.NotAuthorizedException; import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.internal.InternalTaskanaEngine; import pro.taskana.common.internal.InternalTaskanaEngine;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.common.internal.util.IdGenerator; import pro.taskana.common.internal.util.IdGenerator;
import pro.taskana.common.internal.util.LogSanitizer; import pro.taskana.common.internal.util.LogSanitizer;
import pro.taskana.common.internal.util.ObjectAttributeChangeDetector; import pro.taskana.common.internal.util.ObjectAttributeChangeDetector;
@ -151,7 +150,7 @@ public class ClassificationServiceImpl implements ClassificationService {
new ClassificationDeletedEvent( new ClassificationDeletedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_CLASSIFICATION_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_CLASSIFICATION_HISTORY_EVENT),
classification, classification,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
@ -237,7 +236,7 @@ public class ClassificationServiceImpl implements ClassificationService {
new ClassificationCreatedEvent( new ClassificationCreatedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_CLASSIFICATION_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_CLASSIFICATION_HISTORY_EVENT),
classificationImpl, classificationImpl,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
@ -290,7 +289,7 @@ public class ClassificationServiceImpl implements ClassificationService {
new ClassificationUpdatedEvent( new ClassificationUpdatedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_CLASSIFICATION_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_CLASSIFICATION_HISTORY_EVENT),
classificationImpl, classificationImpl,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
LOGGER.debug( LOGGER.debug(

View File

@ -5,6 +5,7 @@ import java.sql.SQLException;
import pro.taskana.TaskanaEngineConfiguration; import pro.taskana.TaskanaEngineConfiguration;
import pro.taskana.classification.api.ClassificationService; import pro.taskana.classification.api.ClassificationService;
import pro.taskana.common.api.exceptions.NotAuthorizedException; import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.api.security.CurrentUserContext;
import pro.taskana.monitor.api.MonitorService; import pro.taskana.monitor.api.MonitorService;
import pro.taskana.task.api.TaskService; import pro.taskana.task.api.TaskService;
import pro.taskana.workbasket.api.WorkbasketService; import pro.taskana.workbasket.api.WorkbasketService;
@ -114,6 +115,14 @@ public interface TaskanaEngine {
*/ */
void checkRoleMembership(TaskanaRole... roles) throws NotAuthorizedException; void checkRoleMembership(TaskanaRole... roles) throws NotAuthorizedException;
/**
* Returns the CurrentUserContext class.
*
* @return the CurrentUserContext
*/
CurrentUserContext getCurrentUserContext();
/** /**
* Connection management mode. Controls the connection handling of taskana * Connection management mode. Controls the connection handling of taskana
* *

View File

@ -41,11 +41,12 @@ import pro.taskana.common.api.exceptions.ConnectionNotSetException;
import pro.taskana.common.api.exceptions.NotAuthorizedException; import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.api.exceptions.SystemException; import pro.taskana.common.api.exceptions.SystemException;
import pro.taskana.common.api.exceptions.TaskanaRuntimeException; import pro.taskana.common.api.exceptions.TaskanaRuntimeException;
import pro.taskana.common.api.security.CurrentUserContext;
import pro.taskana.common.api.security.GroupPrincipal;
import pro.taskana.common.internal.configuration.DB; import pro.taskana.common.internal.configuration.DB;
import pro.taskana.common.internal.persistence.InstantTypeHandler; import pro.taskana.common.internal.persistence.InstantTypeHandler;
import pro.taskana.common.internal.persistence.MapTypeHandler; import pro.taskana.common.internal.persistence.MapTypeHandler;
import pro.taskana.common.internal.security.CurrentUserContext; import pro.taskana.common.internal.security.CurrentUserContextImpl;
import pro.taskana.common.internal.security.GroupPrincipal;
import pro.taskana.monitor.api.MonitorService; import pro.taskana.monitor.api.MonitorService;
import pro.taskana.monitor.internal.MonitorMapper; import pro.taskana.monitor.internal.MonitorMapper;
import pro.taskana.monitor.internal.MonitorServiceImpl; import pro.taskana.monitor.internal.MonitorServiceImpl;
@ -76,12 +77,13 @@ public class TaskanaEngineImpl implements TaskanaEngine {
private final CreateTaskPreprocessorManager createTaskPreprocessorManager; private final CreateTaskPreprocessorManager createTaskPreprocessorManager;
private final InternalTaskanaEngineImpl internalTaskanaEngineImpl; private final InternalTaskanaEngineImpl internalTaskanaEngineImpl;
private final WorkingDaysToDaysConverter workingDaysToDaysConverter; private final WorkingDaysToDaysConverter workingDaysToDaysConverter;
private final HistoryEventManager historyEventManager;
private final CurrentUserContext currentUserContext;
protected TaskanaEngineConfiguration taskanaEngineConfiguration; protected TaskanaEngineConfiguration taskanaEngineConfiguration;
protected TransactionFactory transactionFactory; protected TransactionFactory transactionFactory;
protected SqlSessionManager sessionManager; protected SqlSessionManager sessionManager;
protected ConnectionManagementMode mode = ConnectionManagementMode.PARTICIPATE; protected ConnectionManagementMode mode = ConnectionManagementMode.PARTICIPATE;
protected Connection connection = null; protected Connection connection = null;
private HistoryEventManager historyEventManager;
protected TaskanaEngineImpl(TaskanaEngineConfiguration taskanaEngineConfiguration) { protected TaskanaEngineImpl(TaskanaEngineConfiguration taskanaEngineConfiguration) {
this.taskanaEngineConfiguration = taskanaEngineConfiguration; this.taskanaEngineConfiguration = taskanaEngineConfiguration;
@ -96,6 +98,8 @@ public class TaskanaEngineImpl implements TaskanaEngine {
taskanaEngineConfiguration.isGermanPublicHolidaysEnabled(), taskanaEngineConfiguration.isGermanPublicHolidaysEnabled(),
taskanaEngineConfiguration.isCorpusChristiEnabled(), taskanaEngineConfiguration.isCorpusChristiEnabled(),
taskanaEngineConfiguration.getCustomHolidays()); taskanaEngineConfiguration.getCustomHolidays());
currentUserContext =
new CurrentUserContextImpl(TaskanaEngineConfiguration.shouldUseLowerCaseForAccessIds());
} }
public static TaskanaEngine createTaskanaEngine( public static TaskanaEngine createTaskanaEngine(
@ -205,7 +209,7 @@ public class TaskanaEngineImpl implements TaskanaEngine {
return true; return true;
} }
List<String> accessIds = CurrentUserContext.getAccessIds(); List<String> accessIds = currentUserContext.getAccessIds();
Set<String> rolesMembers = new HashSet<>(); Set<String> rolesMembers = new HashSet<>();
for (TaskanaRole role : roles) { for (TaskanaRole role : roles) {
rolesMembers.addAll(getConfiguration().getRoleMap().get(role)); rolesMembers.addAll(getConfiguration().getRoleMap().get(role));
@ -226,15 +230,20 @@ public class TaskanaEngineImpl implements TaskanaEngine {
String rolesAsString = Arrays.toString(roles); String rolesAsString = Arrays.toString(roles);
LOGGER.debug( LOGGER.debug(
"Throwing NotAuthorizedException because accessIds {} are not member of roles {}", "Throwing NotAuthorizedException because accessIds {} are not member of roles {}",
CurrentUserContext.getAccessIds(), currentUserContext.getAccessIds(),
rolesAsString); rolesAsString);
} }
throw new NotAuthorizedException( throw new NotAuthorizedException(
"current user is not member of role(s) " + Arrays.toString(roles), "current user is not member of role(s) " + Arrays.toString(roles),
CurrentUserContext.getUserid()); currentUserContext.getUserid());
} }
} }
@Override
public CurrentUserContext getCurrentUserContext() {
return currentUserContext;
}
/** /**
* This method creates the sqlSessionManager of myBatis. It integrates all the SQL mappers and * This method creates the sqlSessionManager of myBatis. It integrates all the SQL mappers and
* sets the databaseId attribute. * sets the databaseId attribute.

View File

@ -15,9 +15,8 @@ import pro.taskana.common.api.ScheduledJob;
import pro.taskana.common.api.TaskanaEngine; import pro.taskana.common.api.TaskanaEngine;
import pro.taskana.common.api.TaskanaRole; import pro.taskana.common.api.TaskanaRole;
import pro.taskana.common.api.exceptions.SystemException; import pro.taskana.common.api.exceptions.SystemException;
import pro.taskana.common.api.security.UserPrincipal;
import pro.taskana.common.internal.JobServiceImpl; import pro.taskana.common.internal.JobServiceImpl;
import pro.taskana.common.internal.TaskanaEngineImpl;
import pro.taskana.common.internal.security.UserPrincipal;
import pro.taskana.common.internal.transaction.TaskanaTransactionProvider; import pro.taskana.common.internal.transaction.TaskanaTransactionProvider;
import pro.taskana.task.internal.TaskServiceImpl; import pro.taskana.task.internal.TaskServiceImpl;
@ -25,12 +24,12 @@ import pro.taskana.task.internal.TaskServiceImpl;
public class JobRunner { public class JobRunner {
private static final Logger LOGGER = LoggerFactory.getLogger(TaskServiceImpl.class); private static final Logger LOGGER = LoggerFactory.getLogger(TaskServiceImpl.class);
private TaskanaEngineImpl taskanaEngine; private final TaskanaEngine taskanaEngine;
private JobServiceImpl jobService; private final JobServiceImpl jobService;
private TaskanaTransactionProvider<Object> txProvider; private TaskanaTransactionProvider<Object> txProvider;
public JobRunner(TaskanaEngine taskanaEngine) { public JobRunner(TaskanaEngine taskanaEngine) {
this.taskanaEngine = (TaskanaEngineImpl) taskanaEngine; this.taskanaEngine = taskanaEngine;
jobService = (JobServiceImpl) taskanaEngine.getJobService(); jobService = (JobServiceImpl) taskanaEngine.getJobService();
} }
@ -54,7 +53,7 @@ public class JobRunner {
private List<ScheduledJob> findAndLockJobsToRun() { private List<ScheduledJob> findAndLockJobsToRun() {
List<ScheduledJob> availableJobs = jobService.findJobsToRun(); List<ScheduledJob> availableJobs = jobService.findJobsToRun();
List<ScheduledJob> lockedJobs = new ArrayList<ScheduledJob>(); List<ScheduledJob> lockedJobs = new ArrayList<>();
for (ScheduledJob job : availableJobs) { for (ScheduledJob job : availableJobs) {
lockedJobs.add(lockJobTransactionally(job)); lockedJobs.add(lockJobTransactionally(job));
} }
@ -81,8 +80,7 @@ public class JobRunner {
} }
job.setLockedBy(hostAddress + " - " + Thread.currentThread().getName()); job.setLockedBy(hostAddress + " - " + Thread.currentThread().getName());
String owner = hostAddress + " - " + Thread.currentThread().getName(); String owner = hostAddress + " - " + Thread.currentThread().getName();
ScheduledJob lockedJob = jobService.lockJob(job, owner); return jobService.lockJob(job, owner);
return lockedJob;
} }
private void runJobTransactionally(ScheduledJob scheduledJob) { private void runJobTransactionally(ScheduledJob scheduledJob) {
@ -114,20 +112,16 @@ public class JobRunner {
} else { } else {
// we must establish admin context // we must establish admin context
try { try {
Subject.doAs( PrivilegedExceptionAction<Void> action =
getAdminSubject(), () -> {
new PrivilegedExceptionAction<Object>() { try {
@Override runScheduledJobImpl(scheduledJob);
public Object run() throws Exception { } catch (Exception e) {
try { throw new SystemException(String.format("could not run Job %s.", scheduledJob), e);
runScheduledJobImpl(scheduledJob);
} catch (Exception e) {
throw new SystemException(
String.format("could not run Job %s.", scheduledJob), e);
}
return null;
} }
}); return null;
};
Subject.doAs(getAdminSubject(), action);
} catch (PrivilegedActionException e) { } catch (PrivilegedActionException e) {
LOGGER.warn("Attempt to run job {} failed.", scheduledJob, e); LOGGER.warn("Attempt to run job {} failed.", scheduledJob, e);
} }

View File

@ -12,7 +12,6 @@ import pro.taskana.common.api.exceptions.InvalidArgumentException;
import pro.taskana.common.api.exceptions.NotAuthorizedException; import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.api.exceptions.SystemException; import pro.taskana.common.api.exceptions.SystemException;
import pro.taskana.common.internal.InternalTaskanaEngine; import pro.taskana.common.internal.InternalTaskanaEngine;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.common.internal.util.IdGenerator; import pro.taskana.common.internal.util.IdGenerator;
import pro.taskana.task.api.exceptions.TaskCommentNotFoundException; import pro.taskana.task.api.exceptions.TaskCommentNotFoundException;
import pro.taskana.task.api.exceptions.TaskNotFoundException; import pro.taskana.task.api.exceptions.TaskNotFoundException;
@ -59,7 +58,7 @@ class TaskCommentServiceImpl {
LOGGER.debug("entry to updateTaskComment (taskComment = {})", taskCommentToUpdate); LOGGER.debug("entry to updateTaskComment (taskComment = {})", taskCommentToUpdate);
String userId = CurrentUserContext.getUserid(); String userId = taskanaEngine.getEngine().getCurrentUserContext().getUserid();
TaskCommentImpl taskCommentImplToUpdate = (TaskCommentImpl) taskCommentToUpdate; TaskCommentImpl taskCommentImplToUpdate = (TaskCommentImpl) taskCommentToUpdate;
@ -132,7 +131,7 @@ class TaskCommentServiceImpl {
LOGGER.debug("entry to deleteTaskComment (taskComment = {}", taskCommentId); LOGGER.debug("entry to deleteTaskComment (taskComment = {}", taskCommentId);
String userId = CurrentUserContext.getUserid(); String userId = taskanaEngine.getEngine().getCurrentUserContext().getUserid();
try { try {
@ -241,7 +240,7 @@ class TaskCommentServiceImpl {
taskCommentImplToCreate.setModified(now); taskCommentImplToCreate.setModified(now);
taskCommentImplToCreate.setCreated(now); taskCommentImplToCreate.setCreated(now);
String creator = CurrentUserContext.getUserid(); String creator = taskanaEngine.getEngine().getCurrentUserContext().getUserid();
if (taskanaEngine.getEngine().getConfiguration().isSecurityEnabled() && creator == null) { if (taskanaEngine.getEngine().getConfiguration().isSecurityEnabled() && creator == null) {
throw new SystemException( throw new SystemException(
"TaskanaSecurity is enabled, but the current UserId is" "TaskanaSecurity is enabled, but the current UserId is"

View File

@ -18,7 +18,6 @@ import pro.taskana.common.api.exceptions.SystemException;
import pro.taskana.common.api.exceptions.TaskanaRuntimeException; import pro.taskana.common.api.exceptions.TaskanaRuntimeException;
import pro.taskana.common.internal.InternalTaskanaEngine; import pro.taskana.common.internal.InternalTaskanaEngine;
import pro.taskana.common.internal.configuration.DB; import pro.taskana.common.internal.configuration.DB;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.task.api.CallbackState; import pro.taskana.task.api.CallbackState;
import pro.taskana.task.api.ObjectReferenceQuery; import pro.taskana.task.api.ObjectReferenceQuery;
import pro.taskana.task.api.TaskCustomField; import pro.taskana.task.api.TaskCustomField;
@ -1604,7 +1603,7 @@ public class TaskQueryImpl implements TaskQuery {
this.accessIdIn = null; this.accessIdIn = null;
} else if (this.accessIdIn == null) { } else if (this.accessIdIn == null) {
String[] accessIds = new String[0]; String[] accessIds = new String[0];
List<String> ucAccessIds = CurrentUserContext.getAccessIds(); List<String> ucAccessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();
if (!ucAccessIds.isEmpty()) { if (!ucAccessIds.isEmpty()) {
accessIds = new String[ucAccessIds.size()]; accessIds = new String[ucAccessIds.size()];
accessIds = ucAccessIds.toArray(accessIds); accessIds = ucAccessIds.toArray(accessIds);

View File

@ -29,7 +29,6 @@ import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.api.exceptions.SystemException; import pro.taskana.common.api.exceptions.SystemException;
import pro.taskana.common.api.exceptions.TaskanaException; import pro.taskana.common.api.exceptions.TaskanaException;
import pro.taskana.common.internal.InternalTaskanaEngine; import pro.taskana.common.internal.InternalTaskanaEngine;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.common.internal.util.CheckedConsumer; import pro.taskana.common.internal.util.CheckedConsumer;
import pro.taskana.common.internal.util.IdGenerator; import pro.taskana.common.internal.util.IdGenerator;
import pro.taskana.common.internal.util.ObjectAttributeChangeDetector; import pro.taskana.common.internal.util.ObjectAttributeChangeDetector;
@ -243,7 +242,7 @@ public class TaskServiceImpl implements TaskService {
new TaskCreatedEvent( new TaskCreatedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT),
task, task,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
} catch (PersistenceException e) { } catch (PersistenceException e) {
@ -299,13 +298,13 @@ public class TaskServiceImpl implements TaskService {
String workbasketId = resultTask.getWorkbasketSummary().getId(); String workbasketId = resultTask.getWorkbasketSummary().getId();
List<WorkbasketSummary> workbaskets = query.idIn(workbasketId).list(); List<WorkbasketSummary> workbaskets = query.idIn(workbasketId).list();
if (workbaskets.isEmpty()) { if (workbaskets.isEmpty()) {
String currentUser = CurrentUserContext.getUserid(); String currentUser = taskanaEngine.getEngine().getCurrentUserContext().getUserid();
throw new NotAuthorizedException( throw new NotAuthorizedException(
"The current user " "The current user "
+ currentUser + currentUser
+ " has no read permission for workbasket " + " has no read permission for workbasket "
+ workbasketId, + workbasketId,
CurrentUserContext.getUserid()); taskanaEngine.getEngine().getCurrentUserContext().getUserid());
} else { } else {
resultTask.setWorkbasketSummary(workbaskets.get(0)); resultTask.setWorkbasketSummary(workbaskets.get(0));
} }
@ -424,7 +423,7 @@ public class TaskServiceImpl implements TaskService {
throws InvalidArgumentException, TaskNotFoundException, ConcurrencyException, throws InvalidArgumentException, TaskNotFoundException, ConcurrencyException,
NotAuthorizedException, AttachmentPersistenceException, InvalidStateException, NotAuthorizedException, AttachmentPersistenceException, InvalidStateException,
ClassificationNotFoundException { ClassificationNotFoundException {
String userId = CurrentUserContext.getUserid(); String userId = taskanaEngine.getEngine().getCurrentUserContext().getUserid();
LOGGER.debug("entry to updateTask(task = {}, userId = {})", task, userId); LOGGER.debug("entry to updateTask(task = {}, userId = {})", task, userId);
TaskImpl newTaskImpl = (TaskImpl) task; TaskImpl newTaskImpl = (TaskImpl) task;
TaskImpl oldTaskImpl; TaskImpl oldTaskImpl;
@ -452,7 +451,7 @@ public class TaskServiceImpl implements TaskService {
new TaskUpdatedEvent( new TaskUpdatedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT),
task, task,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
changeDetails)); changeDetails));
} }
@ -816,7 +815,7 @@ public class TaskServiceImpl implements TaskService {
new TaskCancelledEvent( new TaskCancelledEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT),
cancelledTask, cancelledTask,
CurrentUserContext.getUserid())); taskanaEngine.getEngine().getCurrentUserContext().getUserid()));
} }
} finally { } finally {
taskanaEngine.returnConnection(); taskanaEngine.returnConnection();
@ -844,7 +843,7 @@ public class TaskServiceImpl implements TaskService {
new TaskTerminatedEvent( new TaskTerminatedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT),
terminatedTask, terminatedTask,
CurrentUserContext.getUserid())); taskanaEngine.getEngine().getCurrentUserContext().getUserid()));
} }
} finally { } finally {
@ -910,7 +909,7 @@ public class TaskServiceImpl implements TaskService {
taskanaEngine.openConnection(); taskanaEngine.openConnection();
Set<String> adminAccessIds = Set<String> adminAccessIds =
taskanaEngine.getEngine().getConfiguration().getRoleMap().get(TaskanaRole.ADMIN); taskanaEngine.getEngine().getConfiguration().getRoleMap().get(TaskanaRole.ADMIN);
if (adminAccessIds.contains(CurrentUserContext.getUserid())) { if (adminAccessIds.contains(taskanaEngine.getEngine().getCurrentUserContext().getUserid())) {
serviceLevelHandler.refreshPriorityAndDueDatesOfTasks( serviceLevelHandler.refreshPriorityAndDueDatesOfTasks(
tasks, serviceLevelChanged, priorityChanged); tasks, serviceLevelChanged, priorityChanged);
} else { } else {
@ -949,10 +948,10 @@ public class TaskServiceImpl implements TaskService {
} else { } else {
List<String> taskIds = List<String> taskIds =
existingTasks.stream().map(MinimalTaskSummary::getTaskId).collect(Collectors.toList()); existingTasks.stream().map(MinimalTaskSummary::getTaskId).collect(Collectors.toList());
List<String> accessIds = CurrentUserContext.getAccessIds(); List<String> accessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();
List<String> taskIdsNotAuthorizedFor = List<String> taskIdsNotAuthorizedFor =
taskMapper.filterTaskIdsNotAuthorizedFor(taskIds, accessIds); taskMapper.filterTaskIdsNotAuthorizedFor(taskIds, accessIds);
String userId = CurrentUserContext.getUserid(); String userId = taskanaEngine.getEngine().getCurrentUserContext().getUserid();
for (String taskId : taskIdsNotAuthorizedFor) { for (String taskId : taskIdsNotAuthorizedFor) {
bulkLog.addError( bulkLog.addError(
taskId, taskId,
@ -1056,9 +1055,9 @@ public class TaskServiceImpl implements TaskService {
if (!forced) { if (!forced) {
filteredSummaries = filteredSummaries =
filteredSummaries.filter( filteredSummaries.filter(
addErrorToBulkLog(TaskServiceImpl::checkPreconditionsForCompleteTask, bulkLog)); addErrorToBulkLog(this::checkPreconditionsForCompleteTask, bulkLog));
} else { } else {
String userId = CurrentUserContext.getUserid(); String userId = taskanaEngine.getEngine().getCurrentUserContext().getUserid();
filteredSummaries = filteredSummaries =
filteredSummaries.filter( filteredSummaries.filter(
addErrorToBulkLog( addErrorToBulkLog(
@ -1148,7 +1147,10 @@ public class TaskServiceImpl implements TaskService {
task.setCompleted(now); task.setCompleted(now);
task.setState(targetState); task.setState(targetState);
taskMapper.update(task); taskMapper.update(task);
LOGGER.debug("Task '{}' cancelled by user '{}'.", taskId, CurrentUserContext.getUserid()); LOGGER.debug(
"Task '{}' cancelled by user '{}'.",
taskId,
taskanaEngine.getEngine().getCurrentUserContext().getUserid());
return task; return task;
} }
@ -1180,7 +1182,7 @@ public class TaskServiceImpl implements TaskService {
private Task claim(String taskId, boolean forceClaim) private Task claim(String taskId, boolean forceClaim)
throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, throws TaskNotFoundException, InvalidStateException, InvalidOwnerException,
NotAuthorizedException { NotAuthorizedException {
String userId = CurrentUserContext.getUserid(); String userId = taskanaEngine.getEngine().getCurrentUserContext().getUserid();
LOGGER.debug( LOGGER.debug(
"entry to claim(id = {}, userId = {}, forceClaim = {})", taskId, userId, forceClaim); "entry to claim(id = {}, userId = {}, forceClaim = {})", taskId, userId, forceClaim);
TaskImpl task; TaskImpl task;
@ -1198,7 +1200,7 @@ public class TaskServiceImpl implements TaskService {
new TaskClaimedEvent( new TaskClaimedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT),
task, task,
CurrentUserContext.getUserid())); taskanaEngine.getEngine().getCurrentUserContext().getUserid()));
} }
} finally { } finally {
taskanaEngine.returnConnection(); taskanaEngine.returnConnection();
@ -1222,7 +1224,7 @@ public class TaskServiceImpl implements TaskService {
task.setOwner(userId); task.setOwner(userId);
} }
private static void checkPreconditionsForClaimTask(TaskSummary task, boolean forced) private void checkPreconditionsForClaimTask(TaskSummary task, boolean forced)
throws InvalidStateException, InvalidOwnerException { throws InvalidStateException, InvalidOwnerException {
TaskState state = task.getState(); TaskState state = task.getState();
if (!state.in(TaskState.READY, TaskState.CLAIMED)) { if (!state.in(TaskState.READY, TaskState.CLAIMED)) {
@ -1231,7 +1233,7 @@ public class TaskServiceImpl implements TaskService {
} }
if (!forced if (!forced
&& state == TaskState.CLAIMED && state == TaskState.CLAIMED
&& !task.getOwner().equals(CurrentUserContext.getUserid())) { && !task.getOwner().equals(taskanaEngine.getEngine().getCurrentUserContext().getUserid())) {
throw new InvalidOwnerException( throw new InvalidOwnerException(
String.format(TASK_WITH_ID_IS_ALREADY_CLAIMED_BY, task.getId(), task.getOwner())); String.format(TASK_WITH_ID_IS_ALREADY_CLAIMED_BY, task.getId(), task.getOwner()));
} }
@ -1250,23 +1252,29 @@ public class TaskServiceImpl implements TaskService {
} }
} }
private static void checkPreconditionsForCompleteTask(TaskSummary task) private void checkPreconditionsForCompleteTask(TaskSummary task)
throws InvalidStateException, InvalidOwnerException { throws InvalidStateException, InvalidOwnerException {
if (taskIsNotClaimed(task)) { if (taskIsNotClaimed(task)) {
throw new InvalidStateException( throw new InvalidStateException(
String.format(TASK_WITH_ID_HAS_TO_BE_CLAIMED_BEFORE, task.getId())); String.format(TASK_WITH_ID_HAS_TO_BE_CLAIMED_BEFORE, task.getId()));
} else if (!CurrentUserContext.getAccessIds().contains(task.getOwner())) { } else if (!taskanaEngine
.getEngine()
.getCurrentUserContext()
.getAccessIds()
.contains(task.getOwner())) {
throw new InvalidOwnerException( throw new InvalidOwnerException(
String.format( String.format(
"Owner of task %s is %s, but current user is %s ", "Owner of task %s is %s, but current user is %s ",
task.getId(), task.getOwner(), CurrentUserContext.getUserid())); task.getId(),
task.getOwner(),
taskanaEngine.getEngine().getCurrentUserContext().getUserid()));
} }
} }
private Task cancelClaim(String taskId, boolean forceUnclaim) private Task cancelClaim(String taskId, boolean forceUnclaim)
throws TaskNotFoundException, InvalidStateException, InvalidOwnerException, throws TaskNotFoundException, InvalidStateException, InvalidOwnerException,
NotAuthorizedException { NotAuthorizedException {
String userId = CurrentUserContext.getUserid(); String userId = taskanaEngine.getEngine().getCurrentUserContext().getUserid();
LOGGER.debug( LOGGER.debug(
"entry to cancelClaim(taskId = {}), userId = {}, forceUnclaim = {})", "entry to cancelClaim(taskId = {}), userId = {}, forceUnclaim = {})",
taskId, taskId,
@ -1298,7 +1306,7 @@ public class TaskServiceImpl implements TaskService {
new TaskClaimCancelledEvent( new TaskClaimCancelledEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT),
task, task,
CurrentUserContext.getUserid())); taskanaEngine.getEngine().getCurrentUserContext().getUserid()));
} }
} finally { } finally {
taskanaEngine.returnConnection(); taskanaEngine.returnConnection();
@ -1310,7 +1318,7 @@ public class TaskServiceImpl implements TaskService {
private Task completeTask(String taskId, boolean isForced) private Task completeTask(String taskId, boolean isForced)
throws TaskNotFoundException, InvalidOwnerException, InvalidStateException, throws TaskNotFoundException, InvalidOwnerException, InvalidStateException,
NotAuthorizedException { NotAuthorizedException {
String userId = CurrentUserContext.getUserid(); String userId = taskanaEngine.getEngine().getCurrentUserContext().getUserid();
LOGGER.debug( LOGGER.debug(
"entry to completeTask(id = {}, userId = {}, isForced = {})", taskId, userId, isForced); "entry to completeTask(id = {}, userId = {}, isForced = {})", taskId, userId, isForced);
TaskImpl task; TaskImpl task;
@ -1339,7 +1347,7 @@ public class TaskServiceImpl implements TaskService {
new TaskCompletedEvent( new TaskCompletedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT),
task, task,
CurrentUserContext.getUserid())); taskanaEngine.getEngine().getCurrentUserContext().getUserid()));
} }
} finally { } finally {
taskanaEngine.returnConnection(); taskanaEngine.returnConnection();
@ -1491,7 +1499,7 @@ public class TaskServiceImpl implements TaskService {
task1.setRead(false); task1.setRead(false);
task1.setTransferred(false); task1.setTransferred(false);
String creator = CurrentUserContext.getUserid(); String creator = taskanaEngine.getEngine().getCurrentUserContext().getUserid();
if (taskanaEngine.getEngine().getConfiguration().isSecurityEnabled() && creator == null) { if (taskanaEngine.getEngine().getConfiguration().isSecurityEnabled() && creator == null) {
throw new SystemException( throw new SystemException(
"TaskanaSecurity is enabled, but the current UserId is NULL while creating a Task."); "TaskanaSecurity is enabled, but the current UserId is NULL while creating a Task.");
@ -1553,7 +1561,12 @@ public class TaskServiceImpl implements TaskService {
List<String> updateClaimedTaskIds = new ArrayList<>(); List<String> updateClaimedTaskIds = new ArrayList<>();
List<TaskSummary> taskSummaryList = List<TaskSummary> taskSummaryList =
taskSummaries taskSummaries
.peek(summary -> completeActionsOnTask(summary, CurrentUserContext.getUserid(), now)) .peek(
summary ->
completeActionsOnTask(
summary,
taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
now))
.peek(summary -> taskIds.add(summary.getId())) .peek(summary -> taskIds.add(summary.getId()))
.peek( .peek(
summary -> { summary -> {
@ -1914,6 +1927,6 @@ public class TaskServiceImpl implements TaskService {
new TaskCompletedEvent( new TaskCompletedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_HISTORY_EVENT),
task, task,
CurrentUserContext.getUserid()))); taskanaEngine.getEngine().getCurrentUserContext().getUserid())));
} }
} }

View File

@ -15,7 +15,6 @@ import pro.taskana.common.api.exceptions.InvalidArgumentException;
import pro.taskana.common.api.exceptions.NotAuthorizedException; import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.api.exceptions.TaskanaException; import pro.taskana.common.api.exceptions.TaskanaException;
import pro.taskana.common.internal.InternalTaskanaEngine; import pro.taskana.common.internal.InternalTaskanaEngine;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.common.internal.util.IdGenerator; import pro.taskana.common.internal.util.IdGenerator;
import pro.taskana.spi.history.api.events.task.TaskTransferredEvent; import pro.taskana.spi.history.api.events.task.TaskTransferredEvent;
import pro.taskana.spi.history.internal.HistoryEventManager; import pro.taskana.spi.history.internal.HistoryEventManager;
@ -357,7 +356,7 @@ public class TaskTransferrer {
currentTaskId, currentTaskId,
new NotAuthorizedException( new NotAuthorizedException(
"The workbasket of this task got not TRANSFER permissions. TaskId=" + currentTaskId, "The workbasket of this task got not TRANSFER permissions. TaskId=" + currentTaskId,
CurrentUserContext.getUserid())); taskanaEngine.getEngine().getCurrentUserContext().getUserid()));
taskIdIterator.remove(); taskIdIterator.remove();
} }
} }
@ -372,7 +371,7 @@ public class TaskTransferrer {
task, task,
oldWorkbasketSummary, oldWorkbasketSummary,
newWorkbasketSummary, newWorkbasketSummary,
CurrentUserContext.getUserid())); taskanaEngine.getEngine().getCurrentUserContext().getUserid()));
} }
private void updateTasksToBeTransferred( private void updateTasksToBeTransferred(

View File

@ -16,7 +16,6 @@ import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.api.exceptions.SystemException; import pro.taskana.common.api.exceptions.SystemException;
import pro.taskana.common.api.exceptions.TaskanaRuntimeException; import pro.taskana.common.api.exceptions.TaskanaRuntimeException;
import pro.taskana.common.internal.InternalTaskanaEngine; import pro.taskana.common.internal.InternalTaskanaEngine;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.workbasket.api.WorkbasketCustomField; import pro.taskana.workbasket.api.WorkbasketCustomField;
import pro.taskana.workbasket.api.WorkbasketPermission; import pro.taskana.workbasket.api.WorkbasketPermission;
import pro.taskana.workbasket.api.WorkbasketQuery; import pro.taskana.workbasket.api.WorkbasketQuery;
@ -666,7 +665,7 @@ public class WorkbasketQueryImpl implements WorkbasketQuery {
// might already be set by accessIdsHavePermission // might already be set by accessIdsHavePermission
if (this.accessId == null) { if (this.accessId == null) {
String[] accessIds = new String[0]; String[] accessIds = new String[0];
List<String> ucAccessIds = CurrentUserContext.getAccessIds(); List<String> ucAccessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();
if (!ucAccessIds.isEmpty()) { if (!ucAccessIds.isEmpty()) {
accessIds = ucAccessIds.toArray(accessIds); accessIds = ucAccessIds.toArray(accessIds);
} }

View File

@ -21,7 +21,6 @@ import pro.taskana.common.api.exceptions.InvalidArgumentException;
import pro.taskana.common.api.exceptions.NotAuthorizedException; import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.api.exceptions.TaskanaException; import pro.taskana.common.api.exceptions.TaskanaException;
import pro.taskana.common.internal.InternalTaskanaEngine; import pro.taskana.common.internal.InternalTaskanaEngine;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.common.internal.util.IdGenerator; import pro.taskana.common.internal.util.IdGenerator;
import pro.taskana.common.internal.util.ObjectAttributeChangeDetector; import pro.taskana.common.internal.util.ObjectAttributeChangeDetector;
import pro.taskana.spi.history.api.events.workbasket.WorkbasketAccessItemCreatedEvent; import pro.taskana.spi.history.api.events.workbasket.WorkbasketAccessItemCreatedEvent;
@ -163,7 +162,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
new WorkbasketCreatedEvent( new WorkbasketCreatedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT),
newWorkbasket, newWorkbasket,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
LOGGER.debug("Method createWorkbasket() created Workbasket '{}'", workbasket); LOGGER.debug("Method createWorkbasket() created Workbasket '{}'", workbasket);
@ -216,7 +215,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
new WorkbasketUpdatedEvent( new WorkbasketUpdatedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT),
workbasketToUpdate, workbasketToUpdate,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
LOGGER.debug( LOGGER.debug(
@ -285,7 +284,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
new WorkbasketAccessItemCreatedEvent( new WorkbasketAccessItemCreatedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT),
wb, wb,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
LOGGER.debug( LOGGER.debug(
@ -345,7 +344,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
new WorkbasketAccessItemUpdatedEvent( new WorkbasketAccessItemUpdatedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT),
workbasket, workbasket,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
@ -384,7 +383,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
new WorkbasketAccessItemDeletedEvent( new WorkbasketAccessItemDeletedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT),
workbasket, workbasket,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
@ -413,7 +412,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
return; return;
} }
List<String> accessIds = CurrentUserContext.getAccessIds(); List<String> accessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();
WorkbasketAccessItem wbAcc = WorkbasketAccessItem wbAcc =
workbasketAccessMapper.findByWorkbasketAndAccessId(workbasketId, accessIds); workbasketAccessMapper.findByWorkbasketAndAccessId(workbasketId, accessIds);
if (wbAcc == null) { if (wbAcc == null) {
@ -423,7 +422,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
+ "' on workbasket '" + "' on workbasket '"
+ workbasketId + workbasketId
+ "' is needed.", + "' is needed.",
CurrentUserContext.getUserid()); taskanaEngine.getEngine().getCurrentUserContext().getUserid());
} }
List<WorkbasketPermission> grantedPermissions = List<WorkbasketPermission> grantedPermissions =
@ -438,7 +437,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
+ "' on workbasket '" + "' on workbasket '"
+ workbasketId + workbasketId
+ "' is needed.", + "' is needed.",
CurrentUserContext.getUserid()); taskanaEngine.getEngine().getCurrentUserContext().getUserid());
} }
} }
} finally { } finally {
@ -464,7 +463,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
if (skipAuthorizationCheck(requestedPermissions)) { if (skipAuthorizationCheck(requestedPermissions)) {
return; return;
} }
List<String> accessIds = CurrentUserContext.getAccessIds(); List<String> accessIds = taskanaEngine.getEngine().getCurrentUserContext().getAccessIds();
WorkbasketAccessItem wbAcc = WorkbasketAccessItem wbAcc =
workbasketAccessMapper.findByWorkbasketKeyDomainAndAccessId( workbasketAccessMapper.findByWorkbasketKeyDomainAndAccessId(
workbasketKey, domain, accessIds); workbasketKey, domain, accessIds);
@ -477,7 +476,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
+ "' and domain '" + "' and domain '"
+ domain + domain
+ "' is needed.", + "' is needed.",
CurrentUserContext.getUserid()); taskanaEngine.getEngine().getCurrentUserContext().getUserid());
} }
List<WorkbasketPermission> grantedPermissions = List<WorkbasketPermission> grantedPermissions =
this.getPermissionsFromWorkbasketAccessItem(wbAcc); this.getPermissionsFromWorkbasketAccessItem(wbAcc);
@ -493,7 +492,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
+ "' and domain '" + "' and domain '"
+ domain + domain
+ "' is needed.", + "' is needed.",
CurrentUserContext.getUserid()); taskanaEngine.getEngine().getCurrentUserContext().getUserid());
} }
} }
} finally { } finally {
@ -562,7 +561,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
new WorkbasketAccessItemsUpdatedEvent( new WorkbasketAccessItemsUpdatedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT),
workbasket, workbasket,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
} finally { } finally {
@ -594,7 +593,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
public List<WorkbasketPermission> getPermissionsForWorkbasket(String workbasketId) { public List<WorkbasketPermission> getPermissionsForWorkbasket(String workbasketId) {
WorkbasketAccessItem wbAcc = WorkbasketAccessItem wbAcc =
workbasketAccessMapper.findByWorkbasketAndAccessId( workbasketAccessMapper.findByWorkbasketAndAccessId(
workbasketId, CurrentUserContext.getAccessIds()); workbasketId, taskanaEngine.getEngine().getCurrentUserContext().getAccessIds());
return this.getPermissionsFromWorkbasketAccessItem(wbAcc); return this.getPermissionsFromWorkbasketAccessItem(wbAcc);
} }
@ -707,7 +706,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
new WorkbasketDistributionTargetsUpdatedEvent( new WorkbasketDistributionTargetsUpdatedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT),
sourceWorkbasket, sourceWorkbasket,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
} }
@ -757,7 +756,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
new WorkbasketDistributionTargetAddedEvent( new WorkbasketDistributionTargetAddedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT),
sourceWorkbasket, sourceWorkbasket,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
LOGGER.debug( LOGGER.debug(
@ -806,7 +805,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
new WorkbasketDistributionTargetRemovedEvent( new WorkbasketDistributionTargetRemovedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT),
workbasket, workbasket,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
} }
@ -887,7 +886,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
new WorkbasketDeletedEvent( new WorkbasketDeletedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT),
workbasketToDelete, workbasketToDelete,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
} else { } else {
@ -1040,7 +1039,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
new WorkbasketAccessItemDeletedEvent( new WorkbasketAccessItemDeletedEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT),
workbasket, workbasket,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
details)); details));
} }
} }
@ -1212,7 +1211,7 @@ public class WorkbasketServiceImpl implements WorkbasketService {
new WorkbasketMarkedForDeletionEvent( new WorkbasketMarkedForDeletionEvent(
IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT), IdGenerator.generateWithPrefix(ID_PREFIX_WORKBASKET_HISTORY_EVENT),
workbasket, workbasket,
CurrentUserContext.getUserid(), taskanaEngine.getEngine().getCurrentUserContext().getUserid(),
null)); null));
} }
} finally { } finally {

View File

@ -17,7 +17,6 @@ import pro.taskana.common.api.BulkOperationResults;
import pro.taskana.common.api.exceptions.InvalidArgumentException; import pro.taskana.common.api.exceptions.InvalidArgumentException;
import pro.taskana.common.api.exceptions.NotAuthorizedException; import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.api.exceptions.TaskanaException; import pro.taskana.common.api.exceptions.TaskanaException;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.common.test.security.JaasExtension; import pro.taskana.common.test.security.JaasExtension;
import pro.taskana.common.test.security.WithAccessId; import pro.taskana.common.test.security.WithAccessId;
import pro.taskana.task.api.TaskService; import pro.taskana.task.api.TaskService;
@ -160,7 +159,7 @@ class CompleteTaskAccTest extends AbstractAccTest {
Task claimedTask = TASK_SERVICE.claim(createdTask.getId()); Task claimedTask = TASK_SERVICE.claim(createdTask.getId());
assertThat(claimedTask.getOwner()).isNotNull(); assertThat(claimedTask.getOwner()).isNotNull();
assertThat(CurrentUserContext.getUserid()).isEqualTo(claimedTask.getOwner()); assertThat(taskanaEngine.getCurrentUserContext().getUserid()).isEqualTo(claimedTask.getOwner());
assertThat(claimedTask.getClaimed()).isNotNull(); assertThat(claimedTask.getClaimed()).isNotNull();
assertThat(before).isBeforeOrEqualTo(claimedTask.getClaimed()); assertThat(before).isBeforeOrEqualTo(claimedTask.getClaimed());
assertThat(claimedTask.getCreated()).isBeforeOrEqualTo(claimedTask.getClaimed()); assertThat(claimedTask.getCreated()).isBeforeOrEqualTo(claimedTask.getClaimed());
@ -184,7 +183,8 @@ class CompleteTaskAccTest extends AbstractAccTest {
Instant beforeForceClaim = Instant.now(); Instant beforeForceClaim = Instant.now();
Task taskAfterClaim = TASK_SERVICE.forceClaim(createdTask.getId()); Task taskAfterClaim = TASK_SERVICE.forceClaim(createdTask.getId());
assertThat(taskAfterClaim.getOwner()).isEqualTo(CurrentUserContext.getUserid()); assertThat(taskAfterClaim.getOwner())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
assertThat(beforeForceClaim) assertThat(beforeForceClaim)
.isBeforeOrEqualTo(taskAfterClaim.getModified()) .isBeforeOrEqualTo(taskAfterClaim.getModified())
.isBeforeOrEqualTo(taskAfterClaim.getClaimed()); .isBeforeOrEqualTo(taskAfterClaim.getClaimed());

View File

@ -18,7 +18,6 @@ import org.junit.jupiter.api.extension.ExtendWith;
import pro.taskana.common.api.exceptions.InvalidArgumentException; import pro.taskana.common.api.exceptions.InvalidArgumentException;
import pro.taskana.common.api.exceptions.NotAuthorizedException; import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.internal.TaskanaEngineProxy; import pro.taskana.common.internal.TaskanaEngineProxy;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.common.test.security.JaasExtension; import pro.taskana.common.test.security.JaasExtension;
import pro.taskana.common.test.security.WithAccessId; import pro.taskana.common.test.security.WithAccessId;
import pro.taskana.task.api.TaskCustomField; import pro.taskana.task.api.TaskCustomField;
@ -70,7 +69,8 @@ class CreateTaskAccTest extends AbstractAccTest {
Instant expectedPlanned = moveForwardToWorkingDay(createdTask.getCreated()); Instant expectedPlanned = moveForwardToWorkingDay(createdTask.getCreated());
assertThat(createdTask).isNotNull(); assertThat(createdTask).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
assertThat(createdTask.getOwner()).isEqualTo("user-1-1"); assertThat(createdTask.getOwner()).isEqualTo("user-1-1");
assertThat(createdTask.getWorkbasketKey()).isEqualTo("USER-1-1"); assertThat(createdTask.getWorkbasketKey()).isEqualTo("USER-1-1");
assertThat(createdTask.getName()).isEqualTo("T-Vertragstermin VERA"); assertThat(createdTask.getName()).isEqualTo("T-Vertragstermin VERA");
@ -93,7 +93,7 @@ class CreateTaskAccTest extends AbstractAccTest {
@Test @Test
void should_CreateTask_When_ObjectReferenceSystemAndSystemInstanceIsNull() throws Exception { void should_CreateTask_When_ObjectReferenceSystemAndSystemInstanceIsNull() throws Exception {
String currentUser = CurrentUserContext.getUserid(); String currentUser = taskanaEngine.getCurrentUserContext().getUserid();
Task newTask = taskService.newTask("USER-1-1", "DOMAIN_A"); Task newTask = taskService.newTask("USER-1-1", "DOMAIN_A");
newTask.setClassificationKey("T2100"); newTask.setClassificationKey("T2100");
@ -104,7 +104,8 @@ class CreateTaskAccTest extends AbstractAccTest {
Task createdTask = taskService.createTask(newTask); Task createdTask = taskService.createTask(newTask);
assertThat(createdTask).isNotNull(); assertThat(createdTask).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
} }
@WithAccessId(user = "admin") @WithAccessId(user = "admin")
@ -113,7 +114,7 @@ class CreateTaskAccTest extends AbstractAccTest {
void should_CreateTask_When_NoExplicitPermissionsButUserIsInAdministrativeRole() void should_CreateTask_When_NoExplicitPermissionsButUserIsInAdministrativeRole()
throws Exception { throws Exception {
String currentUser = CurrentUserContext.getUserid(); String currentUser = taskanaEngine.getCurrentUserContext().getUserid();
Task newTask = taskService.newTask("USER-1-1", "DOMAIN_A"); Task newTask = taskService.newTask("USER-1-1", "DOMAIN_A");
newTask.setClassificationKey("T2100"); newTask.setClassificationKey("T2100");
@ -124,7 +125,8 @@ class CreateTaskAccTest extends AbstractAccTest {
Task createdTask = taskService.createTask(newTask); Task createdTask = taskService.createTask(newTask);
assertThat(createdTask).isNotNull(); assertThat(createdTask).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
} }
@WithAccessId(user = "user-1-1") @WithAccessId(user = "user-1-1")
@ -140,7 +142,8 @@ class CreateTaskAccTest extends AbstractAccTest {
Instant expectedPlanned = moveForwardToWorkingDay(createdTask.getCreated()); Instant expectedPlanned = moveForwardToWorkingDay(createdTask.getCreated());
assertThat(createdTask).isNotNull(); assertThat(createdTask).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
assertThat(createdTask.getName()).isEqualTo("T-Vertragstermin VERA"); assertThat(createdTask.getName()).isEqualTo("T-Vertragstermin VERA");
assertThat(createdTask.getPrimaryObjRef().getValue()).isEqualTo("1234567"); assertThat(createdTask.getPrimaryObjRef().getValue()).isEqualTo("1234567");
assertThat(createdTask.getExternalId()).isNotNull(); assertThat(createdTask.getExternalId()).isNotNull();
@ -255,7 +258,8 @@ class CreateTaskAccTest extends AbstractAccTest {
createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567")); createObjectReference("COMPANY_A", "SYSTEM_A", "INSTANCE_A", "VNR", "1234567"));
Task createdTask = taskService.createTask(newTask); Task createdTask = taskService.createTask(newTask);
assertThat(createdTask.getId()).isNotNull(); assertThat(createdTask.getId()).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
// verify that the database content is as expected // verify that the database content is as expected
TaskanaEngineProxy engineProxy = new TaskanaEngineProxy(taskanaEngine); TaskanaEngineProxy engineProxy = new TaskanaEngineProxy(taskanaEngine);
@ -289,7 +293,8 @@ class CreateTaskAccTest extends AbstractAccTest {
Task readTask = taskService.getTask(createdTask.getId()); Task readTask = taskService.getTask(createdTask.getId());
assertThat(readTask).isNotNull(); assertThat(readTask).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
assertThat(readTask.getAttachments()).isNotNull(); assertThat(readTask.getAttachments()).isNotNull();
assertThat(readTask.getAttachments()).hasSize(1); assertThat(readTask.getAttachments()).hasSize(1);
assertThat(readTask.getAttachments().get(0).getCreated()).isNotNull(); assertThat(readTask.getAttachments().get(0).getCreated()).isNotNull();
@ -350,11 +355,13 @@ class CreateTaskAccTest extends AbstractAccTest {
Task createdTask = taskService.createTask(newTask); Task createdTask = taskService.createTask(newTask);
assertThat(createdTask.getId()).isNotNull(); assertThat(createdTask.getId()).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
Task readTask = taskService.getTask(createdTask.getId()); Task readTask = taskService.getTask(createdTask.getId());
assertThat(readTask).isNotNull(); assertThat(readTask).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
assertThat(readTask.getAttachments()).isNotNull(); assertThat(readTask.getAttachments()).isNotNull();
assertThat(readTask.getAttachments()).hasSize(2); assertThat(readTask.getAttachments()).hasSize(2);
assertThat(readTask.getAttachments().get(1).getCreated()).isNotNull(); assertThat(readTask.getAttachments().get(1).getCreated()).isNotNull();
@ -401,11 +408,13 @@ class CreateTaskAccTest extends AbstractAccTest {
Task createdTask = taskService.createTask(newTask); Task createdTask = taskService.createTask(newTask);
assertThat(createdTask.getId()).isNotNull(); assertThat(createdTask.getId()).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
Task readTask = taskService.getTask(createdTask.getId()); Task readTask = taskService.getTask(createdTask.getId());
assertThat(readTask).isNotNull(); assertThat(readTask).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
assertThat(readTask.getAttachments()).isNotNull(); assertThat(readTask.getAttachments()).isNotNull();
assertThat(readTask.getAttachments()).hasSize(2); assertThat(readTask.getAttachments()).hasSize(2);
assertThat(readTask.getAttachments().get(1).getCreated()).isNotNull(); assertThat(readTask.getAttachments().get(1).getCreated()).isNotNull();
@ -489,7 +498,8 @@ class CreateTaskAccTest extends AbstractAccTest {
Task createdTask = taskService.createTask(newTask); Task createdTask = taskService.createTask(newTask);
assertThat(createdTask).isNotNull(); assertThat(createdTask).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
assertThat(createdTask.getName()).isEqualTo("Test Name"); assertThat(createdTask.getName()).isEqualTo("Test Name");
} }
@ -505,7 +515,8 @@ class CreateTaskAccTest extends AbstractAccTest {
Task createdTask = taskService.createTask(newTask); Task createdTask = taskService.createTask(newTask);
assertThat(createdTask).isNotNull(); assertThat(createdTask).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
assertThat(createdTask.getPriority()).isEqualTo(2); assertThat(createdTask.getPriority()).isEqualTo(2);
} }
@ -576,7 +587,8 @@ class CreateTaskAccTest extends AbstractAccTest {
Task createdTask = taskService.createTask(newTask); Task createdTask = taskService.createTask(newTask);
assertThat(createdTask).isNotNull(); assertThat(createdTask).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
assertThat(createdTask.getDomain()).isNotNull(); assertThat(createdTask.getDomain()).isNotNull();
assertThat(createdTask.getDomain()).isEqualTo(workbasket.getDomain()); assertThat(createdTask.getDomain()).isEqualTo(workbasket.getDomain());
} }

View File

@ -18,7 +18,7 @@ import org.junit.jupiter.api.extension.ExtendWith;
import pro.taskana.common.api.BaseQuery.SortDirection; import pro.taskana.common.api.BaseQuery.SortDirection;
import pro.taskana.common.api.exceptions.SystemException; import pro.taskana.common.api.exceptions.SystemException;
import pro.taskana.common.internal.security.UserPrincipal; import pro.taskana.common.api.security.UserPrincipal;
import pro.taskana.common.internal.util.CheckedConsumer; import pro.taskana.common.internal.util.CheckedConsumer;
import pro.taskana.common.test.security.JaasExtension; import pro.taskana.common.test.security.JaasExtension;
import pro.taskana.common.test.security.WithAccessId; import pro.taskana.common.test.security.WithAccessId;

View File

@ -15,7 +15,6 @@ import org.junit.jupiter.api.extension.ExtendWith;
import pro.taskana.classification.api.models.Classification; import pro.taskana.classification.api.models.Classification;
import pro.taskana.classification.api.models.ClassificationSummary; import pro.taskana.classification.api.models.ClassificationSummary;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.common.test.security.JaasExtension; import pro.taskana.common.test.security.JaasExtension;
import pro.taskana.common.test.security.WithAccessId; import pro.taskana.common.test.security.WithAccessId;
import pro.taskana.task.api.TaskService; import pro.taskana.task.api.TaskService;
@ -441,13 +440,15 @@ class UpdateTaskAttachmentsAccTest extends AbstractAccTest {
Task createdTask = taskService.createTask(newTask); Task createdTask = taskService.createTask(newTask);
assertThat(createdTask.getId()).isNotNull(); assertThat(createdTask.getId()).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
createdTask createdTask
.getAttachments() .getAttachments()
.forEach(at -> assertThat(createdTask.getModified()).isEqualTo(at.getModified())); .forEach(at -> assertThat(createdTask.getModified()).isEqualTo(at.getModified()));
Task readTask = taskService.getTask(createdTask.getId()); Task readTask = taskService.getTask(createdTask.getId());
assertThat(readTask).isNotNull(); assertThat(readTask).isNotNull();
assertThat(createdTask.getCreator()).isEqualTo(CurrentUserContext.getUserid()); assertThat(createdTask.getCreator())
.isEqualTo(taskanaEngine.getCurrentUserContext().getUserid());
assertThat(readTask.getAttachments()).isNotNull(); assertThat(readTask.getAttachments()).isNotNull();
assertThat(readTask.getAttachments()).hasSize(2); assertThat(readTask.getAttachments()).hasSize(2);
assertThat(readTask.getAttachments().get(1).getCreated()).isNotNull(); assertThat(readTask.getAttachments().get(1).getCreated()).isNotNull();

View File

@ -63,8 +63,6 @@ class ArchitectureTest {
ArchRule myRule = ArchRule myRule =
classes() classes()
.that() .that()
.haveSimpleNameNotEndingWith("TaskanaHistoryEvent")
.and()
.resideInAPackage("..api..") .resideInAPackage("..api..")
.should() .should()
.onlyDependOnClassesThat() .onlyDependOnClassesThat()

View File

@ -15,6 +15,7 @@ import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import pro.taskana.common.api.TaskanaEngine; import pro.taskana.common.api.TaskanaEngine;
import pro.taskana.common.api.security.CurrentUserContext;
import pro.taskana.common.internal.InternalTaskanaEngine; import pro.taskana.common.internal.InternalTaskanaEngine;
import pro.taskana.common.internal.configuration.DB; import pro.taskana.common.internal.configuration.DB;
import pro.taskana.task.api.TaskState; import pro.taskana.task.api.TaskState;
@ -31,15 +32,18 @@ class TaskQueryImplTest {
@Mock TaskServiceImpl taskServiceMock; @Mock TaskServiceImpl taskServiceMock;
private TaskQueryImpl taskQueryImpl;
@Mock private InternalTaskanaEngine internalTaskanaEngine; @Mock private InternalTaskanaEngine internalTaskanaEngine;
@Mock private TaskanaEngine taskanaEngine; @Mock private TaskanaEngine taskanaEngine;
@Mock private SqlSession sqlSession; @Mock private SqlSession sqlSession;
@Mock private CurrentUserContext currentUserContext;
private TaskQueryImpl taskQueryImpl;
@BeforeEach @BeforeEach
void setup() { void setup() {
when(internalTaskanaEngine.getEngine()).thenReturn(taskanaEngine); when(internalTaskanaEngine.getEngine()).thenReturn(taskanaEngine);
when(taskanaEngine.getTaskService()).thenReturn(taskServiceMock); when(taskanaEngine.getTaskService()).thenReturn(taskServiceMock);
when(taskanaEngine.getCurrentUserContext()).thenReturn(currentUserContext);
Configuration configuration = new org.apache.ibatis.session.Configuration(); Configuration configuration = new org.apache.ibatis.session.Configuration();
configuration.setDatabaseId(DB.H2.dbProductId); configuration.setDatabaseId(DB.H2.dbProductId);

View File

@ -23,7 +23,6 @@ import pro.taskana.common.api.TaskanaEngine.ConnectionManagementMode;
import pro.taskana.common.api.exceptions.NotAuthorizedException; import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.internal.TaskanaEngineImpl; import pro.taskana.common.internal.TaskanaEngineImpl;
import pro.taskana.common.internal.TaskanaEngineTestConfiguration; import pro.taskana.common.internal.TaskanaEngineTestConfiguration;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.common.internal.util.IdGenerator; import pro.taskana.common.internal.util.IdGenerator;
import pro.taskana.common.test.security.JaasExtension; import pro.taskana.common.test.security.JaasExtension;
import pro.taskana.common.test.security.WithAccessId; import pro.taskana.common.test.security.WithAccessId;
@ -234,7 +233,7 @@ class TaskServiceImplIntAutocommitTest {
@WithAccessId(user = "user-1-1", groups = "businessadmin") @WithAccessId(user = "user-1-1", groups = "businessadmin")
@Test @Test
void shouldNotTransferByFailingSecurity() throws Exception { void shouldNotTransferByFailingSecurity() throws Exception {
final String user = CurrentUserContext.getUserid(); final String user = taskanaEngine.getCurrentUserContext().getUserid();
// Set up Security for this Test // Set up Security for this Test
DataSource dataSource = TaskanaEngineTestConfiguration.getDataSource(); DataSource dataSource = TaskanaEngineTestConfiguration.getDataSource();

View File

@ -27,7 +27,6 @@ import pro.taskana.common.api.exceptions.NotAuthorizedException;
import pro.taskana.common.internal.TaskanaEngineImpl; import pro.taskana.common.internal.TaskanaEngineImpl;
import pro.taskana.common.internal.TaskanaEngineTestConfiguration; import pro.taskana.common.internal.TaskanaEngineTestConfiguration;
import pro.taskana.common.internal.configuration.DbSchemaCreator; import pro.taskana.common.internal.configuration.DbSchemaCreator;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.common.internal.util.IdGenerator; import pro.taskana.common.internal.util.IdGenerator;
import pro.taskana.common.test.security.JaasExtension; import pro.taskana.common.test.security.JaasExtension;
import pro.taskana.common.test.security.WithAccessId; import pro.taskana.common.test.security.WithAccessId;
@ -193,7 +192,7 @@ class TaskServiceImplIntExplicitTest {
wb = workbasketService.createWorkbasket(wb); wb = workbasketService.createWorkbasket(wb);
workbasketService.createWorkbasketAccessItem( workbasketService.createWorkbasketAccessItem(
this.createWorkbasketWithSecurity( this.createWorkbasketWithSecurity(
wb, CurrentUserContext.getUserid(), true, true, true, false)); wb, taskanaEngine.getCurrentUserContext().getUserid(), true, true, true, false));
Classification classification = Classification classification =
classificationService.newClassification( classificationService.newClassification(
UUID.randomUUID().toString(), wb.getDomain(), "t1"); // not persisted, UUID.randomUUID().toString(), wb.getDomain(), "t1"); // not persisted,
@ -263,7 +262,7 @@ class TaskServiceImplIntExplicitTest {
@Test @Test
void shouldTransferTaskToOtherWorkbasket() throws Exception { void shouldTransferTaskToOtherWorkbasket() throws Exception {
final int sleepTime = 100; final int sleepTime = 100;
final String user = CurrentUserContext.getUserid(); final String user = taskanaEngine.getCurrentUserContext().getUserid();
try (Connection connection = dataSource.getConnection()) { try (Connection connection = dataSource.getConnection()) {
taskanaEngineImpl.setConnection(connection); taskanaEngineImpl.setConnection(connection);

View File

@ -15,6 +15,7 @@ import org.mockito.Mock;
import org.mockito.junit.jupiter.MockitoExtension; import org.mockito.junit.jupiter.MockitoExtension;
import pro.taskana.common.api.TaskanaEngine; import pro.taskana.common.api.TaskanaEngine;
import pro.taskana.common.api.security.CurrentUserContext;
import pro.taskana.common.internal.InternalTaskanaEngine; import pro.taskana.common.internal.InternalTaskanaEngine;
import pro.taskana.workbasket.api.models.WorkbasketSummary; import pro.taskana.workbasket.api.models.WorkbasketSummary;
import pro.taskana.workbasket.internal.models.WorkbasketSummaryImpl; import pro.taskana.workbasket.internal.models.WorkbasketSummaryImpl;
@ -35,9 +36,12 @@ class WorkbasketQueryImplTest {
@Mock private SqlSession sqlSession; @Mock private SqlSession sqlSession;
@Mock private CurrentUserContext currentUserContext;
@BeforeEach @BeforeEach
void setup() { void setup() {
when(internalTaskanaEngine.getEngine()).thenReturn(taskanaEngine); when(internalTaskanaEngine.getEngine()).thenReturn(taskanaEngine);
when(taskanaEngine.getCurrentUserContext()).thenReturn(currentUserContext);
} }
@Test @Test

View File

@ -17,8 +17,8 @@ import org.springframework.stereotype.Component;
import pro.taskana.common.api.ScheduledJob.Type; import pro.taskana.common.api.ScheduledJob.Type;
import pro.taskana.common.api.TaskanaEngine; import pro.taskana.common.api.TaskanaEngine;
import pro.taskana.common.api.TaskanaRole; import pro.taskana.common.api.TaskanaRole;
import pro.taskana.common.api.security.UserPrincipal;
import pro.taskana.common.internal.jobs.JobRunner; import pro.taskana.common.internal.jobs.JobRunner;
import pro.taskana.common.internal.security.UserPrincipal;
import pro.taskana.common.internal.transaction.TaskanaTransactionProvider; import pro.taskana.common.internal.transaction.TaskanaTransactionProvider;
import pro.taskana.task.internal.jobs.TaskCleanupJob; import pro.taskana.task.internal.jobs.TaskCleanupJob;
import pro.taskana.workbasket.internal.jobs.WorkbasketCleanupJob; import pro.taskana.workbasket.internal.jobs.WorkbasketCleanupJob;
@ -28,8 +28,15 @@ import pro.taskana.workbasket.internal.jobs.WorkbasketCleanupJob;
public class JobScheduler { public class JobScheduler {
private static final Logger LOGGER = LoggerFactory.getLogger(JobScheduler.class); private static final Logger LOGGER = LoggerFactory.getLogger(JobScheduler.class);
@Autowired TaskanaTransactionProvider<Object> springTransactionProvider; private final TaskanaTransactionProvider<Object> springTransactionProvider;
@Autowired private TaskanaEngine taskanaEngine; private final TaskanaEngine taskanaEngine;
@Autowired
public JobScheduler(
TaskanaTransactionProvider<Object> springTransactionProvider, TaskanaEngine taskanaEngine) {
this.springTransactionProvider = springTransactionProvider;
this.taskanaEngine = taskanaEngine;
}
@PostConstruct @PostConstruct
public void scheduleCleanupJob() public void scheduleCleanupJob()
@ -64,24 +71,19 @@ public class JobScheduler {
* Creates an admin subject and runs the job using the subject. * Creates an admin subject and runs the job using the subject.
*/ */
private void runAsyncJobsAsAdmin() throws PrivilegedActionException { private void runAsyncJobsAsAdmin() throws PrivilegedActionException {
Subject.doAs( PrivilegedExceptionAction<Object> jobs =
getAdminSubject(), () -> {
new PrivilegedExceptionAction<Object>() { try {
JobRunner runner = new JobRunner(taskanaEngine);
@Override runner.registerTransactionProvider(springTransactionProvider);
public Object run() throws Exception { LOGGER.info("Running Jobs");
runner.runJobs();
try { return "Successful";
JobRunner runner = new JobRunner(taskanaEngine); } catch (Throwable e) {
runner.registerTransactionProvider(springTransactionProvider); throw new Exception(e);
LOGGER.info("Running Jobs");
runner.runJobs();
return "Successful";
} catch (Throwable e) {
throw new Exception(e);
}
} }
}); };
Subject.doAs(getAdminSubject(), jobs);
} }
private Subject getAdminSubject() { private Subject getAdminSubject() {

View File

@ -12,7 +12,7 @@ import org.wildfly.security.auth.server.SecurityDomain;
import org.wildfly.security.auth.server.SecurityIdentity; import org.wildfly.security.auth.server.SecurityIdentity;
import org.wildfly.security.authz.Roles; import org.wildfly.security.authz.Roles;
import pro.taskana.common.internal.security.GroupPrincipal; import pro.taskana.common.api.security.GroupPrincipal;
/** Simple Filter to map all Elytron Roles to JAAS-Principals. */ /** Simple Filter to map all Elytron Roles to JAAS-Principals. */
public class ElytronToJaasFilter extends GenericFilterBean { public class ElytronToJaasFilter extends GenericFilterBean {

View File

@ -13,7 +13,6 @@ import org.springframework.web.bind.annotation.RestController;
import pro.taskana.TaskanaEngineConfiguration; import pro.taskana.TaskanaEngineConfiguration;
import pro.taskana.common.api.TaskanaEngine; import pro.taskana.common.api.TaskanaEngine;
import pro.taskana.common.api.TaskanaRole; import pro.taskana.common.api.TaskanaRole;
import pro.taskana.common.internal.security.CurrentUserContext;
import pro.taskana.common.rest.models.TaskanaUserInfoRepresentationModel; import pro.taskana.common.rest.models.TaskanaUserInfoRepresentationModel;
import pro.taskana.common.rest.models.VersionRepresentationModel; import pro.taskana.common.rest.models.VersionRepresentationModel;
@ -90,8 +89,8 @@ public class TaskanaEngineController {
public ResponseEntity<TaskanaUserInfoRepresentationModel> getCurrentUserInfo() { public ResponseEntity<TaskanaUserInfoRepresentationModel> getCurrentUserInfo() {
LOGGER.debug("Entry to getCurrentUserInfo()"); LOGGER.debug("Entry to getCurrentUserInfo()");
TaskanaUserInfoRepresentationModel resource = new TaskanaUserInfoRepresentationModel(); TaskanaUserInfoRepresentationModel resource = new TaskanaUserInfoRepresentationModel();
resource.setUserId(CurrentUserContext.getUserid()); resource.setUserId(taskanaEngine.getCurrentUserContext().getUserid());
resource.setGroupIds(CurrentUserContext.getGroupIds()); resource.setGroupIds(taskanaEngine.getCurrentUserContext().getGroupIds());
for (TaskanaRole role : taskanaEngineConfiguration.getRoleMap().keySet()) { for (TaskanaRole role : taskanaEngineConfiguration.getRoleMap().keySet()) {
if (taskanaEngine.isUserInRole(role)) { if (taskanaEngine.isUserInRole(role)) {
resource.getRoles().add(role); resource.getRoles().add(role);

View File

@ -16,8 +16,8 @@ import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.web.filter.GenericFilterBean; import org.springframework.web.filter.GenericFilterBean;
import pro.taskana.common.api.exceptions.SystemException; import pro.taskana.common.api.exceptions.SystemException;
import pro.taskana.common.internal.security.GroupPrincipal; import pro.taskana.common.api.security.GroupPrincipal;
import pro.taskana.common.internal.security.UserPrincipal; import pro.taskana.common.api.security.UserPrincipal;
/** Simple Filter to map all Spring Security Roles to JAAS-Principals. */ /** Simple Filter to map all Spring Security Roles to JAAS-Principals. */
public class SpringSecurityToJaasFilter extends GenericFilterBean { public class SpringSecurityToJaasFilter extends GenericFilterBean {

View File

@ -68,6 +68,7 @@ class TaskanaEngineControllerIntTest {
HttpMethod.GET, HttpMethod.GET,
restHelper.defaultRequest(), restHelper.defaultRequest(),
ParameterizedTypeReference.forType(TaskanaUserInfoRepresentationModel.class)); ParameterizedTypeReference.forType(TaskanaUserInfoRepresentationModel.class));
assertThat(response.getBody()).isNotNull();
assertThat(response.getBody().getUserId()).isEqualTo("teamlead-1"); assertThat(response.getBody().getUserId()).isEqualTo("teamlead-1");
assertThat(response.getBody().getGroupIds()) assertThat(response.getBody().getGroupIds())
.contains("cn=business-admins,cn=groups,ou=test,o=taskana"); .contains("cn=business-admins,cn=groups,ou=test,o=taskana");