⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 ldapusermanager.java

📁 一个利用Java语言实现的ftp程序
💻 JAVA
字号:
/*
 * Copyright (C) The Apache Software Foundation. All rights reserved.
 *
 * This software is published under the terms of the Apache Software License
 * version 1.1, a copy of which has been included with this distribution in
 * the LICENSE file.
 */
package server.ftp.usermanager;

import java.io.File;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Properties;

import javax.naming.Context;
import javax.naming.NamingEnumeration;
import javax.naming.NamingException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import javax.naming.directory.BasicAttribute;
import javax.naming.directory.BasicAttributes;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;
import javax.naming.directory.ModificationItem;
import javax.naming.directory.SearchResult;

import server.ftp.FtpConfig;
import util.StringUtils;

/**
 * Ldap based user manager class. Tested using Netscape Directory Server 4.1.
 * The LDAP requires the password to be nonempty for simple authentication. So
 * instead of using empty string password (""), we will be using single space (" ").
 * <br>
 * The required LDAP attribute types:
 * <ul>
 *   <li>memberuid</li>
 *   <li>uid</li>
 *   <li>cn</li>
 *   <li>sn</li>
 *   <li>userpassword</li>
 *   <li>objectclass</li>
 *   <li>enableflag (created by ftp-db.ldif file)</li>
 *   <li>homedirectory</li>
 *   <li>writepermission (created by ftp-db.ldif file)</li>
 *   <li>idletime (created by ftp-db.ldif file)</li>
 *   <li>uploadrate (created by ftp-db.ldif file)</li>
 *   <li>downloadrate (created by ftp-db.ldif file)</li>
 * </ul>
 * 
 * Some of the above mentioned attribute types are created by ftd-db.ldif schema file.
 * The schema file also creates an object class called ftpUsers derived from 
 * inetOrgPerson and have all these attributes.<br>
 * Assumed LDAP objectclass hierarchy:<br>
 * <pre>
 *        top
 *         |
 *       person
 *         |
 * organizationalPerson
 *         |
 *    inetOrgPerson
 *         |
 *      ftpUsers
 * </pre>
 * 
 * @author <a href="mailto:rana_b@yahoo.com">Rana Bhattacharyya</a>
 */
public
class LdapUserManager extends UserManager {
    
    
    // LDAP attributes
    private final static String LOGIN      = "memberuid";
    private final static String UID        = "uid";
    private final static String CN         = "cn";
    private final static String SN         = "sn";
    private final static String PASSWORD   = "userpassword";
    private final static String OBJ_CLASS  = "objectclass";
    private final static String ENABLE     = "enableflag";
    private final static String ROOT_DIR   = "homedirectory";
    private final static String WRITE_PERM = "writepermission";
    private final static String IDLE_TIME  = "idletime";
    private final static String UP_RATE    = "uploadrate";
    private final static String DOWN_RATE  = "downloadrate";
    
    private final static String[] ALL_ATTRS = {
        UID,
        ENABLE,
        ROOT_DIR,
        WRITE_PERM,
        IDLE_TIME,
        UP_RATE,
        DOWN_RATE
    };
    
    private final static String[] UID_ATTRS = {
        UID
    };
    
    
    // Currently we are using only one connection.
    // So all the methods are synchronized.
    private DirContext mAdminContext;
    private Properties mAdminEnv;
    private String mstRoot;
    private String mstDnPrefix;
    private String mstDnSuffix;
    private Attribute mObjClassAttr;
    
    
    /**
     * Instantiate LDAP based <code>UserManager</code> implementation.
     */
    public LdapUserManager(FtpConfig cfg) throws Exception { 
        super(cfg);
        
        // get ldap parameters
        String url      = cfg.getProperty(FtpConfig.PREFIX + "ldap.url");
        String admin    = cfg.getProperty(FtpConfig.PREFIX + "ldap.admin");
        String password = cfg.getProperty(FtpConfig.PREFIX + "ldap.password");
        String auth     = cfg.getProperty(FtpConfig.PREFIX + "ldap.authentication");
        
        mstRoot     = cfg.getProperty(FtpConfig.PREFIX + "ldap.root");
        mstDnPrefix = cfg.getProperty(FtpConfig.PREFIX + "ldap.dn.prefix");
        mstDnSuffix = cfg.getProperty(FtpConfig.PREFIX + "ldap.dn.suffix");
        
        
        // create connection
        mAdminEnv = new Properties();
        mAdminEnv.setProperty(Context.INITIAL_CONTEXT_FACTORY, "com.sun.jndi.ldap.LdapCtxFactory");
        mAdminEnv.setProperty(Context.PROVIDER_URL, url);
        mAdminEnv.setProperty(Context.SECURITY_AUTHENTICATION, auth);             
        mAdminEnv.setProperty(Context.SECURITY_PRINCIPAL, admin);             
        mAdminEnv.setProperty(Context.SECURITY_CREDENTIALS, password);                     
        mAdminContext = new InitialDirContext(mAdminEnv);
        
        
        // create objectClass attribute
        mObjClassAttr = new BasicAttribute(OBJ_CLASS, false);
        mObjClassAttr.add("ftpUsers");
        mObjClassAttr.add("inetOrgPerson");
        mObjClassAttr.add("organizationalPerson");
        mObjClassAttr.add("person");
        mObjClassAttr.add("top");
        
        getConfig().getLogger().info("LDAP user manager opened.");
    }
    
    
    /**
     * Get all user names.
     */
    public synchronized Collection getAllUserNames() {
        ArrayList allUsers = new ArrayList();
        
        try {
            Attributes matchAttrs = new BasicAttributes(true);
            matchAttrs.put(mObjClassAttr);
            NamingEnumeration answers = mAdminContext.search(mstRoot, matchAttrs, UID_ATTRS);
            while (answers.hasMore()) {
                SearchResult sr = (SearchResult)answers.next();
                String uid = sr.getAttributes().get(UID).get().toString();
                allUsers.add(uid);
            }
        }
        catch(Exception ex) {
            getConfig().getLogger().error(ex);
        }
        
        Collections.sort(allUsers);
        return allUsers;
    } 
    
    
    /**
     * Get user object.
     */
    public synchronized User getUserByName(String name) {
        User user = null;
        
        try {
            String dn = getDN(name);
            Attributes attrs = mAdminContext.getAttributes(dn, ALL_ATTRS);
                        
            user = new User();
            user.setName(attrs.get(UID).get().toString());
            user.getVirtualDirectory().setRootDirectory(new File(attrs.get(ROOT_DIR).get().toString()));
            user.setEnabled(Boolean.TRUE.toString().equals(attrs.get(ENABLE).get().toString()));
            user.getVirtualDirectory().setWritePermission(Boolean.TRUE.toString().equals(attrs.get(WRITE_PERM).get().toString()));  
            user.setMaxIdleTime( Integer.parseInt(attrs.get(IDLE_TIME).get().toString()) );
            user.setMaxUploadRate( Integer.parseInt(attrs.get(UP_RATE).get().toString()) );
            user.setMaxDownloadRate( Integer.parseInt(attrs.get(DOWN_RATE).get().toString()) );
        }
        catch(Exception ex) {
            getConfig().getLogger().error(ex);
            user = null;
        }
        
        return user;
    }
    
    
    /**
     * User authentication.
     */
    public boolean authenticate(String login, String password) {
        
        // empty password string is not allowed
        if (password == null) {
            password = " ";
        }
        if (password.equals("")) {
            password = " ";
        }
        
        try {
            if( doesExist(login) ) {
                Properties userProp = (Properties)mAdminEnv.clone();
                String dn = getDN(login);
                userProp.setProperty(Context.SECURITY_PRINCIPAL, dn);             
                userProp.setProperty(Context.SECURITY_CREDENTIALS, password);
                
                DirContext userContext = new InitialDirContext(userProp);
                userContext.close(); 
                return true;
            }
        }
        catch(NamingException ex) {   
        }
        return false;
    }
    
    
    /**
     * Save user
     */
    public synchronized void save(User user) throws NamingException {
        if ( doesExist(user.getName()) ) {
            update(user);
        }
        else {
            add(user);
        }
    }
    
    
    /**
     * Add a new user
     */
    private synchronized void add(User user) throws NamingException {
        
        // empty password is not allowed
        if (user.getPassword() == null) {
            user.setPassword(" ");
        }
        if (user.getPassword().equals("")) {
            user.setPassword(" ");
        }
        
        String dn = getDN(user.getName());
        
        Attributes attrs = new BasicAttributes(true);
        attrs.put(new BasicAttribute(LOGIN, user.getName()));
        attrs.put(new BasicAttribute(UID, user.getName()));
        attrs.put(new BasicAttribute(CN, user.getName()));
        attrs.put(new BasicAttribute(SN, user.getName()));
        attrs.put(new BasicAttribute(PASSWORD, user.getPassword()));
        
        attrs.put(mObjClassAttr);
        
        attrs.put(new BasicAttribute(ENABLE, String.valueOf(user.getEnabled())));
        attrs.put(new BasicAttribute(ROOT_DIR, user.getVirtualDirectory().getRootDirectory()));
        attrs.put(new BasicAttribute(WRITE_PERM, String.valueOf(user.getVirtualDirectory().getWritePermission())));
        attrs.put(new BasicAttribute(IDLE_TIME, String.valueOf(user.getMaxIdleTime())));
        attrs.put(new BasicAttribute(UP_RATE, String.valueOf(user.getMaxUploadRate())));
        attrs.put(new BasicAttribute(DOWN_RATE, String.valueOf(user.getMaxDownloadRate())));
        
        mAdminContext.bind(dn, null, attrs);
    }
    
    
    /**
     * Update an existing user
     */
    private synchronized void update(User user) throws NamingException {
        String dn = getDN(user.getName());
        ArrayList mods = new ArrayList();
        
        if (user.getPassword() != null) {
            if (user.getPassword().equals("")) {
                user.setPassword(" ");
            }
            mods.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(PASSWORD, user.getPassword())));
        }
        mods.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(ENABLE, String.valueOf(user.getEnabled()))));
        mods.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(ROOT_DIR, user.getVirtualDirectory().getRootDirectory())));
        mods.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(WRITE_PERM, String.valueOf(user.getVirtualDirectory().getWritePermission()))));
        mods.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(IDLE_TIME, String.valueOf(user.getMaxIdleTime()))));
        mods.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(UP_RATE, String.valueOf(user.getMaxUploadRate()))));
        mods.add(new ModificationItem(DirContext.REPLACE_ATTRIBUTE, new BasicAttribute(DOWN_RATE, String.valueOf(user.getMaxDownloadRate()))));
        
        
        ModificationItem modArr[] = new ModificationItem[mods.size()];
        for(int i=0; i<modArr.length; i++) {
            modArr[i] = (ModificationItem)mods.get(i);
        }
        mAdminContext.modifyAttributes(dn, modArr);
    }
    
    
    /**
     * User existance check
     */
    public synchronized boolean doesExist(String name) {
        boolean bExist = false;
        try {
            String dn = getDN(name);
            mAdminContext.getAttributes(dn, UID_ATTRS);
            bExist = true;
        }
        catch(NamingException ex) {
        }
        return bExist;
    }
    
    
    /**
     * Delete user
     */
    public synchronized void delete(String userName) throws NamingException {
        String dn = getDN(userName);
        mAdminContext.unbind(dn);
    }
    
    
    /**
     * Close user manager
     */
    public synchronized void dispose() {
        if (mAdminContext != null) {
            try {
                mAdminContext.close();
            }
            catch(NamingException ex) {
            }
            mAdminContext = null;
        }
    }
    
    /**
     * Get the distinguished name (DN) for this user name
     */
    private String getDN(String userName) throws NamingException {
        
        //escape special characters
        userName = StringUtils.replaceString(userName, "\\", "\\\\");
        userName = StringUtils.replaceString(userName, ",", "\\,");        
        userName = StringUtils.replaceString(userName, "+", "\\+");
        userName = StringUtils.replaceString(userName, "\"", "\\\"");
        userName = StringUtils.replaceString(userName, "<", "\\<");
        userName = StringUtils.replaceString(userName, ">", "\\>");
        userName = StringUtils.replaceString(userName, ";", "\\;"); 
        
        return mstDnPrefix + userName + mstDnSuffix;
    }   
        
}    

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -