Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package com.cfalzone.viewtools;
- import java.security.MessageDigest;
- import java.util.Hashtable;
- import javax.naming.AuthenticationException;
- import javax.naming.Context;
- import javax.naming.NamingEnumeration;
- import javax.naming.NamingException;
- import javax.naming.directory.DirContext;
- import javax.naming.directory.InitialDirContext;
- import javax.naming.directory.SearchControls;
- import javax.naming.directory.SearchResult;
- import javax.servlet.http.HttpServletRequest;
- import javax.servlet.http.HttpSession;
- import org.apache.velocity.tools.view.tools.ViewTool;
- import com.dotmarketing.business.APILocator;
- import com.dotmarketing.plugin.business.PluginAPI;
- import com.dotmarketing.util.Logger;
- import com.dotmarketing.util.UtilMethods;
- /**
- * Simple Session-based LDAP Authentication ViewTool for DotCMS
- *
- * @author Christopher Falzone <cfalzone@edinboro.edu>
- * @version 2010.1006
- */
- public class SimpleLDAPTool implements ViewTool {
- private String ldapServer = null;
- private String ldapBase = null;
- private String ldapReaderDN = null;
- private String ldapReaderPassword = null;
- private String ldapUsernameAttribute = null;
- private String superSecretKey = null;
- private final static String ldapContext = "com.sun.jndi.ldap.LdapCtxFactory";
- private final static String ldapSecurity = "simple";
- /**
- * Init Method for the viewtool
- */
- public void init(Object obj) {
- /* get the plugin Properties */
- PluginAPI pluginAPI = APILocator.getPluginAPI();
- try {
- ldapServer = pluginAPI.loadProperty(
- "com.cfalzone.plugins.simpleldap",
- "simpleLDAP.ldapServer");
- ldapBase = pluginAPI.loadProperty(
- "com.cfalzone.plugins.simpleldap",
- "simpleLDAP.ldapBase");
- ldapUsernameAttribute = pluginAPI.loadProperty(
- "com.cfalzone.plugins.simpleldap",
- "simpleLDAP.ldapUsernameAttribute");
- ldapReaderDN = pluginAPI.loadProperty(
- "com.cfalzone.plugins.simpleldap",
- "simpleLDAP.ldapReaderDN");
- ldapReaderPassword = pluginAPI.loadProperty(
- "com.cfalzone.plugins.simpleldap",
- "simpleLDAP.ldapReaderPassword");
- superSecretKey = pluginAPI.loadProperty(
- "com.cfalzone.plugins.simpleldap",
- "simpleLDAP.superSecretKey");
- } catch (Exception e) {
- Logger.error(this, "error while accessing properties", e);
- }
- }
- /**
- * Sees if a user is logged in
- *
- * Example: #set($islogged = $simple_ldap.is_logged($request))
- * #if($UtilMethods.isSet($islogged))
- * ## The User is logged in
- * #else
- * ## Show the login form
- * #end
- *
- * @param request The Request Object
- * @return True if logged in, false otherwise
- */
- public Boolean is_logged(HttpServletRequest request) {
- HttpSession session = request.getSession(true);
- /* Check for a form first */
- String username = request.getParameter("username");
- String password = request.getParameter("password");
- if(UtilMethods.isSet(username) && UtilMethods.isSet(password)) {
- /* There is a form, so process that login */
- if(checkLDAP(username, password)) {
- /* User Credentials pass -- create session and return true */
- session.setAttribute("username",request.getParameter("username"));
- session.setAttribute("logged",MD5(request.getParameter("username")+superSecretKey));
- Logger.info(this, "User "+username+" Logged in from form");
- return true;
- } else {
- /* User Credentials do not pass -- clear session and return false */
- session.invalidate();
- Logger.info(this, "Invalid Login Form from user "+username);
- return false;
- }
- } else {
- /* There is no form so check the session */
- String user = (String) session.getAttribute("username");
- String key = (String) session.getAttribute("logged");
- if(UtilMethods.isSet(user) && UtilMethods.isSet(key)) {
- /* There is a session so check if it is valid */
- if(MD5(user+superSecretKey) == key) {
- /* Key matches so we have a good session return true */
- Logger.info(this, "User "+username+" Logged in from session");
- return true;
- } else {
- /* Invalid Session */
- session.invalidate();
- Logger.info(this, "Invalid Session from user "+username+" with key "+key);
- return false;
- }
- } else {
- /* No session or form so just return false */
- return false;
- }
- }
- }
- /**
- * Checks to see if the supplied username and password are valid credentials
- *
- * @param username The username to test
- * @param password The password to test
- * @return True if valid credentials, false otherwise
- */
- private Boolean checkLDAP(String username, String password) {
- Hashtable<String, String> ldapEnv = new Hashtable<String, String>();
- DirContext dirContext = null;
- String ldapFilter = "("+ldapUsernameAttribute+"="+username+")";
- SearchControls constraints = new SearchControls();
- /* Connect to LDAP */
- ldapEnv.put(Context.INITIAL_CONTEXT_FACTORY, ldapContext);
- ldapEnv.put(Context.PROVIDER_URL, ldapServer);
- ldapEnv.put(Context.SECURITY_AUTHENTICATION, ldapSecurity);
- ldapEnv.put(Context.SECURITY_PRINCIPAL, ldapReaderDN);
- ldapEnv.put(Context.SECURITY_CREDENTIALS, ldapReaderPassword);
- constraints.setSearchScope(SearchControls.SUBTREE_SCOPE);
- try {
- dirContext = new InitialDirContext(ldapEnv);
- } catch(Exception e) {
- Logger.error(this, "error while connecting to LDAP", e);
- return false;
- }
- /* Do an LDAP Search for this user */
- try {
- Logger.info(this, "Searching for user "+username+" ...");
- NamingEnumeration<SearchResult> results = dirContext.search(ldapBase, ldapFilter, constraints);
- if(results != null && results.hasMore()) {
- /* This user Exists - check their password now */
- SearchResult sr = (SearchResult)results.next();
- String dn = sr.getName();
- /* Try opening a Connection using this user */
- Logger.info(this, "Found user "+username+" with dn "+dn+" Attempting Login ...");
- Hashtable<String, String> authEnv = new Hashtable<String, String>();
- authEnv.put(Context.INITIAL_CONTEXT_FACTORY, ldapContext);
- authEnv.put(Context.PROVIDER_URL, ldapServer);
- authEnv.put(Context.SECURITY_AUTHENTICATION, ldapSecurity);
- authEnv.put(Context.SECURITY_PRINCIPAL, dn);
- authEnv.put(Context.SECURITY_CREDENTIALS, password);
- try {
- @SuppressWarnings("unused")
- DirContext authContext = new InitialDirContext(authEnv);
- /* At this point we were able to bind with the user so they have good credentials */
- Logger.info(this, "User "+username+" logged in");
- return true;
- } catch(AuthenticationException e) {
- /* This is bad credentials */
- Logger.error(this, "User "+username+" bad credentials", e);
- return false;
- } catch (NamingException e) {
- Logger.error(this, "Error trying to login user "+username, e);
- return false;
- }
- } else {
- /* This user does not exist so return false */
- Logger.error(this, "User "+username+" not found");
- return false;
- }
- } catch (Exception e) {
- Logger.error(this, "Error while searching LDAP for user "+username, e);
- return false;
- }
- }
- /**
- * Converts a byte array to a hex string
- *
- * @param data The Byte Array
- * @return The Hex String
- */
- private String convertToHex(byte[] data) {
- StringBuffer buf = new StringBuffer();
- for (int i = 0; i < data.length; i++) {
- int halfbyte = (data[i] >>> 4) & 0x0F;
- int two_halfs = 0;
- do {
- if ((0 <= halfbyte) && (halfbyte <= 9))
- buf.append((char) ('0' + halfbyte));
- else
- buf.append((char) ('a' + (halfbyte - 10)));
- halfbyte = data[i] & 0x0F;
- } while(two_halfs++ < 1);
- }
- return buf.toString();
- }
- /**
- * Creates an MD5 String from the input
- *
- * @param text The String to create the MD5 From
- * @return The MD5 String
- */
- private String MD5(String text) {
- MessageDigest md;
- byte[] md5hash = new byte[32];
- try {
- md = MessageDigest.getInstance("MD5");
- md.update(text.getBytes("iso-8859-1"), 0, text.length());
- md5hash = md.digest();
- } catch(Exception e) {
- Logger.error(this, "Cannot Create an MD5", e);
- return null;
- }
- return convertToHex(md5hash);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement