diff --git a/pom.xml b/pom.xml
index 38e1f2a..b588eef 100644
--- a/pom.xml
+++ b/pom.xml
@@ -7,12 +7,11 @@
org.activestack
syncengine
- 1.1.18-httpconnector-SNAPSHOT
+ 1.1.65-SNAPSHOT
3.2.4.RELEASE
1.6.11
- 1.6.1
1.19.0
1.19.0
1.9.5
@@ -193,6 +192,18 @@
jedis
2.5.2
+
+
+
+ org.quartz-scheduler
+ quartz
+ 2.2.2
+
+
+ org.quartz-scheduler
+ quartz-jobs
+ 2.2.2
+
org.springframework
spring-beans
@@ -218,21 +229,11 @@
log4j
1.2.16
-
- org.slf4j
- slf4j-api
- ${slf4j.version}
-
-
- org.slf4j
- jcl-over-slf4j
- ${slf4j.version}
-
-
- org.slf4j
- slf4j-log4j12
- ${slf4j.version}
-
+
+
+
+
+
commons-dbcp
commons-dbcp
@@ -246,7 +247,7 @@
joda-time
joda-time
- 2.1
+ 2.9
com.google.apis
@@ -329,6 +330,26 @@
yamlbeans
1.09
+
+ org.logback-extensions
+ logback-ext-loggly
+ 0.1.2
+
+
+
+
+ com.zaxxer
+ HikariCP
+ 2.4.1
+
+
+
+
+ com.h2database
+ h2
+ 1.3.167
+ test
+
@@ -342,7 +363,16 @@
1.7
+
+ org.apache.maven.plugins
+ maven-surefire-plugin
+ 2.18.1
+
+ true
+
+
+
@@ -369,4 +399,4 @@
-
\ No newline at end of file
+
diff --git a/src/main/java/com/percero/agents/auth/helpers/AccountHelper.java b/src/main/java/com/percero/agents/auth/helpers/AccountHelper.java
index bf1cfb7..7febf4d 100644
--- a/src/main/java/com/percero/agents/auth/helpers/AccountHelper.java
+++ b/src/main/java/com/percero/agents/auth/helpers/AccountHelper.java
@@ -1,291 +1,246 @@
package com.percero.agents.auth.helpers;
-import java.lang.reflect.InvocationTargetException;
-import java.security.Principal;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Set;
-import java.util.UUID;
-
-import org.apache.log4j.Logger;
-import org.hibernate.HibernateException;
-import org.hibernate.NonUniqueResultException;
-import org.hibernate.Query;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.stereotype.Component;
-import org.springframework.util.StringUtils;
-
import com.percero.agents.auth.principal.PrincipalUser;
import com.percero.agents.auth.services.IAuthService;
-import com.percero.agents.auth.vo.IUserAnchor;
-import com.percero.agents.auth.vo.IUserIdentifier;
-import com.percero.agents.auth.vo.IUserRole;
-import com.percero.agents.auth.vo.ServiceIdentifier;
-import com.percero.agents.auth.vo.ServiceUser;
+import com.percero.agents.auth.vo.*;
import com.percero.agents.sync.access.IAccessManager;
import com.percero.agents.sync.helpers.PostCreateHelper;
import com.percero.agents.sync.helpers.PostDeleteHelper;
import com.percero.agents.sync.helpers.PostPutHelper;
-import com.percero.agents.sync.hibernate.SyncHibernateUtils;
-import com.percero.agents.sync.metadata.EntityImplementation;
-import com.percero.agents.sync.metadata.IMappedClassManager;
-import com.percero.agents.sync.metadata.MappedClass;
-import com.percero.agents.sync.metadata.MappedClassManagerFactory;
-import com.percero.agents.sync.metadata.PropertyImplementation;
-import com.percero.agents.sync.metadata.PropertyImplementationParam;
-import com.percero.agents.sync.metadata.RelationshipImplementation;
+import com.percero.agents.sync.metadata.*;
import com.percero.agents.sync.services.IDataProviderManager;
import com.percero.agents.sync.services.ISyncAgentService;
import com.percero.agents.sync.vo.Client;
import com.percero.framework.bl.IManifest;
import com.percero.framework.bl.ManifestHelper;
import com.percero.framework.vo.IPerceroObject;
+import org.apache.log4j.Logger;
+import org.hibernate.HibernateException;
+import org.hibernate.NonUniqueResultException;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.stereotype.Component;
+import org.springframework.util.StringUtils;
+
+import java.lang.reflect.InvocationTargetException;
+import java.security.Principal;
+import java.util.*;
@Component
public class AccountHelper implements IAccountHelper {
- private static final Logger log = Logger.getLogger(AccountHelper.class);
-
- public AccountHelper() {
- }
-
- @Autowired
- protected IManifest manifest = null;
- public void setManifest(IManifest value) {
- manifest = value;
- }
-
- @Autowired
- protected IAuthService authService;
- public void setAuthService(IAuthService value) {
- authService = value;
- }
-
- @Autowired
- protected IAccessManager accessManager;
- public void setAccessManager(IAccessManager value) {
- accessManager = value;
- }
-
- @Autowired
- protected SessionFactory appSessionFactory;
- public void setAppSessionFactory(SessionFactory value) {
- appSessionFactory = value;
- }
-
- @Autowired
- protected ISyncAgentService syncAgentService;
- public void setSyncAgentService(ISyncAgentService value) {
- syncAgentService = value;
- }
-
- @Autowired
- protected PostPutHelper postPutHelper;
- public void setPostPutHelper(PostPutHelper value) {
- postPutHelper = value;
- }
-
- @Autowired
- protected IDataProviderManager dataProviderManager;
- public void setDataProviderManager(IDataProviderManager value) {
- dataProviderManager = value;
- }
-
- @Autowired
- protected PostCreateHelper postCreateHelper;
- public void setPostCreateHelper(PostCreateHelper value) {
- postCreateHelper = value;
- }
- @Autowired
- protected PostDeleteHelper postDeleteHelper;
- public void setPostDeleteHelper(PostDeleteHelper value) {
- postDeleteHelper = value;
- }
-
- public Principal authenticateOAuth(String regAppKey, String svcOAuthKey, String userId, String userToken, String clientId, String clientType, String deviceId) {
- return authenticateOAuth(regAppKey, svcOAuthKey, userId, userToken, clientId, clientType, deviceId, null);
- }
-
- public Principal authenticateOAuth(String regAppKey, String svcOAuthKey, String userId, String userToken, String clientId, String clientType, String deviceId, Set existingClientIds) {
- if (!StringUtils.hasText(clientType)) {
- clientType = Client.NON_PERSISTENT_TYPE;
- }
-
- // Only worry about existing client if it is set and NOT equal to the "new" client Id.
- Boolean isExistingClient = ( existingClientIds != null && !existingClientIds.isEmpty() );
- boolean validated = false;
- try {
- if (isExistingClient) {
- validated = authService.validateUserByToken(regAppKey, userId, userToken, clientId, existingClientIds);
- } else {
- validated = authService.validateUserByToken(regAppKey, userId, userToken, clientId);
- }
- log.debug("ValidateUserByToken Result: " + userId + " / " + userToken + " / " + clientId + " = " + (validated ? "true" : "false"));
- } catch (Exception e) {
- log.error("Error validating User by Token", e);
- e.printStackTrace();
- validated = false;
- }
-
- if (validated) {
- try {
- // Make sure a valid Person exists for this User.
- IUserAnchor userAnchor = validateUser(regAppKey, userId, authService);
-
- if (userAnchor == null) {
- // Something went wrong here.
- throw new Error("Invalid UserAnchor object.");
- }
-
- List roleList = getUserRoles(userId);
-
- String[] groups = (String[]) roleList.toArray(new String[0]);
- PrincipalUser theUser = new PrincipalUser(userId, userId, userToken, clientType, clientId, groups);
-
- Boolean foundValidClient = false;
- if (StringUtils.hasText(deviceId))
- {
- if (isExistingClient) {
- Iterator itrExistingClientIds = existingClientIds.iterator();
- while (itrExistingClientIds.hasNext()) {
- String existingClientId = itrExistingClientIds.next();
- if (!existingClientId.equals(clientId)) {
- // Need to move the existing client to the new client.
- log.debug("Renaming client " + existingClientId + " to " + clientId);
- accessManager.renameClient(existingClientId, clientId);
- }
- }
- }
- }
-
- if (!foundValidClient)
- foundValidClient = accessManager.findClientByClientIdUserId(clientId, userId);
-
- if (!foundValidClient) {
- // Unable to find a valid client, so need to create one.
- accessManager.createClient(clientId, userId, clientType, deviceId);
- }
-
- return theUser;
- } catch(Exception e) {
- log.error("Error getting Roles", e);
- e.printStackTrace();
- }
- }
-
- log.debug("authenticateOAuth: Returning null result");
- return null;
- }
-
- public IUserAnchor validateUser(String regAppKey, String userId, IAuthService authService) throws HibernateException {
- IUserAnchor result = null;
- Session s = appSessionFactory.openSession();
- try {
- ManifestHelper.setManifest(manifest);
- //Class userAnchorClass = ManifestHelper.findImplementingClass(IUserAnchor.class);
- EntityImplementation userAnchorEI = null;
- List userAnchorMappedClasses = MappedClass.findEntityImplementation(IUserAnchor.class);
- if (userAnchorMappedClasses.size() > 0) {
- userAnchorEI = userAnchorMappedClasses.get(0);
- }
-
- if (userAnchorEI != null) {
- //IMappedClassManager mcm = MappedClassManagerFactory.getMappedClassManager();
- MappedClass mc = userAnchorEI.mappedClass;
- if (mc != null) {
- String userAnchorQueryString = "SELECT ua FROM " + mc.tableName + " ua WHERE ua.userId=:userId";
- Query userAnchorQuery = s.createQuery(userAnchorQueryString);
- userAnchorQuery.setString("userId", userId);
-
- IUserAnchor foundUserAnchor = (IUserAnchor) userAnchorQuery.uniqueResult();
-
- if (foundUserAnchor == null) {
- result = handleUserAnchorNotFound(regAppKey, userId, authService);
- } else {
- handleUserAnchorFound(regAppKey, userId, authService, foundUserAnchor);
- result = foundUserAnchor;
- }
- }
- }
- } catch (NonUniqueResultException nre) {
- log.error("More than one UserAnchor objects found for userId " + userId, nre);
- } finally {
- if (s != null && s.isOpen())
- s.close();
- }
- return result;
- }
-
- protected IUserAnchor handleUserAnchorNotFound(String regAppKey, String userId, IAuthService authService) {
- // Get this person's email addresses from the AuthManager.
- List serviceUserList = authService.getServiceUsers(userId);
- IUserAnchor result = addOrUpdateUserAnchorFromServiceUserList(userId, serviceUserList, null);
- //setupUserRoles(userId, serviceUserList);
-
- return result;
- }
-
- protected void handleUserAnchorFound(String regAppKey, String userId, IAuthService authService, IUserAnchor userAnchor) {
- // Get this person's email addresses from the AuthManager.
- List serviceUserList = authService.getServiceUsers(userId);
-
- if (userAnchor != null && (userAnchor instanceof IPerceroObject)) {
- try {
- // Attempt to get updated information from ServiceProvider.
- EntityImplementation userAnchorEI = null;
- List userAnchorMappedClasses = MappedClass.findEntityImplementation(IUserAnchor.class);
- if (userAnchorMappedClasses.size() > 0) {
- userAnchorEI = userAnchorMappedClasses.get(0);
- }
-
- PropertyImplementation firstNamePropImpl = userAnchorEI.findPropertyImplementationByName(IUserAnchor.FIRST_NAME_FIELD);
- PropertyImplementation lastNamePropImpl = userAnchorEI.findPropertyImplementationByName(IUserAnchor.LAST_NAME_FIELD);
- //MappedField firstNameField = userAnchorEI.mappedClass.getExternalizeFieldByName("firstName");
- //MappedField lastNameField = userAnchorappedClass.getExternalizeFieldByName("lastName");
- String firstName = "";
- String lastName = "";
-
- if (firstNamePropImpl != null || lastNamePropImpl != null) {
- if (firstNamePropImpl != null)
- firstName = (String) firstNamePropImpl.mappedField.getGetter().invoke(userAnchor);
- if (lastNamePropImpl != null)
- lastName = (String) lastNamePropImpl.mappedField.getGetter().invoke(userAnchor);
-
- boolean userAnchorUpdated = false;
- for (ServiceUser nextServiceUser : serviceUserList) {
- if (StringUtils.hasText(nextServiceUser.getFirstName()) && firstNamePropImpl != null) {
- if (firstName == null || !firstName.equals(nextServiceUser.getFirstName())) {
- firstName = nextServiceUser.getFirstName();
- firstNamePropImpl.mappedField.getSetter().invoke(userAnchor, firstName);
- userAnchorUpdated = true;
- }
- }
- if (StringUtils.hasText(nextServiceUser.getLastName()) && lastNamePropImpl != null) {
- if (lastName == null || !lastName.equals(nextServiceUser.getLastName())) {
- lastName = nextServiceUser.getLastName();
- lastNamePropImpl.mappedField.getSetter().invoke(userAnchor, lastName);
- userAnchorUpdated = true;
- }
- }
- }
-
- if (userAnchorUpdated) {
- syncAgentService.systemPutObject((IPerceroObject) userAnchor, null, new Date(), null, true);
- }
- }
- } catch(Exception e) {
- log.warn("Unable to get ServiceUser information for First/Last Name", e);
- }
- }
-
- //setupUserRoles(userId, serviceUserList);
- addOrUpdateUserAnchorFromServiceUserList(userId, serviceUserList, userAnchor);
- }
+ private static final Logger log = Logger.getLogger(AccountHelper.class);
+
+ public AccountHelper() {
+ }
+
+ @Autowired
+ protected IManifest manifest = null;
+ public void setManifest(IManifest value) {
+ manifest = value;
+ }
+
+ @Autowired
+ protected IAuthService authService;
+ public void setAuthService(IAuthService value) {
+ authService = value;
+ }
+
+ @Autowired
+ protected IAccessManager accessManager;
+ public void setAccessManager(IAccessManager value) {
+ accessManager = value;
+ }
+
+ @Autowired
+ protected ISyncAgentService syncAgentService;
+ public void setSyncAgentService(ISyncAgentService value) {
+ syncAgentService = value;
+ }
+
+ @Autowired
+ protected PostPutHelper postPutHelper;
+ public void setPostPutHelper(PostPutHelper value) {
+ postPutHelper = value;
+ }
+
+ @Autowired
+ protected IDataProviderManager dataProviderManager;
+ public void setDataProviderManager(IDataProviderManager value) {
+ dataProviderManager = value;
+ }
+
+ @Autowired
+ protected PostCreateHelper postCreateHelper;
+ public void setPostCreateHelper(PostCreateHelper value) {
+ postCreateHelper = value;
+ }
+ @Autowired
+ protected PostDeleteHelper postDeleteHelper;
+ public void setPostDeleteHelper(PostDeleteHelper value) {
+ postDeleteHelper = value;
+ }
+
+ public Principal authenticateOAuth(String regAppKey, String svcOAuthKey, String userId, String userToken, String clientId, String clientType, String deviceId) {
+ return authenticateOAuth(regAppKey, svcOAuthKey, userId, userToken, clientId, clientType, deviceId, null);
+ }
+
+ public Principal authenticateOAuth(String regAppKey, String svcOAuthKey, String userId, String userToken, String clientId, String clientType, String deviceId, Set existingClientIds) {
+ log.debug("[AccountHelper] Authenticating user " + userId + ", token " + userToken + ", client " + clientId + ", device " + deviceId + " " + (existingClientIds == null || existingClientIds.isEmpty() ? "NO existing clients" : existingClientIds.size() + " existing client(s)"));
+
+ if (!StringUtils.hasText(clientType)) {
+ clientType = Client.NON_PERSISTENT_TYPE;
+ }
+
+ // Only worry about existing client if it is set and NOT equal to the "new" client Id.
+ Boolean isExistingClient = ( existingClientIds != null && !existingClientIds.isEmpty() );
+ boolean validated = false;
+ try {
+ if (isExistingClient) {
+ validated = authService.validateUserByToken(regAppKey, userId, userToken, clientId, existingClientIds);
+ } else {
+ validated = authService.validateUserByToken(regAppKey, userId, userToken, clientId);
+ }
+ log.debug("[AccountHelper] ValidateUserByToken Result: " + userId + " / " + userToken + " / " + clientId + " = " + (validated ? "true" : "false"));
+ } catch (Exception e) {
+ log.error("[AccountHelper] Error validating User by Token", e);
+ validated = false;
+ }
+
+ if (validated) {
+ try {
+ // Make sure a valid Person exists for this User.
+ IUserAnchor userAnchor = validateUser(regAppKey, userId, authService);
+
+ if (userAnchor == null) {
+ // Something went wrong here.
+ throw new Error("[AccountHelper] Invalid UserAnchor object.");
+ }
+
+ List roleList = getUserRoles(userId);
+
+ String[] groups = (String[]) roleList.toArray(new String[0]);
+ PrincipalUser theUser = new PrincipalUser(userId, userId, userToken, clientType, clientId, groups);
+
+ Boolean foundValidClient = false;
+ if (StringUtils.hasText(deviceId))
+ {
+ if (isExistingClient) {
+ Iterator itrExistingClientIds = existingClientIds.iterator();
+ while (itrExistingClientIds.hasNext()) {
+ String existingClientId = itrExistingClientIds.next();
+ if (!existingClientId.equals(clientId)) {
+ // Need to move the existing client to the new client.
+ log.debug("Renaming client " + existingClientId + " to " + clientId);
+ accessManager.renameClient(existingClientId, clientId);
+ }
+ }
+ }
+ }
+
+ if (!foundValidClient)
+ foundValidClient = accessManager.findClientByClientIdUserId(clientId, userId);
+
+ if (!foundValidClient) {
+ // Unable to find a valid client, so need to create one.
+ accessManager.createClient(clientId, userId, clientType, deviceId);
+ }
+
+ return theUser;
+ } catch(Exception e) {
+ log.error("Error getting Roles", e);
+ e.printStackTrace();
+ }
+ }
+
+ log.debug("authenticateOAuth: Returning null result");
+ return null;
+ }
+
+ public IUserAnchor validateUser(String regAppKey, String userId, IAuthService authService) throws HibernateException {
+ IUserAnchor result = null;
+ try {
+ ManifestHelper.setManifest(manifest);
+ IUserAnchor foundUserAnchor = UserAnchorHelper.getUserAnchor(userId);
+
+ if (foundUserAnchor == null) {
+ result = handleUserAnchorNotFound(regAppKey, userId, authService);
+ } else {
+ handleUserAnchorFound(regAppKey, userId, authService, foundUserAnchor);
+ result = foundUserAnchor;
+ }
+ } catch (NonUniqueResultException nre) {
+ log.error("[AccountHelper] More than one UserAnchor objects found for userId " + userId, nre);
+ }
+ return result;
+ }
+
+ protected IUserAnchor handleUserAnchorNotFound(String regAppKey, String userId, IAuthService authService) {
+ log.debug("[AccountHelper] Handling UserAnchor NOT Found for user " + userId);
+ // Get this person's email addresses from the AuthManager.
+ List serviceUserList = authService.getServiceUsers(userId);
+ IUserAnchor result = addOrUpdateUserAnchorFromServiceUserList(userId, serviceUserList, null);
+ //setupUserRoles(userId, serviceUserList);
+
+ return result;
+ }
+
+ protected void handleUserAnchorFound(String regAppKey, String userId, IAuthService authService, IUserAnchor userAnchor) {
+ log.debug("[AccountHelper] Handling UserAnchor Found for user " + userId);
+ // Get this person's email addresses from the AuthManager.
+ List serviceUserList = authService.getServiceUsers(userId);
+
+ if (userAnchor != null && (userAnchor instanceof IPerceroObject)) {
+ try {
+ // Attempt to get updated information from ServiceProvider.
+ EntityImplementation userAnchorEI = null;
+ List userAnchorMappedClasses = MappedClass.findEntityImplementation(IUserAnchor.class);
+ if (userAnchorMappedClasses.size() > 0) {
+ userAnchorEI = userAnchorMappedClasses.get(0);
+ }
+
+ PropertyImplementation firstNamePropImpl = userAnchorEI.findPropertyImplementationByName(IUserAnchor.FIRST_NAME_FIELD);
+ PropertyImplementation lastNamePropImpl = userAnchorEI.findPropertyImplementationByName(IUserAnchor.LAST_NAME_FIELD);
+ //MappedField firstNameField = userAnchorEI.mappedClass.getExternalizeFieldByName("firstName");
+ //MappedField lastNameField = userAnchorappedClass.getExternalizeFieldByName("lastName");
+ String firstName = "";
+ String lastName = "";
+
+ if (firstNamePropImpl != null || lastNamePropImpl != null) {
+ if (firstNamePropImpl != null)
+ firstName = (String) firstNamePropImpl.mappedField.getGetter().invoke(userAnchor);
+ if (lastNamePropImpl != null)
+ lastName = (String) lastNamePropImpl.mappedField.getGetter().invoke(userAnchor);
+
+ boolean userAnchorUpdated = false;
+ for (ServiceUser nextServiceUser : serviceUserList) {
+ if (StringUtils.hasText(nextServiceUser.getFirstName()) && firstNamePropImpl != null) {
+ if (firstName == null || !firstName.equals(nextServiceUser.getFirstName())) {
+ firstName = nextServiceUser.getFirstName();
+ firstNamePropImpl.mappedField.getSetter().invoke(userAnchor, firstName);
+ userAnchorUpdated = true;
+ }
+ }
+ if (StringUtils.hasText(nextServiceUser.getLastName()) && lastNamePropImpl != null) {
+ if (lastName == null || !lastName.equals(nextServiceUser.getLastName())) {
+ lastName = nextServiceUser.getLastName();
+ lastNamePropImpl.mappedField.getSetter().invoke(userAnchor, lastName);
+ userAnchorUpdated = true;
+ }
+ }
+ }
+
+ if (userAnchorUpdated) {
+ syncAgentService.systemPutObject((IPerceroObject) userAnchor, null, new Date(), null, true);
+ }
+ }
+ } catch(Exception e) {
+ log.warn("Unable to get ServiceUser information for First/Last Name", e);
+ }
+ }
+
+ //setupUserRoles(userId, serviceUserList);
+ addOrUpdateUserAnchorFromServiceUserList(userId, serviceUserList, userAnchor);
+ }
// public Object validateServiceUser(String regAppKey, String svcOauthKey, ServiceUser theServiceUser, IAuthService theAuthService) throws Exception {
// try {
@@ -311,224 +266,151 @@ protected void handleUserAnchorFound(String regAppKey, String userId, IAuthServi
// return Boolean.FALSE;
// }
- /* (non-Javadoc)
- * @see com.com.percero.agents.auth.helpers.IAccountHelper#getUserRoles(java.lang.String)
- */
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public List getUserRoles(String userId) throws Exception {
- Session s = appSessionFactory.openSession();
-
- try {
- ManifestHelper.setManifest(manifest);
- Class userAnchorClass = ManifestHelper.findImplementingClass(IUserAnchor.class);
- Class userRoleClass = ManifestHelper.findImplementingClass(IUserRole.class);
-
- if (userAnchorClass != null && userRoleClass != null) {
- EntityImplementation userAnchorEI = null;
- List userAnchorMappedClasses = MappedClass.findEntityImplementation(IUserAnchor.class);
- if (userAnchorMappedClasses.size() > 0) {
- userAnchorEI = userAnchorMappedClasses.get(0);
- }
- EntityImplementation userRoleEI = null;
- List userRoleMappedClasses = MappedClass.findEntityImplementation(IUserRole.class);
- if (userRoleMappedClasses.size() > 0) {
- userRoleEI = userRoleMappedClasses.get(0);
- }
-
- RelationshipImplementation userAnchorRelImpl = userRoleEI.findRelationshipImplementationBySourceVarName(IUserRole.USER_ANCHOR_FIELD_NAME);
-
- if (userAnchorEI != null && userRoleEI != null) {
- String userRoleEiQueryString = "SELECT ur.roleName FROM " + userRoleEI.mappedClass.tableName
- + " ur WHERE ur." + userAnchorRelImpl.sourceMappedField.getField().getName() + " IN (SELECT ua FROM " + userAnchorEI.mappedClass.tableName + " ua WHERE ua.userId=:userId)";
- Query userRoleEiQuery = s.createQuery(userRoleEiQueryString);
- userRoleEiQuery.setString("userId", userId);
-
- List result = (List) userRoleEiQuery.list();
- return result;
- }
- else {
- if (userAnchorEI == null) {
- log.debug("No User Anchor Entity Implementation Class found!");
- }
- if (userRoleEI == null) {
- log.debug("No User Role Entity Implementation Class found!");
- }
- }
- }
- } catch (Exception e) {
- log.error("Unable to Get Person Roles", e);
- } finally {
- s.close();
- }
-
- return new ArrayList();
- }
-
- /**
- @SuppressWarnings({ "rawtypes", "unchecked" })
- protected IUserRoleA getUserRoleAnnotation(Class userRoleClass) {
- IUserRoleA userRoleAnnotation = null;
- Class nextClazz = userRoleClass;
- while(userRoleAnnotation == null && nextClazz != null) {
- userRoleAnnotation = (IUserRoleA) nextClazz.getAnnotation(IUserRoleA.class);
- if (userRoleAnnotation == null)
- nextClazz = nextClazz.getSuperclass();
- }
- return userRoleAnnotation;
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- protected IUserIdentifierA getUserIdentifierAnnotation(Class userIdentifierClass) {
- IUserIdentifierA userIdentifierAnnotation = null;
- Class nextClazz = userIdentifierClass;
- while(userIdentifierAnnotation == null && nextClazz != null) {
- userIdentifierAnnotation = (IUserIdentifierA) nextClazz.getAnnotation(IUserIdentifierA.class);
- if (userIdentifierAnnotation == null)
- nextClazz = nextClazz.getSuperclass();
- }
- return userIdentifierAnnotation;
- }
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- protected IUserAnchorA getUserAnchorAnnotation(Class userAnchorClass) {
- IUserAnchorA userAnchorAnnotation = null;
- Class nextClazz = userAnchorClass;
- while(userAnchorAnnotation == null && nextClazz != null) {
- userAnchorAnnotation = (IUserAnchorA) nextClazz.getAnnotation(IUserAnchorA.class);
- if (userAnchorAnnotation == null)
- nextClazz = nextClazz.getSuperclass();
- }
- return userAnchorAnnotation;
- }
-
- @SuppressWarnings({ "rawtypes" })
- protected Field getUserAnchorField(Class entityInterfaceClass, String fieldName) {
- Class nextClazz = entityInterfaceClass;
- while(nextClazz != null) {
- List fields = SyncHibernateUtils.getClassFields(nextClazz);
- Iterator itrFields = fields.iterator();
- while (itrFields.hasNext()) {
- Field nextField = itrFields.next();
- PropertyInterfaces nextEntityInterfacePropertiesA = nextField.getAnnotation(PropertyInterfaces.class);
-
- if (nextEntityInterfacePropertiesA != null && nextEntityInterfacePropertiesA.entityInterfaceClass() == entityInterfaceClass) {
- PropertyInterface[] propInterfaces = nextEntityInterfacePropertiesA.propertyInterfaces();
- for(PropertyInterface nextPropInterface : propInterfaces) {
- if (nextPropInterface.propertyName() != null && nextPropInterface.propertyName().equals(fieldName)) {
- // We have found the appropriate field.
- return nextField;
- }
- }
- }
- }
- nextClazz = nextClazz.getSuperclass();
- }
-
- return null;
- }
-
- @SuppressWarnings({ "rawtypes" })
- protected PropertyInterface getEntityPropertyInterfaceAnnotation(Class entityInterfaceClass, String fieldName) {
- Class nextClazz = entityInterfaceClass;
- while(nextClazz != null) {
- List fields = SyncHibernateUtils.getClassFields(nextClazz);
- Iterator itrFields = fields.iterator();
- while (itrFields.hasNext()) {
- Field nextField = itrFields.next();
- PropertyInterfaces nextEntityInterfacePropertiesA = nextField.getAnnotation(PropertyInterfaces.class);
-
- if (nextEntityInterfacePropertiesA != null && nextEntityInterfacePropertiesA.entityInterfaceClass() == entityInterfaceClass) {
- PropertyInterface[] propInterfaces = nextEntityInterfacePropertiesA.propertyInterfaces();
- for(PropertyInterface nextPropInterface : propInterfaces) {
- if (nextPropInterface.propertyName() != null && nextPropInterface.propertyName().equals(fieldName)) {
- // We have found the appropriate field.
- return nextPropInterface;
- }
- }
- }
- }
- nextClazz = nextClazz.getSuperclass();
- }
-
- return null;
- }*/
-
- protected IUserAnchor addOrUpdateUserAnchorFromServiceUserList(String userId, List serviceUserList, IUserAnchor result) {
- Session s = null;
- try {
- ManifestHelper.setManifest(manifest);
- //Set userIdentifierClasses = ManifestHelper.findImplementingClasses(IUserIdentifier.class);
- //Class userAnchorClass = ManifestHelper.findImplementingClass(IUserAnchor.class);
- EntityImplementation eiUserAnchor = null;
- List userAnchorEntityImplementations = MappedClass.findEntityImplementation(IUserAnchor.class);
- if (userAnchorEntityImplementations.size() > 0) {
- eiUserAnchor = userAnchorEntityImplementations.get(0);
- }
- List userIdentifierEntityImplementations = MappedClass.findEntityImplementation(IUserIdentifier.class);
-
- if (userIdentifierEntityImplementations.size() > 0) {
- List identifiersToSave = new ArrayList();
-
- Iterator itrUserIdentifierEntityImplementations = userIdentifierEntityImplementations.iterator();
- while (itrUserIdentifierEntityImplementations.hasNext()) {
- EntityImplementation userIdentifierEntityImplementation = itrUserIdentifierEntityImplementations.next();
-
- //MappedField userAnchorMappedField = userIdentifierEntityImplementation.getMappedFieldByName(userIdentifierAnnotation.userAnchorFieldName());
- PropertyImplementation userIdentifierPropImpl = userIdentifierEntityImplementation.findPropertyImplementationByName(IUserIdentifier.USER_IDENTIFIER_FIELD_NAME);
- RelationshipImplementation userAnchorRelImpl = userIdentifierEntityImplementation.findRelationshipImplementationBySourceVarName(IUserIdentifier.USER_ANCHOR_FIELD_NAME);
- //IUserIdentifierA userIdentifierAnnotation = getUserIdentifierAnnotation(userIdentifierEntityImplementation);
- if (userAnchorRelImpl != null) {
-
- if (s == null) {
- s = appSessionFactory.openSession();
- }
-
- // Get this userAnchor's identifier(s).
- String userIdentifierQueryString = "SELECT ui FROM " + userIdentifierEntityImplementation.mappedClass.tableName
- + " ui WHERE ui." + userIdentifierPropImpl.mappedField.getField().getName() + "=:value AND (ui." +
- userAnchorRelImpl.sourceMappedField.getField().getName() + " IS NULL OR ui." + userAnchorRelImpl.sourceMappedField.getField().getName() +
- " IN (SELECT ua FROM " + eiUserAnchor.mappedClass.tableName + " ua WHERE (ua.userId=null OR ua.userId='' OR ua.userId=:userId)))";
- for (ServiceUser nextServiceUser : serviceUserList) {
- for (ServiceIdentifier nextIdentifier : nextServiceUser.getIdentifiers()) {
- try {
- // Make sure this Identifier is in the same paradigm.
- String paradigm = null;
- Iterator itrParams = userIdentifierPropImpl.params.iterator();
- while (itrParams.hasNext()) {
- PropertyImplementationParam nextParam = itrParams.next();
- if (nextParam.name.equalsIgnoreCase(IUserIdentifier.PARADIGM_PARAM_NAME)) {
- paradigm = nextParam.value;
- break;
- }
- }
- if (nextIdentifier.getParadigm() == null || !nextIdentifier.getParadigm().equalsIgnoreCase(paradigm)) {
- continue;
- }
-
- // Look for this existing identifier.
- Query userIdentifierQuery = s.createQuery(userIdentifierQueryString);
- userIdentifierQuery.setString("userId", userId);
- userIdentifierQuery.setString("value", nextIdentifier.getValue());
- IUserIdentifier foundIdentifier = (IUserIdentifier) userIdentifierQuery.uniqueResult();
-
- if (foundIdentifier != null) {
- // If the email does not have a Person, then associate email with this Person.
- foundIdentifier = (IUserIdentifier) SyncHibernateUtils.cleanObject(foundIdentifier, s);
- IUserAnchor existingUserAnchor = (IUserAnchor) SyncHibernateUtils.cleanObject(userAnchorRelImpl.sourceMappedField.getGetter().invoke(foundIdentifier), s);
- if (existingUserAnchor == null) {
- if (result != null) {
- userAnchorRelImpl.sourceMappedField.getSetter().invoke(foundIdentifier, result);
- syncAgentService.systemPutObject((IPerceroObject) foundIdentifier, null, null, null, true);
- }
- else {
- identifiersToSave.add(foundIdentifier);
- }
- } else if (result == null) {
- result = existingUserAnchor;
- }
- } else { // Identifier object NOT found, need to add.
- // Identifier.identifierValue will be set later, once that is determined.
- IUserIdentifier newIdentifier = (IUserIdentifier) userIdentifierEntityImplementation.mappedClass.clazz.newInstance();
+ /* (non-Javadoc)
+ * @see com.com.percero.agents.auth.helpers.IAccountHelper#getUserRoles(java.lang.String)
+ */
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ public List getUserRoles(String userId) throws Exception {
+
+ ManifestHelper.setManifest(manifest);
+ IUserAnchor userAnchor = UserAnchorHelper.getUserAnchor(userId);
+ List result = RoleHelper.getUserRoleNames(userAnchor);
+
+ return result;
+ }
+
+ /**
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ protected IUserRoleA getUserRoleAnnotation(Class userRoleClass) {
+ IUserRoleA userRoleAnnotation = null;
+ Class nextClazz = userRoleClass;
+ while(userRoleAnnotation == null && nextClazz != null) {
+ userRoleAnnotation = (IUserRoleA) nextClazz.getAnnotation(IUserRoleA.class);
+ if (userRoleAnnotation == null)
+ nextClazz = nextClazz.getSuperclass();
+ }
+ return userRoleAnnotation;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ protected IUserIdentifierA getUserIdentifierAnnotation(Class userIdentifierClass) {
+ IUserIdentifierA userIdentifierAnnotation = null;
+ Class nextClazz = userIdentifierClass;
+ while(userIdentifierAnnotation == null && nextClazz != null) {
+ userIdentifierAnnotation = (IUserIdentifierA) nextClazz.getAnnotation(IUserIdentifierA.class);
+ if (userIdentifierAnnotation == null)
+ nextClazz = nextClazz.getSuperclass();
+ }
+ return userIdentifierAnnotation;
+ }
+
+ @SuppressWarnings({ "rawtypes", "unchecked" })
+ protected IUserAnchorA getUserAnchorAnnotation(Class userAnchorClass) {
+ IUserAnchorA userAnchorAnnotation = null;
+ Class nextClazz = userAnchorClass;
+ while(userAnchorAnnotation == null && nextClazz != null) {
+ userAnchorAnnotation = (IUserAnchorA) nextClazz.getAnnotation(IUserAnchorA.class);
+ if (userAnchorAnnotation == null)
+ nextClazz = nextClazz.getSuperclass();
+ }
+ return userAnchorAnnotation;
+ }
+
+ @SuppressWarnings({ "rawtypes" })
+ protected Field getUserAnchorField(Class entityInterfaceClass, String fieldName) {
+ Class nextClazz = entityInterfaceClass;
+ while(nextClazz != null) {
+ List fields = SyncHibernateUtils.getClassFields(nextClazz);
+ Iterator itrFields = fields.iterator();
+ while (itrFields.hasNext()) {
+ Field nextField = itrFields.next();
+ PropertyInterfaces nextEntityInterfacePropertiesA = nextField.getAnnotation(PropertyInterfaces.class);
+
+ if (nextEntityInterfacePropertiesA != null && nextEntityInterfacePropertiesA.entityInterfaceClass() == entityInterfaceClass) {
+ PropertyInterface[] propInterfaces = nextEntityInterfacePropertiesA.propertyInterfaces();
+ for(PropertyInterface nextPropInterface : propInterfaces) {
+ if (nextPropInterface.propertyName() != null && nextPropInterface.propertyName().equals(fieldName)) {
+ // We have found the appropriate field.
+ return nextField;
+ }
+ }
+ }
+ }
+ nextClazz = nextClazz.getSuperclass();
+ }
+
+ return null;
+ }
+
+ @SuppressWarnings({ "rawtypes" })
+ protected PropertyInterface getEntityPropertyInterfaceAnnotation(Class entityInterfaceClass, String fieldName) {
+ Class nextClazz = entityInterfaceClass;
+ while(nextClazz != null) {
+ List fields = SyncHibernateUtils.getClassFields(nextClazz);
+ Iterator itrFields = fields.iterator();
+ while (itrFields.hasNext()) {
+ Field nextField = itrFields.next();
+ PropertyInterfaces nextEntityInterfacePropertiesA = nextField.getAnnotation(PropertyInterfaces.class);
+
+ if (nextEntityInterfacePropertiesA != null && nextEntityInterfacePropertiesA.entityInterfaceClass() == entityInterfaceClass) {
+ PropertyInterface[] propInterfaces = nextEntityInterfacePropertiesA.propertyInterfaces();
+ for(PropertyInterface nextPropInterface : propInterfaces) {
+ if (nextPropInterface.propertyName() != null && nextPropInterface.propertyName().equals(fieldName)) {
+ // We have found the appropriate field.
+ return nextPropInterface;
+ }
+ }
+ }
+ }
+ nextClazz = nextClazz.getSuperclass();
+ }
+
+ return null;
+ }*/
+
+ protected IUserAnchor addOrUpdateUserAnchorFromServiceUserList(String userId, List serviceUserList, IUserAnchor result) {
+ log.debug("[AccountHelper] Add/Update UserAnchor for user " + userId);
+ try {
+ // TODO: why are we doing this everywhere?
+ ManifestHelper.setManifest(manifest);
+
+ EntityImplementation eiUserAnchor = UserAnchorHelper.getUserAnchorEntityImplementation();
+ List userIdentifierEntityImplementations = MappedClass.findEntityImplementation(IUserIdentifier.class);
+
+ List identifiersToSave = new ArrayList();
+
+ Iterator itrUserIdentifierEntityImplementations = userIdentifierEntityImplementations.iterator();
+ while (itrUserIdentifierEntityImplementations.hasNext()) {
+ EntityImplementation userIdentifierEntityImplementation = itrUserIdentifierEntityImplementations.next();
+
+ PropertyImplementation userIdentifierPropImpl = userIdentifierEntityImplementation.findPropertyImplementationByName(IUserIdentifier.USER_IDENTIFIER_FIELD_NAME);
+ RelationshipImplementation userAnchorRelImpl = userIdentifierEntityImplementation.findRelationshipImplementationBySourceVarName(IUserIdentifier.USER_ANCHOR_FIELD_NAME);
+
+ for (ServiceUser nextServiceUser : serviceUserList) {
+ for (ServiceIdentifier nextIdentifier : nextServiceUser.getIdentifiers()) {
+ try {
+ // Make sure this Identifier is in the same paradigm.
+ String paradigm = null;
+ Iterator itrParams = userIdentifierPropImpl.params.iterator();
+ while (itrParams.hasNext()) {
+ PropertyImplementationParam nextParam = itrParams.next();
+ if (nextParam.name.equalsIgnoreCase(IUserIdentifier.PARADIGM_PARAM_NAME)) {
+ paradigm = nextParam.value;
+ break;
+ }
+ }
+ if (nextIdentifier.getParadigm() == null || !nextIdentifier.getParadigm().equalsIgnoreCase(paradigm)) {
+ continue;
+ }
+
+ // Look for this existing identifier.
+ IUserIdentifier foundIdentifier = (IUserIdentifier) UserIdentifierHelper.getUserIdentifierForUserAndValue(userIdentifierEntityImplementation,result,nextIdentifier.getValue());
+
+
+ if (foundIdentifier == null) {
+ // Identifier object NOT found, need to add.
+ // Identifier.identifierValue will be set later, once that is determined.
+ IUserIdentifier newIdentifier = (IUserIdentifier) userIdentifierEntityImplementation.mappedClass.clazz.newInstance();
/*
IUserIdentifierA userIdentifierA = null;
Class nextClass = newIdentifier.getClass();
@@ -544,65 +426,56 @@ protected IUserAnchor addOrUpdateUserAnchorFromServiceUserList(String userId, Li
MappedField mappedField = mappedClass.getExternalizeFieldByName(userIdentifierA.userIdentifierFieldName());
mappedField.getSetter().invoke(newIdentifier, nextIdentifier.getValue());
*/
- userIdentifierPropImpl.mappedField.getSetter().invoke(newIdentifier, nextIdentifier.getValue());
- identifiersToSave.add(newIdentifier);
- }
- } catch(NonUniqueResultException nure) {
- log.warn("Non-unique User Identifier: " + nextIdentifier, nure);
- }
- }
- }
- }
- }
-
- if (s != null && s.isOpen()) {
- s.close();
- }
-
- // Need to create a new IUserAnchor
- if (result == null) {
- result = (IUserAnchor) eiUserAnchor.mappedClass.clazz.newInstance();
- ((IPerceroObject) result).setID(UUID.randomUUID().toString());
- result.setUserId(userId);
- if (serviceUserList.size() > 0) {
- /**
- IUserAnchorA userAnchorAnnotation = getUserAnchorAnnotation(userAnchorClass);
-
- if (userAnchorAnnotation.firstNameFieldName() != null && !userAnchorAnnotation.firstNameFieldName().isEmpty())
- firstNameMappedField = mcUserAnchor.getMappedFieldByName(userAnchorAnnotation.firstNameFieldName());
- MappedField lastNameMappedField = null;
- if (userAnchorAnnotation.lastNameFieldName() != null && !userAnchorAnnotation.lastNameFieldName().isEmpty())
- lastNameMappedField = mcUserAnchor.getMappedFieldByName(userAnchorAnnotation.lastNameFieldName());
- */
-
- // Find field that has firstName and lastName PropertyImplementations.
- PropertyImplementation firstNamePropImpl = eiUserAnchor.findPropertyImplementationByName(IUserAnchor.FIRST_NAME_FIELD);
- PropertyImplementation lastNamePropImpl = eiUserAnchor.findPropertyImplementationByName(IUserAnchor.LAST_NAME_FIELD);
-
- ServiceUser firstServiceUser = serviceUserList.get(0);
-
- if (firstNamePropImpl != null)
- firstNamePropImpl.mappedField.getSetter().invoke(result, firstServiceUser.getFirstName());
- if (lastNamePropImpl != null)
- lastNamePropImpl.mappedField.getSetter().invoke(result, firstServiceUser.getLastName());
- }
-
- syncAgentService.systemCreateObject((IPerceroObject) result, null);
-
- }
- else if (result.getUserId() == null || result.getUserId().isEmpty()) {
- result.setUserId(userId);
-
- syncAgentService.systemPutObject((IPerceroObject) result, null, null, null, true);
- }
-
- for (IUserIdentifier nextUserIdentifier : identifiersToSave) {
- // Set Email.person now that we have a firm handle on that Person object.
- Boolean isNewObject = false;
- if (((IPerceroObject)nextUserIdentifier).getID() == null || ((IPerceroObject)nextUserIdentifier).getID().isEmpty()) {
- isNewObject = true;
- ((IPerceroObject)nextUserIdentifier).setID(UUID.randomUUID().toString());
- }
+ userIdentifierPropImpl.mappedField.getSetter().invoke(newIdentifier, nextIdentifier.getValue());
+ identifiersToSave.add(newIdentifier);
+ }
+ } catch(NonUniqueResultException nure) {
+ log.warn("Non-unique User Identifier: " + nextIdentifier, nure);
+ }
+ }
+ }
+ }
+
+ // Need to create a new IUserAnchor
+ if (result == null) {
+ String id = UUID.randomUUID().toString();
+ log.debug("[AccountHelper] NO UserAnchor found for user " + userId + ", creating new UserAnchor with ID " + id);
+
+ result = (IUserAnchor) eiUserAnchor.mappedClass.clazz.newInstance();
+ ((IPerceroObject) result).setID(id);
+ result.setUserId(userId);
+ if (serviceUserList.size() > 0) {
+
+ // Find field that has firstName and lastName PropertyImplementations.
+ PropertyImplementation firstNamePropImpl = eiUserAnchor.findPropertyImplementationByName(IUserAnchor.FIRST_NAME_FIELD);
+ PropertyImplementation lastNamePropImpl = eiUserAnchor.findPropertyImplementationByName(IUserAnchor.LAST_NAME_FIELD);
+
+ ServiceUser firstServiceUser = serviceUserList.get(0);
+
+ if (firstNamePropImpl != null)
+ firstNamePropImpl.mappedField.getSetter().invoke(result, firstServiceUser.getFirstName());
+ if (lastNamePropImpl != null)
+ lastNamePropImpl.mappedField.getSetter().invoke(result, firstServiceUser.getLastName());
+ }
+
+ syncAgentService.systemCreateObject((IPerceroObject) result, null);
+ log.debug("[AccountHelper] UserAnchor " + id + " created");
+
+ }
+ else if (result.getUserId() == null || result.getUserId().isEmpty()) {
+ log.debug("[AccountHelper] Valid UserAnchor found but UserId is NOT set, updating UserAnchor for user " + userId);
+ result.setUserId(userId);
+ syncAgentService.systemPutObject((IPerceroObject) result, null, null, null, true);
+ log.debug("[AccountHelper] UserAnchor updated");
+ }
+
+ for (IUserIdentifier nextUserIdentifier : identifiersToSave) {
+ // Set Email.person now that we have a firm handle on that Person object.
+ Boolean isNewObject = false;
+ if (((IPerceroObject)nextUserIdentifier).getID() == null || ((IPerceroObject)nextUserIdentifier).getID().isEmpty()) {
+ isNewObject = true;
+ ((IPerceroObject)nextUserIdentifier).setID(UUID.randomUUID().toString());
+ }
/*
IUserIdentifierA userIdentifierAnnotation = getUserIdentifierAnnotation(nextUserIdentifier.getClass());
@@ -618,147 +491,116 @@ else if (result.getUserId() == null || result.getUserId().isEmpty()) {
}
*/
- IMappedClassManager mcm = MappedClassManagerFactory.getMappedClassManager();
- MappedClass mc = mcm.getMappedClassByClassName(nextUserIdentifier.getClass().getName());
- EntityImplementation entityImpl = mc.entityImplementations.get(IUserIdentifier.class);
- if (entityImpl != null) {
- RelationshipImplementation relImpl = entityImpl.findRelationshipImplementationBySourceVarName(IUserIdentifier.USER_ANCHOR_FIELD_NAME);
- if (relImpl != null) {
- relImpl.sourceMappedField.getSetter().invoke(nextUserIdentifier, result);
- if (isNewObject) {
- syncAgentService.systemCreateObject((IPerceroObject) nextUserIdentifier, null);
- }
- else {
- syncAgentService.systemPutObject((IPerceroObject) nextUserIdentifier, null, null, null, true);
- }
- }
- else {
- log.warn("No UserAnchor found for IUserIdentifier class " + nextUserIdentifier.getClass().getCanonicalName());
- }
- }
- }
-
- if (result != null) {
- setupUserRoles(userId, serviceUserList);
- return result;
- }
- }
-
- } catch (IllegalArgumentException e) {
- log.error(e.getMessage(), e);
- } catch (IllegalAccessException e) {
- log.error(e.getMessage(), e);
- } catch (InvocationTargetException e) {
- log.error(e.getMessage(), e);
- } catch (Exception e) {
- log.error(e.getMessage(), e);
- } finally {
- if (s != null && s.isOpen())
- s.close();
- }
-
- return null;
- }
-
- @SuppressWarnings({ "unchecked" })
- public void setupUserRoles(String userId, List serviceUserList) throws Exception {
- Session s = appSessionFactory.openSession();
-
- try {
- ManifestHelper.setManifest(manifest);
- EntityImplementation userAnchorEI = null;
- List userAnchorMappedClasses = MappedClass.findEntityImplementation(IUserAnchor.class);
- if (userAnchorMappedClasses.size() > 0) {
- userAnchorEI = userAnchorMappedClasses.get(0);
- }
- EntityImplementation userRoleEI = null;
- List userRoleMappedClasses = MappedClass.findEntityImplementation(IUserRole.class);
- if (userRoleMappedClasses.size() > 0) {
- userRoleEI = userRoleMappedClasses.get(0);
- }
-
- if (userAnchorEI != null && userRoleEI != null) {
- RelationshipImplementation userAnchorRelImpl = userRoleEI.findRelationshipImplementationBySourceVarName(IUserRole.USER_ANCHOR_FIELD_NAME);
-
- String userAnchorQueryString = "SELECT ua FROM " + userAnchorEI.mappedClass.tableName + " ua WHERE ua.userId=:userId";
- Query userAnchorQuery = s.createQuery(userAnchorQueryString);
- userAnchorQuery.setString("userId", userId);
-
- IUserAnchor userAnchor = (IUserAnchor) userAnchorQuery.uniqueResult();
-
- //IUserRoleA userRoleAnnotation = getUserRoleAnnotation(userRoleClass);
- String personRoleQueryString = "SELECT ur FROM " + userRoleEI.mappedClass.tableName
- + " ur WHERE ur." + userAnchorRelImpl.sourceMappedField.getField().getName() + " IN (SELECT ua FROM " + userAnchorEI.mappedClass.tableName + " ua WHERE ua.userId=:userId)";
- Query personRoleQuery = s.createQuery(personRoleQueryString);
- personRoleQuery.setString("userId", userId);
-
- List userRoles = (List) personRoleQuery.list();
- List updatedUserRoles = new ArrayList();
-
- // First, remove all roles that a Person has that are not in the serviceUserList.
- for(IUserRole nextUserRole : userRoles) {
- Boolean serviceUserRoleExists = false;
- Boolean isInaccurateList = false;
- for (ServiceUser nextServiceUser : serviceUserList) {
- if (!nextServiceUser.getAreRoleNamesAccurate()) {
- log.debug("Ignoring role names from " + nextServiceUser.getAuthProviderID().toString());
- isInaccurateList = true;
- break;
- }
- else {
- if (nextServiceUser.getRoleNames().contains(nextUserRole.getRoleName())) {
- serviceUserRoleExists = true;
- break;
- }
- }
- }
-
- if (!isInaccurateList && !serviceUserRoleExists) {
- log.warn("Deleting role " + nextUserRole.getRoleName() + " for " + userId);
- syncAgentService.systemDeleteObject(nextUserRole, null, true, new HashSet());
- } else
- updatedUserRoles.add(nextUserRole);
- }
-
- // Second, add all roles that are not on the Person.
- // Get MappedFields to set.
- //MappedField userAnchorMappedField = userRoleMappedClass.getMappedFieldByName(userRoleAnnotation.userAnchorFieldName());
- //MappedField userRoleDateCreatedField = userRoleMappedClass.getMappedFieldByName("dateCreated");
- //MappedField userRoleDateModifiedField = userRoleMappedClass.getMappedFieldByName("dateModified");
-
- for (ServiceUser nextServiceUser : serviceUserList) {
- if (nextServiceUser.getAreRoleNamesAccurate()) {
- // Role names from the service are accurate, so we can match them up here.
- for(String nextServiceRoleName : nextServiceUser.getRoleNames()) {
- Boolean personRoleExists = false;
- for(IUserRole nextUserRole : updatedUserRoles) {
- if (nextUserRole.getRoleName().equalsIgnoreCase(nextServiceRoleName)) {
- personRoleExists = true;
- break;
- }
- }
-
- if (!personRoleExists) {
- IUserRole nextPersonRole = (IUserRole) userRoleEI.mappedClass.clazz.newInstance();
- /*if (userRoleDateCreatedField != null)
- userRoleDateCreatedField.getSetter().invoke(nextPersonRole, currentDate);
- if (userRoleDateModifiedField != null)
- userRoleDateModifiedField.getSetter().invoke(nextPersonRole, currentDate);*/
- userAnchorRelImpl.sourceMappedField.getSetter().invoke(nextPersonRole, userAnchor);
-
- nextPersonRole.setRoleName(nextServiceRoleName);
- nextPersonRole.setID(UUID.randomUUID().toString());
-
- syncAgentService.systemCreateObject(nextPersonRole, null);
- }
- }
- }
- }
- }
- } catch (Exception e) {
- log.error("Unable to Get Person Roles", e);
- } finally {
- s.close();
- }
- }
+ IMappedClassManager mcm = MappedClassManagerFactory.getMappedClassManager();
+ MappedClass mc = mcm.getMappedClassByClassName(nextUserIdentifier.getClass().getName());
+ EntityImplementation entityImpl = mc.entityImplementations.get(IUserIdentifier.class);
+ if (entityImpl != null) {
+ RelationshipImplementation relImpl = entityImpl.findRelationshipImplementationBySourceVarName(IUserIdentifier.USER_ANCHOR_FIELD_NAME);
+ if (relImpl != null) {
+ relImpl.sourceMappedField.getSetter().invoke(nextUserIdentifier, result);
+ if (isNewObject) {
+ log.debug("[AccountHelper] Creating " + nextUserIdentifier.getClass().getCanonicalName() + ":" + ((IPerceroObject) nextUserIdentifier).getID() + " for user " + userId);
+ syncAgentService.systemCreateObject((IPerceroObject) nextUserIdentifier, null);
+ }
+ else {
+ log.debug("[AccountHelper] Updating " + nextUserIdentifier.getClass().getCanonicalName() + ":" + ((IPerceroObject) nextUserIdentifier).getID() + " for user " + userId);
+ syncAgentService.systemPutObject((IPerceroObject) nextUserIdentifier, null, null, null, true);
+ }
+ }
+ else {
+ log.warn("[AccountHelper] No UserAnchor found for IUserIdentifier class " + nextUserIdentifier.getClass().getCanonicalName());
+ }
+ }
+ }
+
+ if (result != null) {
+ setupUserRoles(userId, serviceUserList);
+ return result;
+ }
+
+
+ } catch (IllegalArgumentException e) {
+ log.error(e.getMessage(), e);
+ } catch (IllegalAccessException e) {
+ log.error(e.getMessage(), e);
+ } catch (InvocationTargetException e) {
+ log.error(e.getMessage(), e);
+ } catch (Exception e) {
+ log.error(e.getMessage(), e);
+ }
+
+ return null;
+ }
+
+ @SuppressWarnings({ "unchecked" })
+ public void setupUserRoles(String userId, List serviceUserList) throws Exception {
+ if(serviceUserList.size() <= 0) return; // Need this to keep the UserRoles from getting deleted, with the new auth stuff
+ try {
+ ManifestHelper.setManifest(manifest);
+ EntityImplementation userRoleEI = RoleHelper.getUserRoleEntityImplementation();
+ RelationshipImplementation userAnchorRelImpl = userRoleEI.findRelationshipImplementationBySourceVarName(IUserRole.USER_ANCHOR_FIELD_NAME);
+
+ IUserAnchor userAnchor = UserAnchorHelper.getUserAnchor(userId);
+ List userRoles = RoleHelper.getUserRoles(userAnchor);
+ List updatedUserRoles = new ArrayList();
+
+ // First, remove all roles that a Person has that are not in the serviceUserList.
+ for(IUserRole nextUserRole : userRoles) {
+ Boolean serviceUserRoleExists = false;
+ Boolean isInaccurateList = false;
+ for (ServiceUser nextServiceUser : serviceUserList) {
+ if (!nextServiceUser.getAreRoleNamesAccurate()) {
+ log.debug("Ignoring role names from " + nextServiceUser.getAuthProviderID().toString());
+ isInaccurateList = true;
+ break;
+ }
+ else {
+ if (nextServiceUser.getRoleNames().contains(nextUserRole.getRoleName())) {
+ serviceUserRoleExists = true;
+ break;
+ }
+ }
+ }
+
+ if (!isInaccurateList && !serviceUserRoleExists) {
+ log.warn("Deleting role " + nextUserRole.getRoleName() + " for " + userId);
+ syncAgentService.systemDeleteObject(nextUserRole, null, true, new HashSet());
+ } else
+ updatedUserRoles.add(nextUserRole);
+ }
+
+ // Second, add all roles that are not on the Person.
+ // Get MappedFields to set.
+ //MappedField userAnchorMappedField = userRoleMappedClass.getMappedFieldByName(userRoleAnnotation.userAnchorFieldName());
+ //MappedField userRoleDateCreatedField = userRoleMappedClass.getMappedFieldByName("dateCreated");
+ //MappedField userRoleDateModifiedField = userRoleMappedClass.getMappedFieldByName("dateModified");
+
+ for (ServiceUser nextServiceUser : serviceUserList) {
+ if (nextServiceUser.getAreRoleNamesAccurate()) {
+ // Role names from the service are accurate, so we can match them up here.
+ for(String nextServiceRoleName : nextServiceUser.getRoleNames()) {
+ Boolean personRoleExists = false;
+ for(IUserRole nextUserRole : updatedUserRoles) {
+ if (nextUserRole.getRoleName().equalsIgnoreCase(nextServiceRoleName)) {
+ personRoleExists = true;
+ break;
+ }
+ }
+
+ if (!personRoleExists) {
+ IUserRole nextPersonRole = (IUserRole) userRoleEI.mappedClass.clazz.newInstance();
+ userAnchorRelImpl.sourceMappedField.getSetter().invoke(nextPersonRole, userAnchor);
+
+ nextPersonRole.setRoleName(nextServiceRoleName);
+ nextPersonRole.setID(UUID.randomUUID().toString());
+
+ syncAgentService.systemCreateObject(nextPersonRole, null);
+ }
+ }
+ }
+ }
+ } catch (Exception e) {
+ log.error("Unable to Get Person Roles", e);
+ }
+ }
}
diff --git a/src/main/java/com/percero/agents/auth/helpers/RoleHelper.java b/src/main/java/com/percero/agents/auth/helpers/RoleHelper.java
new file mode 100644
index 0000000..1b2c5b1
--- /dev/null
+++ b/src/main/java/com/percero/agents/auth/helpers/RoleHelper.java
@@ -0,0 +1,76 @@
+package com.percero.agents.auth.helpers;
+
+import com.percero.agents.auth.vo.IUserAnchor;
+import com.percero.agents.auth.vo.IUserRole;
+import com.percero.agents.sync.dao.DAORegistry;
+import com.percero.agents.sync.dao.IDataAccessObject;
+import com.percero.agents.sync.metadata.EntityImplementation;
+import com.percero.agents.sync.metadata.MappedClass;
+import com.percero.agents.sync.metadata.RelationshipImplementation;
+import com.percero.framework.bl.ManifestHelper;
+import com.percero.framework.vo.IPerceroObject;
+
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Created by jonnysamps on 10/2/15.
+ */
+public class RoleHelper {
+
+ /**
+ * Gets a list of role names for a user
+ * @param userAnchor
+ * @return
+ */
+ public static List getUserRoleNames(IUserAnchor userAnchor){
+ List result = new ArrayList<>();
+ List roles = getUserRoles(userAnchor);
+
+ for(IUserRole role : roles)
+ result.add(role.getRoleName());
+
+ return result;
+ }
+
+ public static List getUserRoles(IUserAnchor userAnchor){
+ List result = new ArrayList<>();
+ Class userRoleClass = ManifestHelper.findImplementingClass(IUserRole.class);
+ RelationshipImplementation userAnchorRelImpl = getUserAnchorRI();
+
+ try {
+ // Now find the roles
+ IDataAccessObject userRoleDao =
+ (IDataAccessObject) DAORegistry.getInstance().getDataAccessObject(userRoleClass.getName());
+ IUserRole exampleRole = (IUserRole) userRoleClass.newInstance();
+
+ userAnchorRelImpl.sourceMappedField.getSetter().invoke(exampleRole, userAnchor);
+
+ List roleList = userRoleDao.findByExample(exampleRole, null, null, false);
+ for (IPerceroObject role : roleList) {
+ result.add((IUserRole) role);
+ }
+ }catch(Exception e){}
+
+ return result;
+ }
+
+ /**
+ * Finds the UserRole implementation
+ * @return
+ */
+ public static EntityImplementation getUserRoleEntityImplementation(){
+ EntityImplementation userRoleEI = null;
+ List userRoleMappedClasses = MappedClass.findEntityImplementation(IUserRole.class);
+ if (userRoleMappedClasses.size() > 0)
+ userRoleEI = userRoleMappedClasses.get(0);
+
+ return userRoleEI;
+ }
+
+ public static RelationshipImplementation getUserAnchorRI(){
+ RelationshipImplementation userAnchorRelImpl =
+ getUserRoleEntityImplementation().findRelationshipImplementationBySourceVarName(IUserRole.USER_ANCHOR_FIELD_NAME);
+ return userAnchorRelImpl;
+ }
+}
diff --git a/src/main/java/com/percero/agents/auth/helpers/UserAnchorHelper.java b/src/main/java/com/percero/agents/auth/helpers/UserAnchorHelper.java
new file mode 100644
index 0000000..a1e5ee3
--- /dev/null
+++ b/src/main/java/com/percero/agents/auth/helpers/UserAnchorHelper.java
@@ -0,0 +1,44 @@
+package com.percero.agents.auth.helpers;
+
+import com.percero.agents.auth.vo.IUserAnchor;
+import com.percero.agents.sync.dao.DAORegistry;
+import com.percero.agents.sync.dao.IDataAccessObject;
+import com.percero.agents.sync.metadata.EntityImplementation;
+import com.percero.agents.sync.metadata.MappedClass;
+import com.percero.agents.sync.services.DataProviderManager;
+import com.percero.agents.sync.services.IDataProvider;
+import com.percero.framework.bl.ManifestHelper;
+import com.percero.framework.vo.IPerceroObject;
+
+import java.util.List;
+
+/**
+ * Created by jonnysamps on 10/2/15.
+ */
+public class UserAnchorHelper {
+ public static IUserAnchor getUserAnchor(String userId){
+ IUserAnchor result = null;
+ Class userAnchorClass = ManifestHelper.findImplementingClass(IUserAnchor.class);
+
+ IDataProvider dataProvider = DataProviderManager.getInstance().getDefaultDataProvider();
+
+ try {
+ IUserAnchor example = (IUserAnchor) userAnchorClass.newInstance();
+ example.setUserId(userId);
+ List list = dataProvider.findByExample((IPerceroObject)example, null, null, false);
+ if(list.size() > 0)
+ result = (IUserAnchor)list.get(0);
+ }catch(Exception e){}
+
+ return result;
+ }
+
+ public static EntityImplementation getUserAnchorEntityImplementation(){
+ EntityImplementation userAnchorEI = null;
+ List userAnchorMappedClasses = MappedClass.findEntityImplementation(IUserAnchor.class);
+ if (userAnchorMappedClasses.size() > 0) {
+ userAnchorEI = userAnchorMappedClasses.get(0);
+ }
+ return userAnchorEI;
+ }
+}
diff --git a/src/main/java/com/percero/agents/auth/helpers/UserIdentifierHelper.java b/src/main/java/com/percero/agents/auth/helpers/UserIdentifierHelper.java
new file mode 100644
index 0000000..1386da2
--- /dev/null
+++ b/src/main/java/com/percero/agents/auth/helpers/UserIdentifierHelper.java
@@ -0,0 +1,51 @@
+package com.percero.agents.auth.helpers;
+
+import com.percero.agents.auth.vo.IUserAnchor;
+import com.percero.agents.auth.vo.IUserIdentifier;
+import com.percero.agents.sync.dao.DAORegistry;
+import com.percero.agents.sync.dao.IDataAccessObject;
+import com.percero.agents.sync.metadata.EntityImplementation;
+import com.percero.agents.sync.metadata.PropertyImplementation;
+import com.percero.agents.sync.metadata.RelationshipImplementation;
+import com.percero.framework.vo.IPerceroObject;
+
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Created by jonnysamps on 10/7/15.
+ */
+public class UserIdentifierHelper {
+ public static List getUserIdentifiersForUser(IUserAnchor user){
+ List result = new ArrayList<>();
+
+ return result;
+ }
+
+ public static IUserIdentifier getUserIdentifierForUserAndValue(EntityImplementation ei, IUserAnchor userAnchor, String value){
+
+ IUserIdentifier result = null;
+ IDataAccessObject dao =
+ (IDataAccessObject) DAORegistry.getInstance().getDataAccessObject(ei.mappedClass.className);
+ PropertyImplementation userIdentifierPropImpl = ei.findPropertyImplementationByName(IUserIdentifier.USER_IDENTIFIER_FIELD_NAME);
+ RelationshipImplementation userAnchorRelImpl = ei.findRelationshipImplementationBySourceVarName(IUserIdentifier.USER_ANCHOR_FIELD_NAME);
+
+ try {
+ IUserIdentifier example = (IUserIdentifier) ei.mappedClass.clazz.newInstance();
+ Method valueSetter = userIdentifierPropImpl.mappedField.getSetter();
+ valueSetter.invoke(example, value);
+ Method userSetter = userAnchorRelImpl.sourceMappedField.getSetter();
+ userSetter.invoke(example, userAnchor);
+ List list = dao.findByExample((IPerceroObject) example, null, null, false);
+ if(list.size() > 0)
+ result = (IUserIdentifier) list.get(0);
+
+ }catch(Exception e){}
+
+ return result;
+ }
+
+
+}
+
diff --git a/src/main/java/com/percero/agents/auth/services/AnonAuthProvider.java b/src/main/java/com/percero/agents/auth/services/AnonAuthProvider.java
index 629131c..6346ad4 100644
--- a/src/main/java/com/percero/agents/auth/services/AnonAuthProvider.java
+++ b/src/main/java/com/percero/agents/auth/services/AnonAuthProvider.java
@@ -1,9 +1,6 @@
package com.percero.agents.auth.services;
-import com.percero.agents.auth.vo.AuthProvider;
-import com.percero.agents.auth.vo.ServiceIdentifier;
-import com.percero.agents.auth.vo.ServiceOrganization;
-import com.percero.agents.auth.vo.ServiceUser;
+import com.percero.agents.auth.vo.*;
import com.percero.util.RandomStringGenerator;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@@ -31,7 +28,10 @@ public String getID() {
return ID;
}
- public ServiceUser authenticate(String credential) {
+ public AuthProviderResponse authenticate(String credential) {
+ AuthProviderResponse result = new AuthProviderResponse();
+ result.authCode = AuthCode.SUCCESS;
+
ServiceUser serviceUser = new ServiceUser();
serviceUser.setFirstName("ANON");
serviceUser.setLastName("ANON");
@@ -51,6 +51,7 @@ public ServiceUser authenticate(String credential) {
serviceUser.getEmails().add(email);
serviceUser.getIdentifiers().add(new ServiceIdentifier("email", email));
- return serviceUser;
+ result.serviceUser = serviceUser;
+ return result;
}
}
diff --git a/src/main/java/com/percero/agents/auth/services/AuthService.java b/src/main/java/com/percero/agents/auth/services/AuthService.java
index f39caaf..71b09bf 100644
--- a/src/main/java/com/percero/agents/auth/services/AuthService.java
+++ b/src/main/java/com/percero/agents/auth/services/AuthService.java
@@ -1,23 +1,13 @@
package com.percero.agents.auth.services;
-import java.util.ArrayList;
-import java.util.Date;
-import java.util.HashMap;
-import java.util.HashSet;
-import java.util.Iterator;
-import java.util.LinkedList;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.UUID;
-
+import com.percero.agents.auth.helpers.IAccountHelper;
+import com.percero.agents.auth.hibernate.AssociationExample;
+import com.percero.agents.auth.hibernate.AuthHibernateUtils;
+import com.percero.agents.auth.hibernate.BaseDataObjectPropertySelector;
+import com.percero.agents.auth.vo.*;
+import com.percero.agents.sync.access.IAccessManager;
import org.apache.log4j.Logger;
-import org.hibernate.Criteria;
-import org.hibernate.Query;
-import org.hibernate.Session;
-import org.hibernate.SessionFactory;
-import org.hibernate.StaleStateException;
-import org.hibernate.Transaction;
+import org.hibernate.*;
import org.hibernate.exception.LockAcquisitionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
@@ -25,21 +15,7 @@
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
-import com.percero.agents.auth.helpers.IAccountHelper;
-import com.percero.agents.auth.hibernate.AssociationExample;
-import com.percero.agents.auth.hibernate.AuthHibernateUtils;
-import com.percero.agents.auth.hibernate.BaseDataObjectPropertySelector;
-import com.percero.agents.auth.vo.AuthProvider;
-import com.percero.agents.auth.vo.OAuthResponse;
-import com.percero.agents.auth.vo.OAuthToken;
-import com.percero.agents.auth.vo.ServiceIdentifier;
-import com.percero.agents.auth.vo.ServiceUser;
-import com.percero.agents.auth.vo.SvcAppRole;
-import com.percero.agents.auth.vo.User;
-import com.percero.agents.auth.vo.UserAccount;
-import com.percero.agents.auth.vo.UserIdentifier;
-import com.percero.agents.auth.vo.UserToken;
-import com.percero.agents.sync.access.IAccessManager;
+import java.util.*;
/**
* The AuthService is responsible for managing authentication of users within the Percero framework. The AuthService
@@ -327,6 +303,18 @@ public OAuthResponse setupServiceUser(String authProviderID, ServiceUser service
UserAccount theFoundUserAccount = updateUserAccountToken(queryUserAccount, true, serviceUser);
if (theFoundUserAccount != null) {
+ try {
+ // Validate the user in the project database (by
+ // checking the IUserAnchor class)
+ // In the case that the UserAnchor object already exists
+ // in the project database but is NOT linked to the
+ // User, we need to link it here.
+ Object validateUserResult = accountHelper.validateUser(null, theFoundUserAccount.getUser().getID(), this);
+ System.out.println(validateUserResult);
+ } catch (Exception e) {
+ log.warn("Error validating user", e);
+ }
+
// Now check Service Application Roles.
Boolean foundMatchingRole = validateUserRoles(serviceUser, theFoundUserAccount.getUser().getID());
@@ -491,24 +479,6 @@ private UserAccount updateUserAccountToken(UserAccount theQueryObject, Boolean c
}
}
- /*
- if (serviceUser.getEmails() != null && serviceUser.getEmails().size() > 0) {
- String strFindUserIdentifier = "SELECT ui.user FROM UserIdentifier ui WHERE ui.type='email' AND (";
- int counter = 0;
- for(String nextEmail : serviceUser.getEmails()) {
- if (counter > 0)
- strFindUserIdentifier += " OR ";
- strFindUserIdentifier += "ui.userIdentifier='" + nextEmail + "'";
- counter++;
- }
- strFindUserIdentifier += ")";
- Query q = s.createQuery(strFindUserIdentifier);
- List userList = (List) q.list();
- if (userList.size() > 0) {
- theUser = userList.get(0);
- }
- }*/
-
Transaction tx = s.beginTransaction();
tx.begin();
Date currentDate = new Date();
@@ -575,33 +545,6 @@ private UserAccount updateUserAccountToken(UserAccount theQueryObject, Boolean c
}
tx.commit();
}
- /*
- if (serviceUser.getEmails() != null && serviceUser.getEmails().size() > 0) {
- if (s == null)
- s = sessionFactoryAuth.openSession();
- Transaction tx = s.beginTransaction();
- Query q = null;
- for(String nextEmail : serviceUser.getEmails()) {
- q = s.createQuery("FROM UserIdentifier ui WHERE ui.userIdentifier=:uid AND ui.type='email'");
- q.setString("uid", nextEmail);
-
- List userIdenditifierList = (List) q.list();
-
- if (userIdenditifierList.size() == 0) {
- try {
- UserIdentifier userIdentifier = new UserIdentifier();
- userIdentifier.setType("email");
- userIdentifier.setUser(theFoundUserAccount.getUser());
- userIdentifier.setUserIdentifier(nextEmail);
- s.saveOrUpdate(userIdentifier);
- } catch(Exception e) {
- log.warn("Unable to save Email UserIdentifier for " + serviceUser.getName(), e);
- }
- }
- }
- tx.commit();
- }
- */
}
} catch (Exception e) {
log.error("Unable to run authenticate UserAccount", e);
@@ -702,57 +645,68 @@ private UserToken loginUserAccount(UserAccount theUserAccount, String clientId,
/* (non-Javadoc)
* @see com.com.percero.agents.auth.services.IAuthService#logoutUser(java.lang.String, java.lang.String, java.lang.String)
*/
- @SuppressWarnings("rawtypes")
public Boolean logoutUser(String aUserId, String aToken, String aClientId) {
Boolean result = false;
- Boolean validUser = StringUtils.hasText(aUserId);
- Boolean validClient = StringUtils.hasText(aClientId);
+ boolean validUser = StringUtils.hasText(aUserId);
+ boolean validClient = StringUtils.hasText(aClientId);
+ boolean validToken = StringUtils.hasText(aToken);
// If neither a valid user or a valid client, then no one to logout.
- if (!validUser && !validClient) {
+ if (!validUser && !validClient && !validToken) {
+ log.warn("Invalid user/client/token on AuthService.logoutUser");
return false;
}
- log.debug("Logging out User: " + aUserId + ", Client: " + aClientId);
- User theQueryUser = new User();
- theQueryUser.setID(aUserId);
-
- UserToken theQueryUserToken = new UserToken();
- if (validUser) {
- theQueryUserToken.setUser(theQueryUser);
+ String deleteUserTokenSql = "DELETE FROM UserToken WHERE ";
+
+ // Match EITHER the ClientID OR the Token
+ if (validClient && validToken) {
+ log.debug("Logging out Client: " + aClientId + ", Token: " + aToken);
+ deleteUserTokenSql += " (clientId=:clientId OR token=:token) ";
}
- if (validClient) {
- theQueryUserToken.setClientId(aClientId);
+ else if (validToken) {
+ log.debug("Logging out Token: " + aToken);
+ log.debug("Logging out Token: " + aToken);
+ deleteUserTokenSql += " token=:token ";
}
-
- if (StringUtils.hasText(aToken)) {
- theQueryUserToken.setToken(aToken);
+ else if (validClient) {
+ log.debug("Logging out Client: " + aClientId);
+ deleteUserTokenSql += " clientId=:clientId ";
+ }
+ else if (validUser) {
+ // This will log out ALL of the User's devices, logging them out completely.
+ log.warn("Logging out ALL User " + aUserId + " devices!");
+ deleteUserTokenSql += " user_ID=:user_ID ";
}
- result = true;
- List userTokenResults = findByExample(theQueryUserToken, null);
- Iterator itrUserTokenResults = userTokenResults.iterator();
Session s = null;
- while (itrUserTokenResults.hasNext()) {
- UserToken userTokenResult = (UserToken) itrUserTokenResults.next();
+ try {
+ s = sessionFactoryAuth.openSession();
- try {
- if (s == null) {
- s = sessionFactoryAuth.openSession();
- }
- log.debug("Deleting UserToken: " + userTokenResult.getID() + ", Client: " + userTokenResult.getClientId());
- Transaction tx = s.beginTransaction();
- tx.begin();
- s.delete(userTokenResult);
- tx.commit();
- } catch (StaleStateException e) {
- // Most likely this failed because the userToken has already been deleted from the database.
- log.debug("Unable to delete UserToken due to StaleStateException: " + e.getMessage());
- result = false;
- } catch (Exception e) {
- log.error("Unable to delete UserToken", e);
- result = false;
+ Query deleteQuery = s.createSQLQuery(deleteUserTokenSql);
+
+ if (validClient && validToken) {
+ deleteQuery.setString("token", aToken);
+ deleteQuery.setString("clientId", aClientId);
+ }
+ else if (validToken) {
+ deleteQuery.setString("token", aToken);
+ }
+ else if (validClient) {
+ deleteQuery.setString("clientId", aClientId);
+ }
+ else if (validUser) {
+ deleteQuery.setString("user_ID", aUserId);
}
+
+ deleteQuery.executeUpdate();
+ } catch (StaleStateException e) {
+ // Most likely this failed because the userToken has already been deleted from the database.
+ log.debug("Unable to delete UserToken due to StaleStateException: " + e.getMessage());
+ result = false;
+ } catch (Exception e) {
+ log.error("Unable to delete UserToken", e);
+ result = false;
}
if (s != null && s.isOpen()) {
@@ -767,6 +721,8 @@ public Boolean logoutUser(String aUserId, String aToken, String aClientId) {
*/
// TODO: This function should also validate that the user is valid against the ServiceProvider's API.
public boolean validateUserByToken(String regAppKey, String aUserId, String aToken, String aClientId) {
+ log.debug("[AuthService] Validating user " + aUserId + " by token " + aToken + ", client " + aClientId + " NO existing clients");
+
boolean result = false;
if (/*StringUtils.hasText(regAppKey) && */StringUtils.hasText(aUserId) && StringUtils.hasText(aToken)) {
@@ -780,12 +736,16 @@ public boolean validateUserByToken(String regAppKey, String aUserId, String aTok
query.setString("clientId", aClientId);
Long uniqueResultCount = (Long) query.uniqueResult();
- if (uniqueResultCount != null && uniqueResultCount > 0)
+ if (uniqueResultCount != null && uniqueResultCount > 0) {
+ if (uniqueResultCount > 1) {
+ log.error("[AuthService] " + uniqueResultCount + " UserTokens found for user " + aUserId + ", token " + aToken + ", client " + aClientId);
+ }
result = true;
+ }
else
- log.warn("Invalid User in validateUserByToken: User " + aUserId + ", Token " + aToken + ", Client " + aClientId);
+ log.warn("[AuthService] Invalid User in validateUserByToken: User " + aUserId + ", Token " + aToken + ", Client " + aClientId);
} catch (Exception e) {
- log.error("Unable to validateUserByToken", e);
+ log.error("[AuthService] Unable to validateUserByToken", e);
result = false;
} finally {
if (s != null)
@@ -802,6 +762,8 @@ public boolean validateUserByToken(String regAppKey, String aUserId, String aTok
* @see com.com.percero.agents.auth.services.IAuthService#validateUserByToken(java.lang.String, java.lang.String, java.lang.String, java.lang.String, java.lang.String)
*/
public boolean validateUserByToken(String regAppKey, String aUserId, String aToken, String aClientId, Set existingClientIds) {
+ log.debug("[AuthService] Validating user " + aUserId + " by token " + aToken + ", client " + aClientId + " " + (existingClientIds != null && !existingClientIds.isEmpty() ? existingClientIds.size() + " existing clients" : " 0 existing clients"));
+
boolean result = false;
if (/*StringUtils.hasText(regAppKey) && */StringUtils.hasText(aUserId) && StringUtils.hasText(aToken)) {
@@ -828,21 +790,21 @@ public boolean validateUserByToken(String regAppKey, String aUserId, String aTok
result = true;
}
else {
- log.warn("Unable to update UserToken in validateUserByToken: User " + aUserId + ", Token " + aToken + ", Client " + aClientId);
+ log.warn("[AuthService] Unable to update UserToken in validateUserByToken: User " + aUserId + ", Token " + aToken + ", Client " + aClientId);
}
}
else {
- log.warn("Invalid User in validateUserByToken: User " + aUserId + ", Token " + aToken + ", Client " + aClientId);
+ log.warn("[AuthService] Invalid User in validateUserByToken: User " + aUserId + ", Token " + aToken + ", Client " + aClientId);
}
} catch (Exception e) {
- log.error("Unable to validateUserByToken", e);
+ log.error("[AuthService] Unable to validateUserByToken", e);
result = false;
} finally {
if (s != null)
s.close();
}
} else {
- log.warn("Invalid User in validateUserByToken");
+ log.warn("[AuthService] Invalid User in validateUserByToken");
}
return result;
@@ -1031,38 +993,44 @@ private static String getRandomId() {
**********************************************/
static final String DELETE_USER_TOKENS_COLLECTION_SQL = "DELETE FROM UserToken WHERE clientId IN (:clientIds)";
- @SuppressWarnings("unchecked")
+ private Set previousInvalidClientIds = new HashSet();
+
+// @SuppressWarnings("unchecked")
/**
* This method checks for any rogue/ghost UserTokens and removes them.
*/
// @Scheduled(fixedRate=30000) // 30 Seconds
@Scheduled(fixedDelay=300000, initialDelay=120000) // 5 Minutes, 2 Minutes
private void cleanupUserTokens() {
- Session s = null;
+// Session s = null;
try {
- s = sessionFactoryAuth.openSession();
+// s = sessionFactoryAuth.openSession();
int firstResultCounter = 0;
- int maxResults = 3;
- String userTokenQueryString = "SELECT DISTINCT(ut.clientId), ut.deviceId FROM UserToken ut ORDER BY ut.clientId";
- Query userTokenQuery = s.createQuery(userTokenQueryString);
- userTokenQuery.setMaxResults(maxResults);
- userTokenQuery.setFirstResult(firstResultCounter);
+ int maxResults = 30;
- // Gather up all clientIds to remove, then delete at the end.
List clientIdsToDelete = new LinkedList();
- List