package org.crosswire.webtools; import org.apache.log4j.Logger; import org.crosswire.xml.XMLBlock; import org.crosswire.utils.Utils; import javax.servlet.http.Cookie; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.HashSet; import java.util.List; import java.util.Arrays; import java.util.Map; import java.util.Set; import java.lang.reflect.Constructor; public class RightsAndRoles { public static String sessionKeyName = "crosswireSession"; static final Logger logger = Logger.getLogger(RightsAndRoles.class); // Extending impl needs to set the sysRightsAndRoles before any instances handed out protected static RightsAndRoles sysRightsAndRoles = new RightsAndRoles(); public static RightsAndRoles getInstance() { return sysRightsAndRoles; } static { // see if we have a RightsAndRoles subclass to register try { logger.info("Looking up RightsAndRoles implementation"); String rightsAndRolesClass = Utils.getSysConfig().getProperty("RightsAndRoles"); if (rightsAndRolesClass != null) { logger.info("Attempting to register RightsAndRoles implementation: " + rightsAndRolesClass); Class clazz = Class.forName(rightsAndRolesClass); if (clazz != null) { Constructor ctor = clazz.getConstructor(); if (ctor != null) { sysRightsAndRoles = (RightsAndRoles)ctor.newInstance(); } else { logger.error("RightsAndRoles class: " + rightsAndRolesClass + ", doesn't have default c-tor"); } } else { logger.error("RightAndRoles class requested: " + rightsAndRolesClass + ", not found on classpath"); } } logger.info("Looking up RightsAndRoles Session Key Name"); String rightsAndRolesSessionKeyName = Utils.getSysConfig().getProperty("RightsAndRolesSessionKeyName"); if (rightsAndRolesSessionKeyName != null) { logger.info("Setting RightsAndRoles Session Key Name to: " + rightsAndRolesSessionKeyName); sessionKeyName = rightsAndRolesSessionKeyName; } } catch (Exception e) { logger.error("Error registering RightsAndRoles class", e); } } /** * get user groups for a user or all user group * * @internalUserID - internalUserID to find group or < 0 for all user groups */ public Set getUserGroups(long internalUserID) { return getUserGroups(internalUserID, false); } /** * override me */ public Set getUserGroups(long internalUserID, boolean groupDetails) { return new HashSet(); } /** * get roles for a user or all roles * * @internalUserID - internalUserID to find group or < 0 for all user groups * * override me */ public Set getUserRoles(long internalRoleID) { return new HashSet(); } // convenience method public Set getUserGroups(String userName) { return getUserGroups(userName, false); } // convenience method public Set getUserGroups(String userName, boolean groupDetails) { User user = getUser(userName); long userID = -1; try { userID = Long.parseLong(user.getInternalUserID()); } catch(Exception e) {} // getUserGroups(-1) returns all user groups, so we want to be sure to not pass userID == -1 // to getUserGroups, but instead an empty set since we've been asked for a particular user's groups // and that user was not found. return userID == -1 ? new HashSet() : getUserGroups(userID, groupDetails); } // convenience method public Set getUserRoles(String userName) { User user = getUser(userName); long userID = -1; try { userID = Long.parseLong(user.getInternalUserID()); } catch(Exception e) {} // getUserRoles(-1) returns all user roles, so we want to be sure to not pass userID == -1 // to getUserRoles, but instead an empty set since we've been asked for a particular user's roles // and that user was not found. return userID == -1 ? new HashSet() : getUserRoles(userID); } // convenience method /** * return all user groups */ public Set getUserGroups() { return getUserGroups(-1, false); } public UserGroup getUserGroup(long userGroupID) { return null; } public UserGroup getUserGroup(String userGroupName) { return null; } /** * get user by login */ public User getUser(String userName) { return null; } /** * get user by hosting portal id */ public User getUser(long internalUserID) { return null; } /** * get current user from hosting portal */ public User getUser(HttpServletRequest request) { return null; } // return a user object if authentication is successful, otherwise null public User authenticateUser(String userName, String passwd) { return authenticateUser(userName, passwd, null); } public User authenticateUser(String userName, String passwd, String userData) { return null; } /** * hasRole - does this user have this role in this UserGroup? * * @user * @role * @userGroup - if null, check for global role */ public boolean hasRole(RightsAndRoles.User user, String role, RightsAndRoles.UserGroup userGroup) { return false; } // Convenience so we don't have to specify (UserGroup)null for global role check // Does this user have this global role? public boolean hasRole(User user, String role) { return hasRole(user, role, (UserGroup)null); } // convenience method, if we have a userGroupName, we'll lookup the user group for you public boolean hasRole(RightsAndRoles.User user, String role, String userGroupName) { RightsAndRoles.UserGroup userGroup = null; if (userGroupName != null) { userGroup = getUserGroup(userGroupName); } return hasRole(user, role, userGroup); } // more conventience methods to lookup current user and check role if current user exists public static boolean hasRole(HttpServletRequest request, HttpServletResponse response, String role) { return hasRole(request, response, role, null); } public static boolean hasRole(HttpServletRequest request, HttpServletResponse response, String role, String userGroupName) { boolean hasRole = false; User user = getInstance().getCurrentUser(request, response); if (user != null) { hasRole = getInstance().hasRole(user, role, userGroupName); } logger.info("hasRole: from: " + request.getRequestURI() + "; userName: " + (user != null ? user.getUserName() : "null") + "; role: " + role + (userGroupName != null ? ("; userGroup: " + userGroupName) : "") + ": " + hasRole); return hasRole; } /** * opens a session for the given user */ public String openSession(User user, HttpServletResponse response) { user.includeUserGroups(); user.includeUserRoles(); Cookie cookie = new Cookie(sessionKeyName, user.getSessionHash()); cookie.setMaxAge(-1); // life of browser cookie.setPath("/"); response.addCookie(cookie); return user.getSessionHash(); } /** * closes a session */ public void closeSession(String sessionKey, HttpServletResponse response) { if (sessionKey == null) { return; } if (response != null) { Cookie cookie = new Cookie(sessionKeyName, sessionKey); cookie.setMaxAge(0); // clear cookie cookie.setPath("/"); response.addCookie(cookie); } } public User getCurrentUser(HttpServletRequest request, HttpServletResponse response) { return null; } /** * checks if a session is present, if not, then can check if a SSO session is present and * open a session accordingly. * Returns session */ public String getCurrentSession(HttpServletRequest request, HttpServletResponse response) { String authToken = null; if (authToken == null) { authToken = request.getParameter(sessionKeyName); } if (authToken == null) { authToken = request.getParameter("sessionHash"); } if (authToken == null) { authToken = request.getHeader("X-Auth-Token"); } if (authToken == null) { authToken = (String)request.getAttribute("X-Auth-Token"); } if (authToken == null) { Cookie cs[] = request.getCookies(); if (cs != null) { List cookies = Arrays.asList(cs); for (Cookie cookie : cookies) { if (sessionKeyName.equals(cookie.getName())) { authToken = cookie.getValue(); break; } } } } // is this necessary? our session token UUIDs should be basic ASCII try { if (authToken != null) authToken = new String(authToken.getBytes("iso8859-1"), "UTF-8"); } catch (Exception e) {} // if we still don't have a session, let's see if we have a SSO session if (authToken == null) { // SSO sync with other system, try to get user from request // if we get a user then open a session for us. User user = getUser(request); if (user != null) { authToken = openSession(user, response); } } return authToken; } public Map getAccountList(String sessionKey) { return new HashMap<>(); } public Map getGroupList(String sessionKey, Integer account) { return new HashMap<>(); } public static class Role extends XMLBlock { public Role() { super(XMLBlock.createXMLBlock("")); init(); } public Role(String name, String title, String internalRoleID) { this(); setRoleName(name); setRoleTitle(title); setInternalRoleID(internalRoleID); } private void init() { } public String getInternalRoleID() { return getAttribute("internalRoleID"); } public void setInternalRoleID(String val) { setAttribute("internalRoleID", val); } public String getRoleName() { return getAttribute("roleName"); } public void setRoleName(String val) { setAttribute("roleName", val); } public String getRoleTitle() { return getAttribute("roleTitle"); } public void setRoleTitle(String val) { setAttribute("roleTitle", val); } public String getRoleDescription() { return getAttribute("roleDescription"); } public void setRoleDescription(String val) { setAttribute("roleDescription", val); } } public static class User extends XMLBlock { private Map json = null; /** * */ public User() { super(XMLBlock.createXMLBlock("")); init(); } private void init() { } public Map getJson() { return json; } public void setJson(Map data) { json = data; } public String getInternalUserID() { return getAttribute("internalUserID"); } public void setInternalUserID(String val) { setAttribute("internalUserID", val); } public String getUserName() { return getAttribute("userName"); } public void setUserName(String val) { setAttribute("userName", val); } public String getSessionHash() { return getAttribute("sessionHash"); } public void setSessionHash(String val) { setAttribute("sessionHash", val); } public String getDefaultFormat() { String f = getAttribute("defaultFormat"); return f != null && f.length() > 0 ? f : null; } public void setDefaultFormat(String val) { if ("null".equals(val)) { val = null; } setAttribute("defaultFormat", val); } public String getFirstName() { return getValue("firstName"); } public void setFirstName(String val) { setValue("firstName", val); } public String getMiddleName() { return getValue("middleName"); } public void setMiddleName(String val) { setValue("middleName", val); } public String getLastName() { return getValue("lastName"); } public void setLastName(String val) { setValue("lastName", val); } public Integer getCompanyID() { Integer v = null; try { v = Integer.parseInt(getValue("companyID")); } catch (Exception e) {}; return v; } public void setCompanyID(Integer val) { setValue("companyID", Integer.toString(val)); } public String getFullName() { String fullName = ""; String firstName = getFirstName(); String middleName = getMiddleName(); String lastName = getLastName(); if (firstName != null && firstName.length() > 0) { fullName += firstName; } if (middleName != null && middleName.length() > 0) { if (fullName.length() > 0) { fullName += " "; } fullName += middleName; } if (lastName != null && lastName.length() > 0) { if (fullName.length() > 0) { fullName += " "; } fullName += lastName; } if (fullName.trim().length() < 1) { fullName = getUserName(); } setValue("fullName", fullName); return fullName; } public String getEmailAddress() { return getValue("emailAddress"); } public void setEmailAddress(String val) { setValue("emailAddress", val); } public String getJobTitle() { return getValue("jobTitle"); } public void setJobTitle(String val) { setValue("jobTitle", val); } public void includeUserGroups() { includeUserGroups(false); } public void includeUserGroups(boolean groupDetails) { XMLBlock userGroups = getBlock("userGroups"); if (userGroups != null) { removeChild(userGroups); } userGroups = createBlock("userGroups"); int count = 0; for (UserGroup ug : RightsAndRoles.getInstance().getUserGroups(getUserName(), groupDetails)) { userGroups.addBlock(ug); ++count; } userGroups.setAttribute("count", Integer.toString(count)); } public void includeUserRoles() { XMLBlock userRoles = getBlock("userRoles"); if (userRoles != null) { removeChild(userRoles); } userRoles = createBlock("userRoles"); int count = 0; for (Role r : RightsAndRoles.getInstance().getUserRoles(getUserName())) { userRoles.addBlock(r); ++count; } userRoles.setAttribute("count", Integer.toString(count)); } public boolean hasRole(String role) { return RightsAndRoles.getInstance().hasRole(this, role); } public boolean hasRole(String role, UserGroup userGroup) { return RightsAndRoles.getInstance().hasRole(this, role, userGroup); } public boolean hasRole(String role, String userGroupName) { return RightsAndRoles.getInstance().hasRole(this, role, userGroupName); } /* public String toString() { getFullName(); logger.debug("user.node = " + this.getNode()); return super.toString(); } */ } public static class UserGroup extends XMLBlock { /** * */ private static final long serialVersionUID = -3234004235624006107L; public UserGroup() { super(XMLBlock.createXMLBlock("")); init(); } private void init() { setType("userGroup"); } public String getType() { return getAttribute("userGroupType"); } public void setType(String val) { setAttribute("userGroupType", val); } public long getID() { try { return Long.parseLong(getAttribute("userGroupID")); } catch (Exception e) {} return -1; } public void setID(long val) { setAttribute("userGroupID", Long.toString(val)); } public String getUserGroupName() { return getAttribute("name"); } public void setUserGroupName(String val) { setAttribute("name", val); } public String getDescription() { return getValue("description"); } public void setDescription(String val) { setValue("description", val); } public void addUser(String userName) { createValue("user", userName); } } }