feedburner

Subscribe to the site feed for newer articles

feedback-image

Driving security for ADF Essentials: Part 4

Labels: , ,

In this post i will share the security utility for performing operations on IAM Fortress applications using it’s java API’s. Use this utility only if you plan on having custom code to manage Fortress as fortress already provides a J2ee application to manage its policies. The code can be used coupled with earlier examples to integrate fortress as a security provider for your ADF essentials application. Also, you can make task flows for performing user, role, permission management using this utility.  The code is mentioned below.

 

package com.blogspot.ramannanda.security.fortress;

import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;

import oracle.adf.share.logging.ADFLogger;

import us.jts.fortress.AccessMgr;
import us.jts.fortress.AccessMgrFactory;
import us.jts.fortress.AdminMgr;
import us.jts.fortress.AdminMgrFactory;
import us.jts.fortress.DelAccessMgr;
import us.jts.fortress.DelAccessMgrFactory;
import us.jts.fortress.DelAdminMgr;
import us.jts.fortress.DelAdminMgrFactory;
import us.jts.fortress.DelReviewMgr;
import us.jts.fortress.DelReviewMgrFactory;
import us.jts.fortress.GlobalErrIds;
import us.jts.fortress.GlobalIds;
import us.jts.fortress.PasswordException;
import us.jts.fortress.PwPolicyMgr;
import us.jts.fortress.PwPolicyMgrFactory;
import us.jts.fortress.ReviewMgr;
import us.jts.fortress.ReviewMgrFactory;
import us.jts.fortress.SecurityException;
import us.jts.fortress.rbac.AdminRole;
import us.jts.fortress.rbac.OrgUnit;
import us.jts.fortress.rbac.PermObj;
import us.jts.fortress.rbac.Permission;
import us.jts.fortress.rbac.PwPolicy;
import us.jts.fortress.rbac.Role;
import us.jts.fortress.rbac.Session;
import us.jts.fortress.rbac.User;
import us.jts.fortress.rbac.UserAdminRole;
import us.jts.fortress.rbac.UserRole;


public class LDAPOperations {
public LDAPOperations() {
super();
}
public static final ADFLogger LDAPLogger = ADFLogger.createADFLogger(LDAPOperations.class);
Session rbacSession = null;

/**
This method is used to initialize a AccessMgr instance which can be used to manage access
* policies related to normal Users ie RBAC entities
* @return {@link us.jts.fortress.AccessMgr}
*/
public AccessMgr createAndGetAccessMgr() {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AccessMgr acMgr = null;
try {
acMgr = AccessMgrFactory.createInstance("");
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Exception occured in creating the instance of access manager",
e);
throw new RuntimeException("Unable to create AccessMgrInstance", e
);
}
return acMgr;
}



/**
* This method is used to initialize a DelAccessMgr entity which can be used to manage access
* policies related to Admin Users i.e ARBAC entities
* @return {@link us.jts.fortress.DelAccessMgr}
*/
public DelAccessMgr createAndGetDelAccessMgr() {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
DelAccessMgr acMgr = null;
try {
acMgr = DelAccessMgrFactory.createInstance(GlobalIds.HOME);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" +
"Exception occured in creating the instance of del access manager", e);
throw new RuntimeException("Unable to create DelAccessMgr Instance", e
);
}
return acMgr;
}
/**
* This method is used to initialize a PwPolicyManager entity which can be used to manage password
* policies for users
* @return {@link us.jts.fortress.PwPolicyMgr}
*/
private PwPolicyMgr createandGetPwPolicyManager() {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
PwPolicyMgr pwPolMgr = null;
try {
pwPolMgr = PwPolicyMgrFactory.createInstance(GlobalIds.HOME);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" +
"Exception occured in creating the instance of password policy manager", e);
throw new RuntimeException("Unable to create password policy Instance", e
);
}
return pwPolMgr;
}


/**
* This method returns an instance of AdminMgr
* This instance is then used to manage user modifications
* @return an instance of AdminMgr
*/
private AdminMgr createAndGetAdminMgr() {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr mgr = null;
try {
mgr = AdminMgrFactory.createInstance(GlobalIds.HOME);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to create AdminMgr Instance", e);
throw new RuntimeException("Unable to create AdminMgr Instance", e
);
}
return mgr;
}

/**
* This method returns an instance of DelAdminMgr
* this instance is used to manage admin users/roles
* @return an instance of {@link us.jts.fortress.DelAdminMgr}
*/
private DelAdminMgr createAndGetDelAdminMgr() {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
DelAdminMgr mgr = null;
try {
mgr = DelAdminMgrFactory.createInstance(GlobalIds.HOME);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to create DelAdminMgr Instance", e);
throw new RuntimeException("Unable to create DelAdminMgr Instance", e
);
}
return mgr;
}


/**
* This method Returns review manager instance which can be used to manage existing RBAC entities
* @return ReviewMgr
*/
private ReviewMgr createAndGetReviewManager() {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
ReviewMgr mgr = null;
try {
mgr = ReviewMgrFactory.createInstance(GlobalIds.HOME);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to create Review Manager Instance", e);
throw new RuntimeException("Unable to create Review Manager Instance", e
);
}
return mgr;
}

/**
* This method creates an instance of DelReviewManager and returns it
* This is used to search admin roles/permissions or create organizations
* @return An instance of {@link us.jts.fortress.DelReviewMgr}
*/
private DelReviewMgr createAndGetDelReviewManager() {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
DelReviewMgr mgr = null;
try {
mgr = DelReviewMgrFactory.createInstance(GlobalIds.HOME);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to create DelReviewManager Instance", e);
throw new RuntimeException("Unable to create DelReviewManager Instance", e
);
}
return mgr;
}

/**
* This method is used to search the password policies
* in OpenLdap
* @return a list of {@link us.jts.fortress.rbac.PwPolicy} objects
*/
public List<PwPolicy> searchPasswordPolicies(String policyName){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
PwPolicyMgr pwPolMgr = this.createandGetPwPolicyManager();
try{
return pwPolMgr.search(policyName);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to search password policies " + e.getMessage(), e);
throw new RuntimeException("Unable to search password policies", e );
}

}
/**
* This method is used to create the password policies
* in OpenLdap
* @param pol {@link us.jts.fortress.rbac.PwPolicy}
*/
public void createPasswordPolicy(PwPolicy pol){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
PwPolicyMgr pwPolMgr = this.createandGetPwPolicyManager();
try{
pwPolMgr.add(pol);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to create password policy " + e.getMessage(), e);
throw new RuntimeException("Unable to create password policy", e);
}

}

/**
* This method is used to update the password policies
* in OpenLdap
* @param pol {@link us.jts.fortress.rbac.PwPolicy}
*/
public void updatePasswordPolicy(PwPolicy pol){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
PwPolicyMgr pwPolMgr = this.createandGetPwPolicyManager();
try{
pwPolMgr.update(pol);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to update password policy " + e.getMessage(), e);
throw new RuntimeException("Unable to update password policy", e);
}

}
/**
* This method is used to check whether the password policies
* already exist in OpenLdap
* @param policyName the name of the password policy to check
*/
public boolean checkPasswordPolicyExists(String policyName){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
boolean policyExists=false;
PwPolicyMgr pwPolMgr = this.createandGetPwPolicyManager();
try{
PwPolicy pwPol=pwPolMgr.read(policyName);
if(pwPol!=null){
policyExists=true;
}

}catch (SecurityException e) {
LDAPLogger.info("[" + methodName + "]" + "Unable to search password policy " + e.getMessage());

}
return policyExists;
}
/**
* This method is used to delete the password policies
* in OpenLdap
* @param policyName the name of the password policy
*/
public void deletePasswordPolicy(String policyName){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
PwPolicyMgr pwPolMgr = this.createandGetPwPolicyManager();
PwPolicy pwPolicy=new PwPolicy(policyName);
try{
pwPolMgr.delete(pwPolicy);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to delete password policy " + e.getMessage(), e);
throw new RuntimeException("Unable to delete password policy", e);
}

}


/**
* This method is used to change the users' password
* @param userId the userId of the user
* @param oldPassword the old password of the user
* @param newPassword the new password of the user
*/
public void changePassword(String userId,String oldPassword,String newPassword){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
LDAPLogger.entering(LDAPOperations.class.getName(), methodName);
AdminMgr mgr=createAndGetAdminMgr();
User user=new User();
try{
user.setUserId(userId);
user.setPassword(oldPassword.toCharArray());
mgr.changePassword(user, newPassword.toCharArray());
LDAPLogger.exiting(LDAPOperations.class.getName(), methodName);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to change the password" + e.getMessage(), e);
throw new RuntimeException("Unable to change the password"+e.getMessage());
}

}
/**
* This method is used to reset the users' password
* @param userId the userId of the user
* @param newPassword the new password of the user
*/
public void resetPasswordForUser(String userId,String newPassword){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
LDAPLogger.entering(LDAPOperations.class.getName(), methodName);
AdminMgr mgr=createAndGetAdminMgr();
User user=new User();
try{
user.setUserId(userId);
mgr.resetPassword(user, newPassword.toCharArray());
LDAPLogger.exiting(LDAPOperations.class.getName(), methodName);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to change the password" + e.getMessage(), e);
throw new RuntimeException("Unable to change the password"+e.getMessage());
}

}
/**
* This method recursively deletes and organization and its permission objects/users
* Its descendants if any are there before deleting the organization
* @param orgUnit The orgUnit name
* @param delAdmMgr A delegated Admin Manager instance
* @param revMgr A Delegated review manager instance
* @param rvMgr A review manager instance
* @param admMgr A admin manager instance
* @return
*/
public Set recursiveDelete(OrgUnit orgUnit,DelAdminMgr delAdmMgr,DelReviewMgr revMgr,ReviewMgr rvMgr,AdminMgr admMgr){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
Set deletedOrganizationUnits=new HashSet();
try{
OrgUnit tempOrgUnit=revMgr.read(orgUnit);
Set children=tempOrgUnit.getChildren();
if(children!=null&&!children.isEmpty()){
Iterator it=children.iterator();
while(it.hasNext()){
OrgUnit newOrgUnit=new OrgUnit();
newOrgUnit.setName((String)it.next());
newOrgUnit.setType(orgUnit.getType());
delAdmMgr.deleteInheritance(orgUnit, newOrgUnit);
deletedOrganizationUnits.addAll(recursiveDelete(newOrgUnit,delAdmMgr,revMgr,rvMgr,admMgr));
}
}
//check for users belonging to this organization unit
else{
//check if user organization
if(tempOrgUnit.getType().equals(OrgUnit.Type.USER)){
List<User> users=rvMgr.findUsers(tempOrgUnit);
if(!users.isEmpty()){
Iterator it=users.iterator();
while(it.hasNext()){
User user=(User)it.next();
admMgr.deleteUser(user);
}
}
}
else{
List <PermObj> permObjs=rvMgr.findPermObjs(tempOrgUnit);
if(!permObjs.isEmpty()){
Iterator it=permObjs.iterator();
while(it.hasNext()){
PermObj permObj=(PermObj)it.next();
//check permObj is admin or not
if(permObj.isAdmin()){
delAdmMgr.deletePermObj(permObj);
}else{
admMgr.deletePermObj(permObj);
}
}
}
}

}

delAdmMgr.delete(tempOrgUnit);

deletedOrganizationUnits.add(tempOrgUnit.getName());
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Exception Occured" + e.getMessage(), e);
throw new RuntimeException("Exception Occurred", e);
}
return deletedOrganizationUnits;
}

/**
* To delete an organization
* @param orgUnit the orgUnit to delete
*/
public Set deleteOrganization(OrgUnit orgUnit){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
Set deletedOrganizations=new HashSet();
LDAPLogger.entering(LDAPOperations.class.getName(), methodName);
//call recursive delete
DelAdminMgr delAdmMgr=createAndGetDelAdminMgr();
AdminMgr adminMgr = createAndGetAdminMgr();
DelReviewMgr delReviewMgr = createAndGetDelReviewManager();
ReviewMgr rvMgr = createAndGetReviewManager();
Set deletedOrgs=recursiveDelete(orgUnit, delAdmMgr, delReviewMgr, rvMgr, adminMgr);
if(deletedOrgs!=null){
deletedOrganizations.addAll(deletedOrgs);
}
LDAPLogger.exiting(LDAPOperations.class.getName(), methodName);
return deletedOrganizations;
}
/**
* To check whether an organization exists or not
* @param orgType the organization type
* @param orgUnitName the orgUnitName
* @return OrgUnit if organization found else return false
*/
public OrgUnit getOrganizationUnit(String orgType,String orgUnitName){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
OrgUnit orgUnit=new OrgUnit();
orgUnit.setName(orgUnitName);
if(orgType.equalsIgnoreCase("PERM")){
orgUnit.setType(OrgUnit.Type.PERM);
}
else{
orgUnit.setType(OrgUnit.Type.USER);
}
DelReviewMgr delRvMgr=createAndGetDelReviewManager();
OrgUnit tempOrgUnit=null;
try{
tempOrgUnit=delRvMgr.read(orgUnit);
return tempOrgUnit;
}catch (SecurityException e) {
LDAPLogger.info("[" + methodName + "]" + "Unable to read organization unit " + e.getMessage(), e);
throw new RuntimeException("Unable to read organization unit", e);
}
}
/**
* To check whether an organization exists or not
* @param orgUnit the orgUnit to check
* @return true if organization exists else false
*/
public boolean checkOrganizationExists(OrgUnit orgUnit){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
boolean orgExists=false;
DelReviewMgr delRvMgr=createAndGetDelReviewManager();
OrgUnit tempOrgUnit=null;
try{
tempOrgUnit=delRvMgr.read(orgUnit);
if(tempOrgUnit!=null){
orgExists=true;
}
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Organization not found " + e.getMessage());
}
return orgExists;
}
/**
* To create an organization
* @param orgUnit the orgUnit to create
*/
public void createOrganizationUnit(OrgUnit orgUnit){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
DelAdminMgr delAdmMgr=createAndGetDelAdminMgr();
try{
delAdmMgr.add(orgUnit);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to create organization unit " + e.getMessage(), e);
throw new RuntimeException("Unable to create organization unit", e);
}

}
/**
* To update an organization
* @param orgUnit the orgUnit to delete
*/
public void updateOrganizationUnit(OrgUnit orgUnit){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
DelAdminMgr delAdmMgr=createAndGetDelAdminMgr();
try{
delAdmMgr.update(orgUnit);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to update organization unit " + e.getMessage(), e);
throw new RuntimeException("Unable to update organization unit", e);
}

}
/**
* This method is used to retrieve all the organizations available in
* fortress that match the criteria
* @param orgType Organization Type whether User organization or Permission Organization
* @param orgName the organization name
* @return A list of OrgUnit Objects
*/
public List<OrgUnit> searchOrganizations(String orgType,String orgName){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
DelReviewMgr delRevMgr=createAndGetDelReviewManager();
try{
if(orgType.trim().equalsIgnoreCase("perm"))
{
return delRevMgr.search(OrgUnit.Type.PERM, orgName);
}
else{
return delRevMgr.search(OrgUnit.Type.USER, orgName);
}


}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to search organization units " + e.getMessage(), e);
throw new RuntimeException("Unable to search organization units", e );
}

}
/**
* Returns a list of users based on the userId
* @param userId the user id of the user it can be partial
* @return
*/
public List<User> searchUsers(String userId){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
ReviewMgr mgr=createAndGetReviewManager();
List <User> users=null;
User user=new User(userId);
try {
users=mgr.findUsers(user);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to search user " + e.getMessage(), e);
throw new RuntimeException("Unable to search user", e );
}
return users;
}
/**
* Returns a list of roles based on the userId
* @param userId the user id of the user it can be partial
* @return
*/
public List<UserRole> searchUserRoles(String userId){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
ReviewMgr mgr=createAndGetReviewManager();
List <UserRole> roles=null;
List<User> users=null;
User user=new User(userId);
try {
users=mgr.findUsers(user);
if(users!=null&&!users.isEmpty()){
roles=users.get(0).getRoles();
}

} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to search roles for user " + e.getMessage(), e);
throw new RuntimeException("Unable to search roles for user", e );
}
return roles;
}
/**
* Returns a list of admin roles based on the userId
* @param userId the user id of the user it can be partial
* @return
*/
public List<UserAdminRole> searchUserAdminRoles(String userId){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
DelReviewMgr delRevMgr=createAndGetDelReviewManager();
List <UserAdminRole> roles=null;
User user=new User(userId);
try {
roles= delRevMgr.assignedRoles(user);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to search admin roles for user " + e.getMessage(), e);
throw new RuntimeException("Unable to search admin roles for user", e );
}
return roles;
}

/**
* This method is used to retrieve all the application/normal roles from the target system
* @return a Set of rolenames
*/
public List<String> getAllRoles(){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
List<String> roles=new ArrayList<String>();
List<Role> searchedRoles=null;
ReviewMgr rvMgr=createAndGetReviewManager();
try{
searchedRoles=rvMgr.findRoles("");
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to search roles " + e.getMessage(), e);
throw new RuntimeException("Unable to search roles ", e );
}
if(searchedRoles!=null && !searchedRoles.isEmpty()){
Iterator roleIterator=searchedRoles.iterator();
while(roleIterator.hasNext()){
roles.add(((Role)roleIterator.next()).getName());
}
}
return roles;
}

/**
* This method is used to retrieve all the application/normal roles from the target system
* @return a List of Role
*/
public List<Role> searchRoles(String roleName){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
List<Role> searchedRoles=null;
ReviewMgr rvMgr=createAndGetReviewManager();
try{
if(roleName==null || roleName.isEmpty()){
searchedRoles=rvMgr.findRoles("");
}
else{
searchedRoles=rvMgr.findRoles(roleName);
}
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to search roles " + e.getMessage(), e);
throw new RuntimeException("Unable to search roles ", e );
}

return searchedRoles;
}
/**
* This method is used to retrieve all the Admin roles from the target system
* @return a Set of admin rolenames
*/
public List<String> getAllAdminRoles(){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
List<String> roles=new ArrayList<String>();
List<AdminRole> searchedRoles=null;
DelReviewMgr delRvMgr=createAndGetDelReviewManager();
try{
searchedRoles=delRvMgr.findRoles("");
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to search admin roles " + e.getMessage(), e);
throw new RuntimeException("Unable to search admin roles ", e );
}
if(searchedRoles!=null && !searchedRoles.isEmpty()){
Iterator roleIterator=searchedRoles.iterator();
while(roleIterator.hasNext()){
roles.add(((Role)roleIterator.next()).getName());
}
}
return roles;
}
/**
* This method is used to retrieve all the Admin roles from the target system
* @return a List of AdminRole
*/
public List<AdminRole> searchAdminRoles(String roleName){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
List<AdminRole> searchedRoles=null;
DelReviewMgr delRvMgr=createAndGetDelReviewManager();
try{
if(roleName==null || roleName.isEmpty()){
searchedRoles=delRvMgr.findRoles("");
}
else {
searchedRoles=delRvMgr.findRoles(roleName);
}
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to search admin roles " + e.getMessage(), e);
throw new RuntimeException("Unable to search admin roles ", e );
}

return searchedRoles;
}
/**
* This method is used to return all the parent permission objects
* @param isAdmin Checks whether to search for Admin Perm Objs or Normal Perm Objs
* @return a list of {@link us.jts.fortress.rbac.PermObj}
*/
public List<PermObj> getAllPermObjs(boolean isAdmin){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
List<PermObj> permObjs=null;
ReviewMgr rvMgr=createAndGetReviewManager();
PermObj temp=new PermObj("");
temp.setAdmin(true);
try{
permObjs=rvMgr.findPermObjs(temp);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to search Perm Objs " + e.getMessage(), e);
throw new RuntimeException("Unable to search Perm Objs ", e );
}

return permObjs;
}

/**
* It creates a role in the system
* @param role A {@link us.jts.fortress.rbac.Role} or {@link us.jts.fortress.rbac.AdminRole} instance
* @see Role AdminRole
*/
public void createRole(Role role, AdminRole adminRole) {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
if(role!=null){
AdminMgr mgr = createAndGetAdminMgr();
try {
mgr.addRole(role);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to add Role " + e.getMessage(), e);
throw new RuntimeException("Unable to add Role", e );
}

}
else if(adminRole!=null){
DelAdminMgr delMgr = createAndGetDelAdminMgr();
try {
delMgr.addRole(adminRole);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to add Admin Role " + e.getMessage(), e);
throw new RuntimeException("Unable to add Admin Role", e );
}
}

}

/**
* This method is used to update an existing role
* The role constraints can be updated but the role name cannot be updated
* @param role conditionally required either role or admin role must exist
* @param adminRole conditionally required either role or admin role is required
*/
public void updateRole(Role role,AdminRole adminRole){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
if(role==null){
delAdminMgr = createAndGetDelAdminMgr();
try {
delAdminMgr.updateRole(adminRole);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to update the Admin role ["+adminRole.getName()+"]",e);
throw new RuntimeException("Unable to assign user to the given role", e
);
}
}
else{
adminMgr = createAndGetAdminMgr();
try {
adminMgr.updateRole(role);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to update the role ["+role.getName()+"]",e);
throw new RuntimeException("Unable to assign user to the given role", e
);
}

}

}

/**
* This method is used to delete an existing role
* @param roleName The name of the role
* @param isAdmin A flag that checks whether role is an ARBAC role or RBAC role.
*/
public void deleteRole(String roleName, boolean isAdmin){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
if(isAdmin){
delAdminMgr = createAndGetDelAdminMgr();
AdminRole role=new AdminRole(roleName);
try {
delAdminMgr.deleteRole(role);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to delete the Admin role ["+roleName+"]",e);
throw new RuntimeException("Unable to assign user to the given role", e
);
}
}
else{
Role role=new Role(roleName);
adminMgr = createAndGetAdminMgr();
try {
adminMgr.deleteRole(role);
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to update the role ["+roleName+"]",e);
throw new RuntimeException("Unable to assign user to the given role", e
);
}

}


}

/**
* This method checks whether the role has already been assigned the permission
* @param perm the permission name
* @param roleName the roleName to search
* @return
*/
public boolean checkRoleAlreadyAssignedPermission(Permission perm,String roleName){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
LDAPLogger.entering(LDAPOperations.class.getName(), methodName);
boolean roleAlreadyAssignedPermission=false;
ReviewMgr rvMgr = null;
try {
rvMgr=createAndGetReviewManager();
Permission permission = rvMgr.readPermission(perm);
if(permission!=null){
Set roles=permission.getRoles();
if(roles!=null){
Iterator it=roles.iterator();
while(it.hasNext()){
String tempRole=(String)it.next();
if(tempRole.equals(roleName)){
return true;
}
}
}
}
}catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign user to the given role ["+roleName+"]");
}
return roleAlreadyAssignedPermission;
}

/**
* The role to be assigned
* @param user the username of the user
* @param roleName the rolename of the role
* @return
*/
public boolean checkRoleAlreadyAssigned(String user,String roleName){
boolean roleExists=false;
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
ReviewMgr rvMgr = createAndGetReviewManager();
User checkUser = new User(user);
try {
checkUser = rvMgr.readUser(checkUser);
List<UserRole>userRoles=checkUser.getRoles();
if(userRoles!=null && !userRoles.isEmpty()){
Iterator it=userRoles.iterator();
while(it.hasNext()){
UserRole userRole=(UserRole)it.next();
if(userRole.getName().equals(roleName))
{
roleExists=true;
return roleExists;
}
}
}
} catch (SecurityException e) {
if (e.getErrorId() == GlobalErrIds.USER_NOT_FOUND) {
roleExists = false;
} else {
LDAPLogger.severe("[" + methodName + "]" + "A system exception was encountered", e);
throw new RuntimeException("A system exception was encountered", e
);
}
}
return roleExists;
}
/**
* Assigns the specified role to the user
* @param roleName the role to assign
* @param userName the user to assign role to
*/
public void assignRoleToUser(String roleName, String userName, boolean isAdmin) {
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
UserAdminRole role = new UserAdminRole(userName, roleName);
try {
delAdminMgr.assignUser(role);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign user to the given role ["+roleName+"]",e);
throw new RuntimeException("Unable to assign user to the given role", e
);
}
} else{
adminMgr = createAndGetAdminMgr();
UserRole role = new UserRole(userName, roleName);
try {
adminMgr.assignUser(role);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign user to the given role ["+roleName+"]",e);
throw new RuntimeException("Unable to assign user to the given role", e
);
}

}


}
/**
* Removes the specified role from the user
* @param roleName the role to revoke
* @param userName the user from whom to revoke the role
*/
public void removeRoleFromUser(String roleName, String userName, boolean isAdmin) {
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
UserAdminRole role = new UserAdminRole(userName, roleName);
try {
delAdminMgr.deassignUser(role);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to deassign user from the given admin role ["+roleName+"]",e);
throw new RuntimeException("Unable to deassign user from the given role", e
);
}
} else{
adminMgr = createAndGetAdminMgr();
UserRole role = new UserRole(userName, roleName);
try {
adminMgr.deassignUser(role);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to deassign user from the given role :"+roleName,e);
throw new RuntimeException("Unable to assign user to the given role", e
);
}

}
}

/**
* This method check whether a permission already exists
* @param perm the permission object to read
* @return true if permission already exists
*/
public boolean checkPermissionExists(Permission perm){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
boolean permissionAlreadyExists=false;
Permission tempPerm=null;
ReviewMgr rvMgr=createAndGetReviewManager();
try{
tempPerm=rvMgr.readPermission(perm);
if(tempPerm!=null){
permissionAlreadyExists=true;
}
}catch (SecurityException e) {
LDAPLogger.info("[" + methodName + "]" + "Unable to read the permission");
}
return permissionAlreadyExists;
}
/**
* This method check whether a permission already exists
* @param permObj the permobj to read
* @return true if permission object already exists
*/
public boolean checkPermObjExists(PermObj permObj){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
boolean permObjExists=false;
PermObj obj=null;
ReviewMgr rvMgr=createAndGetReviewManager();
try{
obj=rvMgr.readPermObj(permObj);
if(obj!=null){
permObjExists=true;
}
}catch (SecurityException e) {
LDAPLogger.info("[" + methodName + "]" + "Unable to read the permission object");
}
return permObjExists;
}

/**
* This method checks whether the role is already present in the system or not
* @param roleName The roleName to search
* @param roleType the roletype Admin or Normal
* @return
*/
public boolean checkRoleExists(String roleName, String roleType){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
boolean roleAlreadyExists=false;
if(roleType.equalsIgnoreCase("Admin")){
AdminRole role=new AdminRole();
AdminRole tempRole;
DelReviewMgr delRvMgr=createAndGetDelReviewManager();
try{
tempRole=delRvMgr.readRole(role);
if(tempRole!=null){
roleAlreadyExists=true;
}
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to find role " + e.getMessage());
}
}
else{

Role searchedRoles=null;
Role role=new Role(roleName);
ReviewMgr rvMgr=createAndGetReviewManager();
try{
searchedRoles=rvMgr.readRole(role);
if(searchedRoles!=null){
roleAlreadyExists=true;
}
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to find role " + e.getMessage(), e);
}
}
return roleAlreadyExists;

}
/**
* Assigns the specified set of roles to the user
* @param roleNames the roles to assign
* @param userName the user to assign role to
* @return the set of roles that were succesfully assigned
*/
public Set assignRolesToUser(Set roleNames, String userName, boolean isAdmin) {
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
Set rolesAssigned = new HashSet();
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
Iterator it = roleNames.iterator();
if(isAdmin){
delAdminMgr = createAndGetDelAdminMgr();
while (it.hasNext()) {
String roleName = (String)it.next();
UserAdminRole role = new UserAdminRole(userName,roleName);
try {
delAdminMgr.assignUser(role);
rolesAssigned.add(roleNames);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign user to the given admin role[ "+roleName+" ]",e);
}
}
}
else{
adminMgr = createAndGetAdminMgr();
while (it.hasNext()) {
String roleName = (String)it.next();
UserRole role = new UserRole(userName,roleName);
try {
adminMgr.assignUser(role);
rolesAssigned.add(roleNames);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign user to the given role[ "+roleName+" ]",e);
}
}
}
return rolesAssigned;
}

/**
* Removes the specified set of roles from the user
* @param roleNames the roles to revoke
* @param userName the user from whom to revoke the role
* @return the set of roles that were succesfully removed
*/
public Set removeRolesFromUser(Set roleNames, String userName, boolean isAdmin) {
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
Set rolesRevoked = new HashSet();
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
Iterator it = roleNames.iterator();
if(isAdmin){
delAdminMgr = createAndGetDelAdminMgr();
while (it.hasNext()) {
String roleName = (String)it.next();
UserAdminRole role = new UserAdminRole(userName,roleName);
try {
delAdminMgr.deassignUser(role);
rolesRevoked.add(roleNames);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to revoke user from the given admin role[ "+roleName+" ]",e);
}
}
}
else{
adminMgr = createAndGetAdminMgr();
while (it.hasNext()) {
String roleName = (String)it.next();
UserRole role = new UserRole(userName,roleName);
try {
adminMgr.deassignUser(role);
rolesRevoked.add(roleNames);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to revoke user from the given role[ "+roleName+" ]",e);
}
}
}
return rolesRevoked;
}
/**
* It is used to generate a random password
*@code{
* generateRandomPassword();
* }
* @return
*/
public String generateRandomPassword() {
String password = Long.toHexString(Double.doubleToLongBits(Math.random()));
int passLength = password.length();
if (passLength >= 8) {
password = password.substring(passLength - 8, passLength);
}

return password;
}
/**
* It is used to generate a random password
*@code{
* generateRandomPassword(8);
* }
* @return
*/
public String generateRandomPassword(String minLength) {
String password = Long.toHexString(Double.doubleToLongBits(Math.random()));
int passLength = password.length();
if (passLength >= minLength.length()) {
password = password.substring(passLength - minLength.length(), passLength);
}

return password;
}

/**
* To check whether user already exists or not
* @param userId The user Id to check
* @return true if user exists
*/
public boolean checkUserExists(String userId){
boolean userExists=false;
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
ReviewMgr rvMgr = createAndGetReviewManager();
User checkUser = new User(userId);
try {
checkUser = rvMgr.readUser(checkUser);
userExists=true;
} catch (SecurityException e) {
if (e.getErrorId() == GlobalErrIds.USER_NOT_FOUND) {
userExists = false;
} else {
LDAPLogger.severe("[" + methodName + "]" + "A system exception was encountered", e);
throw new RuntimeException("A system exception was encountered", e
);
}
}
return userExists;
}

/**
* Creates a user within the specified OU
* the user is of a standard inetOrgPerson class
* this method checks whether a user already exists in the system
* and if it does it replaces the user
* @param user the user with the profile attributes
* @param generatePassword whether to generate password or not
* @return the generatedPassword
*/
public String createUser(User user,boolean generatePassword) {
String generatedPassword=null;
if(user.getPassword()!=null){
generatedPassword = new String(user.getPassword());
}
boolean deleteUser = true;
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adMgr = createAndGetAdminMgr();
ReviewMgr rvMgr = createAndGetReviewManager();
User tempUser = null;
try {
tempUser = rvMgr.readUser(user);
} catch (SecurityException e) {
if (e.getErrorId() == GlobalErrIds.USER_NOT_FOUND) {
deleteUser = false;
} else {
LDAPLogger.severe("[" + methodName + "]" + "A system exception was encountered", e);
throw new RuntimeException("A system exception was encountered", e
);
}

}
if (deleteUser) {
try {
adMgr.deleteUser(tempUser);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" +
"A system exception was encountered:Unable to delete the existing user", e);
throw new RuntimeException("Unable to delete the existing user", e
);
}
}

try {
if(generatePassword){
generatedPassword = generateRandomPassword();
user.setPassword(generatedPassword.toCharArray());
}
adMgr.addUser(user);

} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "A system exception was encountered while creating a user", e);
throw new RuntimeException("Unable to create the user", e );
}
return generatedPassword;

}
/**
* Updates an existing user
* @param user the user with the profile attributes
* @param generatePassword whether to generate password or not
* @return the generatedPassword
*/
public String updateUser(User user,boolean generatePassword) {
String generatedPassword=null;
if(user.getPassword()!=null){
generatedPassword = new String(user.getPassword());
}
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adMgr = createAndGetAdminMgr();
try {
if(generatePassword){
generatedPassword = generateRandomPassword();
user.setPassword(generatedPassword.toCharArray());
}
adMgr.updateUser(user);

} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "A system exception was encountered while updating a user", e);
throw new RuntimeException("Unable to update the user", e );
}
return generatedPassword;

}

/**
* Drops the existing user
* @param user the user that needs to be dropped
*/
public void dropUser(User user) {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adMgr = createAndGetAdminMgr();
try {
adMgr.deleteUser(user);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" +
"A system exception was encountered:Unable to delete the existing user", e);
throw new RuntimeException("Unable to delete the existing user", e
);
}
}

/**
* This method can be used to create Admin or Normal Permission
* @param permObj The name of the permission object @see us.jts.fortress.rbac.PermObj
* @param permissions a set of permissions associated with the permission object
* @param isAdmin flag to see whether to provision admin permissions or Application Permissions.
*/
public void createPermissions(PermObj permObj, Set permissions, boolean isAdmin) {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;

Iterator it = permissions.iterator();
if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
try {
delAdminMgr.addPermObj(permObj);


while (it.hasNext()) {
String permissionName = (String)it.next();
Permission permission = new Permission(permObj.getObjectName(), permissionName);
delAdminMgr.addPermission(permission);

}
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to create Admin Permissions/Permission Object",
e);
throw new RuntimeException("Unable to Create the Admin permission", e
);

}
}
else {
adminMgr = createAndGetAdminMgr();
try {
adminMgr.addPermObj(permObj);

while (it.hasNext()) {
String permissionName = (String)it.next();
Permission permission = new Permission(permObj.getObjectName(), permissionName);
adminMgr.addPermission(permission);

}
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to create Permissions/Permission Object",
e);
throw new RuntimeException("Unable to Create the permission", e
);

}
}
}
/**
* This method can be used to create Admin or Normal Permission
* @param perm the permission object
* @param isAdmin flag to see whether to provision admin permission or application permission.
*/
public void createPermission(Permission perm, boolean isAdmin) {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
try {
delAdminMgr.addPermission(perm);
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to create Admin Permission",
e);
throw new RuntimeException("Unable to Create the Admin permission", e
);

}
}
else {
adminMgr = createAndGetAdminMgr();
try {
adminMgr.addPermission(perm);
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to create Permission Object",
e);
throw new RuntimeException("Unable to Create the permission", e
);

}
}
}
/**
* This method can be used to update Admin or Normal Permission
* @param perm the permission object
* @param isAdmin flag to see whether to update admin permission or application permission.
*/
public void updatePermission(Permission perm, boolean isAdmin) {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
try {
delAdminMgr.updatePermission(perm);
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to update Admin Permission",
e);
throw new RuntimeException("Unable to update the Admin permission", e
);

}
}
else {
adminMgr = createAndGetAdminMgr();
try {
adminMgr.updatePermission(perm);
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to update Permission Object",
e);
throw new RuntimeException("Unable to update the permission", e
);

}
}
}
/**
* This method can be used to delete Admin or Normal Permission
* @param perm the permission object
* @param isAdmin flag to see whether to delete admin permission or application Permission.
*/
public void deletePermission(Permission perm, boolean isAdmin) {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
try {
delAdminMgr.deletePermission(perm);
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to delete Admin Permission",
e);
throw new RuntimeException("Unable to delete the Admin permission", e
);

}
}
else {
adminMgr = createAndGetAdminMgr();
try {
adminMgr.deletePermission(perm);
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to delete Permission",
e);
throw new RuntimeException("Unable to delete the permission", e
);

}
}
}
/**
* This method is used to search for permissions
* @param permObjName
* @param permissionName
* @param isAdmin
* @return the searched permissions
*/
public List<Permission> searchPermissions(String permObjName,String permissionName,Boolean isAdmin){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
LDAPLogger.entering(LDAPOperations.class.getName(), methodName);
List<Permission> tempObj=null;
ReviewMgr rvMgr = null;
rvMgr = createAndGetReviewManager();
try {
Permission perm=new Permission();
if(permObjName==null||permObjName.isEmpty()){
perm.setObjectName("");
}
else{
perm.setObjectName(permObjName);
}
if(permissionName==null||permissionName.isEmpty()){
perm.setOpName("");
}
else{
perm.setOpName(permissionName);
}
perm.setAdmin(isAdmin);
tempObj= rvMgr.findPermissions(perm);
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to search permissions",
e);
throw new RuntimeException("Unable to search permissions", e
);
}

LDAPLogger.exiting(LDAPOperations.class.getName(), methodName);
return tempObj;
}

/**
* This method is used to search for permobjs
* @param permObj the permobject to find
*/
public List<PermObj> searchPermObjs(PermObj permObj){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
LDAPLogger.entering(LDAPOperations.class.getName(), methodName, permObj);
ReviewMgr rvMgr=createAndGetReviewManager();
List<PermObj> searchedPermObjs=null;
try{
searchedPermObjs=rvMgr.findPermObjs(permObj);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to search admin Permission Object",
e);
throw new RuntimeException("Unable to search admin Permission Object", e
);
}
LDAPLogger.exiting(LDAPOperations.class.getName(), methodName);
return searchedPermObjs;
}
/**
* This method is used to create a permission object
* @param permObj the permission object
* @return the created Perm Obj instance
*/
public PermObj createPermissionObject(PermObj permObj){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
LDAPLogger.entering(LDAPOperations.class.getName(), methodName, permObj);
PermObj tempObj=null;
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
if (permObj.isAdmin()) {
try{
delAdminMgr = createAndGetDelAdminMgr();
tempObj=delAdminMgr.addPermObj(permObj);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to create admin Permission Object",
e);
throw new RuntimeException("Unable to create admin Permission Object", e
);
}
}
else {
adminMgr = createAndGetAdminMgr();
try {
tempObj= adminMgr.addPermObj(permObj);
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to create Permission Object",
e);
throw new RuntimeException("Unable to create the permission object", e
);
}
}
LDAPLogger.exiting(LDAPOperations.class.getName(), methodName);
return tempObj;
}
/**
* This method is used to update a permission object
* @param permObj the permission object
*/
public void updatePermissionObject(PermObj permObj){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
LDAPLogger.entering(LDAPOperations.class.getName(), methodName, permObj);
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
if (permObj.isAdmin()) {
try{
delAdminMgr = createAndGetDelAdminMgr();
delAdminMgr.updatePermObj(permObj);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to update admin Permission Object",
e);
throw new RuntimeException("Unable to update admin Permission Object", e
);
}
}
else {
adminMgr = createAndGetAdminMgr();
try {
adminMgr.updatePermObj(permObj);
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to update Permission Object",
e);
throw new RuntimeException("Unable to update the permission object", e
);
}
}
LDAPLogger.exiting(LDAPOperations.class.getName(), methodName);
}
/**
* This method can be used to delete Admin or Normal Permission object along with permissions
* @param permObj The name of the permission object @see us.jts.fortress.rbac.PermObj
*/
public void deletePermissionObject(PermObj permObj) {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
if (permObj.isAdmin()) {
delAdminMgr = createAndGetDelAdminMgr();
try {
delAdminMgr.deletePermObj(permObj);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to delete admin Permission",
e);
throw new RuntimeException("Unable to delete admin Permission", e
);

}
}
else {
adminMgr = createAndGetAdminMgr();
try {
adminMgr.deletePermObj(permObj);
}
catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to delete Permission Object",
e);
throw new RuntimeException("Unable to delete the permission object", e
);
}
}
}
/**
* This can be used to grant permission to user
* @param permissionObjName The name of the permission object
* @param permissions A set of permissions
* @param userName The username to be assigned permissions
* @param isAdmin A flag that checks whether the permission is application or admin permission
* @return a Set of Assigned Permissions
*/
public Set assignPermissionsToUser(String permissionObjName, Set permissions, String userName, boolean isAdmin) {
Set permissionsAssigned = new HashSet();
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
Iterator it = permissions.iterator();
PermObj obj = new PermObj(permissionObjName);
User user = new User(userName);
if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
while (it.hasNext()) {
String permissionName = (String)it.next();
Permission permission = new Permission(obj.getObjectName(), permissionName);
try {
delAdminMgr.grantPermission(permission, user);
permissionsAssigned.add(permissionName);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign user the given Admin permission" +
permissionName, e);
}
}

} else {
adminMgr = createAndGetAdminMgr();
while (it.hasNext()) {
String permissionName = (String)it.next();
Permission permission = new Permission(obj.getObjectName(), permissionName);
try {
adminMgr.grantPermission(permission, user);
permissionsAssigned.add(permissionName);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign user the given permission" +
permissionName, e);
}
}
}
return permissionsAssigned;

}
/**
* This can be used to revoke permission from user
* @param permissionObjName The name of the permission object
* @param permissions A set of permissions to be revoked
* @param userName The username from which to revoke the permissions
* @param isAdmin A flag that checks whether the permission is application or admin permission
* @return a Set of revoked Permissions
*/
public Set revokePermissionFromUser(String permissionObjName, Set permissions, String userName, boolean isAdmin) {
Set permissionsRevoked = new HashSet();
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
Iterator it = permissions.iterator();
PermObj obj = new PermObj(permissionObjName);
User user = new User(userName);
if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
while (it.hasNext()) {
String permissionName = (String)it.next();
Permission permission = new Permission(obj.getObjectName(), permissionName);
try {
delAdminMgr.revokePermission(permission, user);
permissionsRevoked.add(permissionName);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to revoke from user the given Admin permission" +
permissionName, e);
}
}

} else {
adminMgr = createAndGetAdminMgr();
while (it.hasNext()) {
String permissionName = (String)it.next();
Permission permission = new Permission(obj.getObjectName(), permissionName);
try {
adminMgr.revokePermission(permission, user);
permissionsRevoked.add(permissionName);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to revoke from the user the given permission" +
permissionName, e);
}
}
}
return permissionsRevoked;

}
/**
* This can be used to grant permission to role
* @param permissionObjName The name of an existing permission object
* @param Permissions A set of permission strings to be assigned to the user
* @param roleName the rolename to be assigned
* @param isAdmin Flag that checks whether to provision adminRole or Application Role.
* @return a Set of Assigned Permissions
*/
public Set assignPermissionsToRole(String permissionObjName, Set Permissions, String roleName, boolean isAdmin) {
Set permissionsAssigned = new HashSet();
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
Role role = null;
AdminRole adminRole = null;
Iterator it = Permissions.iterator();
PermObj obj = new PermObj(permissionObjName);

if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
adminRole = new AdminRole(roleName);
while (it.hasNext()) {
String permissionName = (String)it.next();
Permission permission = new Permission(obj.getObjectName(), permissionName);
try {
delAdminMgr.grantPermission(permission, adminRole);
permissionsAssigned.add(permissionName);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign role the given permission" +
permissionName, e);
}
}
} else {
adminMgr = createAndGetAdminMgr();
role = new Role(roleName);
while (it.hasNext()) {
String permissionName = (String)it.next();
Permission permission = new Permission(obj.getObjectName(), permissionName);
try {
adminMgr.grantPermission(permission, role);
permissionsAssigned.add(permissionName);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign role the given permission" +
permissionName, e);
}
}

}
return permissionsAssigned;
}
/**
* This can be used to assign individual permissions to the role
* @param perm the permission to revoke
* @param roleName the rolename to be revoked
* @param isAdmin Flag that checks whether to grant Admin Permission to Admin Role or Application Permission to application role.
*/
public void assignPermissionToRole(Permission perm,String roleName ,boolean isAdmin) {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
Role role = null;
AdminRole adminRole = null;
if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
adminRole = new AdminRole(roleName);
try {
delAdminMgr.grantPermission(perm, adminRole);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign the role to the given permission" +
perm.getObjectName(), e);
}

} else {
adminMgr = createAndGetAdminMgr();
role = new Role(roleName);

try {
adminMgr.grantPermission(perm, role);

} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign the role to the given permission" +
perm.getObjectName(), e);
}
}
}
/**
* This can be used to revoke individual permissions from the role
* @param perm the permission to revoke
* @param roleName the rolename to be revoked
* @param isAdmin Flag that checks whether to revoke Admin Permission or Application Permission.
*/
public void revokePermissionFromRole(Permission perm,String roleName ,boolean isAdmin) {
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
Role role = null;
AdminRole adminRole = null;
if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
adminRole = new AdminRole(roleName);

try {
delAdminMgr.revokePermission(perm, adminRole);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to revoke from role the given permission" +
perm.getObjectName(), e);
}

} else {
adminMgr = createAndGetAdminMgr();
role = new Role(roleName);

try {
adminMgr.revokePermission(perm, role);

} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to revoke from role the given permission" +
perm.getObjectName(), e);
}
}
}
/**
* This can be used to revoke individual permissions from the role
* @param permissionObjName The name of an existing permission object
* @param Permissions A set of permission strings to be revoked from the user
* @param roleName the rolename to be revoked
* @param isAdmin Flag that checks whether to revoke adminRole or Application Role.
* @return a Set of revoked Permissions
*/
public Set revokePermissionsFromRole(String permissionObjName, Set Permissions, String roleName, boolean isAdmin) {
Set revokedPermissions = new HashSet();
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
Role role = null;
AdminRole adminRole = null;
Iterator it = Permissions.iterator();
PermObj obj = new PermObj(permissionObjName);

if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
adminRole = new AdminRole(roleName);
while (it.hasNext()) {
String permissionName = (String)it.next();
Permission permission = new Permission(obj.getObjectName(), permissionName);
try {
delAdminMgr.revokePermission(permission, adminRole);
revokedPermissions.add(permissionName);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to revoke from role the given permission" +
permissionName, e);
}
}
} else {
adminMgr = createAndGetAdminMgr();
role = new Role(roleName);
while (it.hasNext()) {
String permissionName = (String)it.next();
Permission permission = new Permission(obj.getObjectName(), permissionName);
try {
adminMgr.revokePermission(permission, role);
revokedPermissions.add(permissionName);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to revoke from role the given permission" +
permissionName, e);
}
}

}
return revokedPermissions;
}
/**
* This can be used to revoke permission from the roles
* @param permissionObjName The name of an existing permission object
* @param permissionName
* @param roles
* @param isAdmin Flag that checks whether to revoke adminRole or Application Role.
* @return a Set of revoked roles from permission
*/
public Set revokePermissionFromRoles(String permissionObjName, String permissionName,Set roles, boolean isAdmin) {
Set revokedRolesFromPermission = new HashSet();
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
Iterator it = roles.iterator();
if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
Permission permission=new Permission();
permission.setObjectName(permissionObjName);
permission.setOpName(permissionName);
permission.setAdmin(isAdmin);
while (it.hasNext()) {
String roleName = (String)it.next();
AdminRole adminRole=new AdminRole(roleName);
try {
delAdminMgr.revokePermission(permission, adminRole);
revokedRolesFromPermission.add(adminRole);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to revoke from permission from the given role" +
roleName, e);
}
}
} else {
adminMgr = createAndGetAdminMgr();
Permission permission=new Permission();
permission.setObjectName(permissionObjName);
permission.setOpName(permissionName);
permission.setAdmin(isAdmin);
while (it.hasNext()) {
String roleName = (String)it.next();
Role role=new Role(roleName);
try {
adminMgr.revokePermission(permission, role);
revokedRolesFromPermission.add(role);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to permission from role the given role" +
roleName, e);
}
}

}
return revokedRolesFromPermission;
}
/**
* This can be used to assign permission to the roles
* @param permissionObjName The name of an existing permission object
* @param permissionName
* @param roles
* @param isAdmin Flag that checks whether to revoke adminRole or Application Role.
* @return a Set of assigned roles to permission
*/
public Set assignPermissionToRoles(String permissionObjName, String permissionName,Set roles, boolean isAdmin) {
Set assignedRolesToPermission = new HashSet();
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
AdminMgr adminMgr = null;
DelAdminMgr delAdminMgr = null;
Iterator it = roles.iterator();
if (isAdmin) {
delAdminMgr = createAndGetDelAdminMgr();
Permission permission=new Permission();
permission.setObjectName(permissionObjName);
permission.setOpName(permissionName);
permission.setAdmin(isAdmin);
while (it.hasNext()) {
String roleName = (String)it.next();
AdminRole adminRole=new AdminRole(roleName);
try {
delAdminMgr.grantPermission(permission, adminRole);
assignedRolesToPermission.add(adminRole);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign permission to the given role" +
roleName, e);
}
}
} else {
adminMgr = createAndGetAdminMgr();
Permission permission=new Permission();
permission.setObjectName(permissionObjName);
permission.setOpName(permissionName);
permission.setAdmin(isAdmin);
while (it.hasNext()) {
String roleName = (String)it.next();
Role role=new Role(roleName);
try {
adminMgr.grantPermission(permission, role);
assignedRolesToPermission.add(role);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "Unable to assign permission to the given role" +
roleName, e);
}
}

}
return assignedRolesToPermission;
}
/**
* @param userName The userName to be authenticated
* @param password The password for the user
* @return
*/
public Session createUserSession(String userName, String password) {
User user = new User(userName, password.toCharArray());
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
try {
rbacSession = createAndGetAccessMgr().createSession(user, false);
} catch (PasswordException pwdException) {
LDAPLogger.severe("[" + methodName + "]" + "Exception occured in validating the username/password");
throw new RuntimeException("Exception occured in validating the username/password", pwdException
);
} catch (SecurityException e) {
LDAPLogger.severe("[" + methodName + "]" + "System Exception occured in creating the instance of session");
throw new RuntimeException("[" + methodName + "]" +
"System Exception occured in creating the instance of session", e
);
}
return rbacSession;
}


public void setRbacSession(Session rbacSession) {
this.rbacSession = rbacSession;
}

public Session getRbacSession() {
return rbacSession;
}
}

Comments

ADF dynamically managing application policies

Labels: , ,

Recently a user contacted me with the requirement that he needed to assign enterprise groups to application roles dynamically. Normally, people can manage this through enterprise manager, but there might have been a specific requirement for that user.  I have already written various posts on ADF security which cover utility methods that use OPSS API’s to perform operations on the enterprise OID, OpenLdap etc.  In this post i will cover this specific requirement; although the given code is very crude, it is there only to serve as an example and the process is what matters.

The code is shown below.

package model;

import oracle.security.jps.service.policystore.ApplicationPolicy;
import oracle.security.jps.service.policystore.PolicyStore;
import java.security.Principal;

import java.util.Hashtable;

import oracle.adf.share.logging.ADFLogger;

import oracle.security.idm.IMException;
import oracle.security.idm.IdentityStore;
import oracle.security.idm.IdentityStoreFactory;
import oracle.security.idm.IdentityStoreFactoryBuilder;
import oracle.security.idm.Role;
import oracle.security.idm.RoleManager;
import oracle.security.idm.User;
import oracle.security.idm.UserManager;
import oracle.security.idm.providers.oid.OIDIdentityStoreFactory;
import oracle.security.jps.JpsContext;
import oracle.security.jps.JpsContextFactory;
import oracle.security.jps.JpsException;
import oracle.security.jps.internal.idstore.ldap.LdapIdentityStore;
import oracle.security.jps.service.idstore.IdentityStoreException;
import oracle.security.jps.service.idstore.IdentityStoreService;
import oracle.security.jps.service.policystore.ApplicationPolicy;
import oracle.security.jps.service.policystore.PolicyObjectNotFoundException;
import oracle.security.jps.service.policystore.PolicyStore;
import oracle.security.jps.service.policystore.PolicyStoreException;
import oracle.security.jps.service.policystore.info.common.InvalidArgumentException;

public class DemoJpsMethods {
public static final ADFLogger DemoJpsLogger=ADFLogger.createADFLogger(DemoJpsMethods.class);
public static final String DEV_GROUP="DevGroup";
public static final String TRAINING_GROUP="TrainingGroup";
public static final String DEV_APP_ROLE="DevAppRole";
public static final String TRAINING_APP_ROLE="TrainingAppRole";
public DemoJpsMethods() {
super();
}

/**
* Dummy method just for testing so not parameterized
*/
public void addUserToAppGroup(){
JpsContext ctxt = IdentityStoreConfigurator.jpsCtxt;
LdapIdentityStore idstoreService =
(LdapIdentityStore)ctxt.getServiceInstance(IdentityStoreService.class);
IdentityStore idmStore=null;
try {
idmStore = idstoreService.getIdmStore();

} catch (IdentityStoreException e) {
throw new RuntimeException(e);
}
User tom=null;
User helen=null;
UserManager um=null;
RoleManager rm=null;
Role trainingRole=null;
Role devRole=null;

try {
um= idmStore.getUserManager();
rm=idmStore.getRoleManager();
} catch (IMException e) {
try {
idmStore.close();
} catch (IMException f) {
}
throw new RuntimeException(e);
}
try {
trainingRole =
idmStore.searchRole(IdentityStore.SEARCH_BY_NAME, TRAINING_GROUP);
devRole =
idmStore.searchRole(IdentityStore.SEARCH_BY_NAME, DEV_GROUP);
} catch (IMException e) {
DemoJpsLogger.severe("Rethrow exception because roles ARE NOT found");
try {
idmStore.close();
} catch (IMException f) {
}
throw new RuntimeException(e);
}


try {
tom = idmStore.searchUser("tom");
helen = idmStore.searchUser("helen");


//if it comes till here user is found

} catch (IMException e) {
DemoJpsLogger.severe("Ignore exception because user is likely not found");
}
//User not found create ?
if(tom==null){
try {
tom= um.createUser("tom", "Welcome_1".toCharArray());

} catch (IMException e) {
try {
idmStore.close();
} catch (IMException f) {
}
throw new RuntimeException(e);

}

}
//User not found create ?
if(helen==null){
try {
helen=um.createUser("helen", "Welcome_1".toCharArray());

} catch (IMException e) {
try {
idmStore.close();
} catch (IMException f) {
}
throw new RuntimeException(e);
}

}
try {
rm.grantRole(trainingRole,tom.getPrincipal());
rm.grantRole(devRole,helen.getPrincipal());
} catch (IMException e) {
try {
idmStore.close();
} catch (IMException f) {
}
throw new RuntimeException(e);
}

if(idmStore!=null){
try {
idmStore.close();
} catch (IMException f) {
}
}



}
public void addAppGroupToAppRole() {
JpsContext ctxt = IdentityStoreConfigurator.jpsCtxt;
LdapIdentityStore idstoreService =
(LdapIdentityStore)ctxt.getServiceInstance(IdentityStoreService.class);
IdentityStore idmStore=null;
try {
idmStore = idstoreService.getIdmStore();
} catch (IdentityStoreException e) {
throw new RuntimeException(e);
}
PolicyStore ps = ctxt.getServiceInstance(PolicyStore.class);
ApplicationPolicy policy;
Role trainingRole=null;
Role devRole=null;
try {
trainingRole =
idmStore.searchRole(IdentityStore.SEARCH_BY_NAME, TRAINING_GROUP);
devRole =
idmStore.searchRole(IdentityStore.SEARCH_BY_NAME, DEV_GROUP);
} catch (IMException e) {
try {
idmStore.close();
} catch (IMException f) {
}
throw new RuntimeException(e);
}



try {
policy = ps.getApplicationPolicy("DemoAppSecurity#V2.0");
policy.addPrincipalToAppRole(trainingRole.getPrincipal(), TRAINING_APP_ROLE);
policy.addPrincipalToAppRole(devRole.getPrincipal(), DEV_APP_ROLE);
} catch (PolicyStoreException e) {
throw new RuntimeException(e);
} catch (IMException e) {
throw new RuntimeException(e);
}

if(idmStore!=null){
try {
idmStore.close();
} catch (IMException f) {
}
}

}



/**
* This nested private class is used for configuring and initializing the context factory
* @author Ramandeep Nanda
*/
private static final class IdentityStoreConfigurator {
private static final JpsContext jpsCtxt=initializeFactory();


private static JpsContext initializeFactory(){
String methodName = Thread.currentThread().getStackTrace()[1].getMethodName();
JpsContextFactory tempFactory;
JpsContext jpsContext;
try {
tempFactory=JpsContextFactory.getContextFactory();
jpsContext=tempFactory.getContext();
}
catch (JpsException e) {
DemoJpsLogger.severe("Exception in "+methodName + " " +e.getMessage() +" ", e);
throw new RuntimeException("Exception in "+methodName + " " +e.getMessage() +" ", e);
}
return jpsContext;
}



}
}


 



So basically there are two methods, the first one just creates the user and assigns them to the enterprise groups, the second one is the one we’re interested in because this one first accesses the application policy and then dynamically assigns the enterprise group to the application role .



We are not done just yet, there are a few steps you need to configure which are mentioned below.




  • Assign PolicyStoreAccessPermission to weblogic user in system-jazn-data.xml.
    <grant>
    <grantee>
    <principals>
    <principal>
    <class>weblogic.security.principal.WLSUserImpl</class>
    <name>weblogic</name>
    </principal>
    </principals>
    </grantee>
    <permissions>
    <permission>
    <class>oracle.security.jps.service.policystore.PolicyStoreAccessPermission</class>
    <name>context=SYSTEM</name>
    <actions>*</actions>
    </permission>
    </permissions>
    </grant>



  • Although i have added the application stripe grant in the application jazn-data.xml, you need to be aware of that. It is mentioned below:
      <grant>
    <grantee>
    <principals>
    <principal>
    <class>oracle.security.jps.internal.core.principals.JpsXmlUserImpl</class>
    <name>weblogic</name>
    </principal>
    </principals>
    </grantee>
    <permissions>
    <permission>
    <class>oracle.security.jps.service.policystore.PolicyStoreAccessPermission</class>
    <name>context=APPLICATION,name=DemoAppSecurity#V2.0</name>
    <actions>*</actions>
    </permission>
    </permissions>
    </grant>


     



  • Run the application and log in with weblogic user i.e login.html page


  • There will be two buttons one creates and adds a user to a group, second adds enterprise group to app role


  • For first, You need an ldap browser to view the changes, use the embedded ldap connection details.


  • For second, you need just to view the system-jazn-data.xml file, here you will see enterprise group added to app role.



The application can be downloaded from here. Application Link

Comments