Changeset 25258


Ignore:
Timestamp:
2012-03-23T14:13:07+13:00 (12 years ago)
Author:
sjm84
Message:

Some major changes tidying up and adding functionality to the Administration functionality

File:
1 edited

Legend:

Unmodified
Added
Removed
  • main/trunk/greenstone3/src/java/org/greenstone/gsdl3/service/Authentication.java

    r25124 r25258  
    77
    88import org.w3c.dom.Element;
    9 import org.w3c.dom.NodeList;
    10 
     9
     10import java.util.ArrayList;
    1111import java.util.HashMap;
     12import java.util.Properties;
     13import java.util.UUID;
    1214import java.util.Vector;
     15import java.security.MessageDigest;
    1316import java.sql.SQLException;
    1417import java.util.regex.Pattern;
    1518import java.io.File;
    16 import java.io.UnsupportedEncodingException;
     19
     20import javax.mail.Message;
     21import javax.mail.Session;
     22import javax.mail.Transport;
     23import javax.mail.internet.InternetAddress;
     24import javax.mail.internet.MimeMessage;
     25
     26import net.tanesha.recaptcha.ReCaptchaImpl;
     27import net.tanesha.recaptcha.ReCaptchaImpl;
     28import net.tanesha.recaptcha.ReCaptchaResponse;
    1729
    1830public class Authentication extends ServiceRack
    1931{
     32    //Error codes
     33    protected static final int NO_ERROR = 0;
     34    protected static final int ERROR_REQUEST_HAS_NO_PARAM_LIST = -1;
     35    protected static final int ERROR_NOT_LOGGED_IN = -2;
     36    protected static final int ERROR_ADMIN_NOT_LOGGED_IN = -3;
     37    protected static final int ERROR_COULD_NOT_GET_USER_INFO = -4;
     38    protected static final int ERROR_USERNAME_NOT_SPECIFIED = -5;
     39    protected static final int ERROR_REQUESTED_USER_NOT_FOUND = -6;
     40    protected static final int ERROR_SQL_EXCEPTION = -7;
     41    protected static final int ERROR_INVALID_USERNAME = -8;
     42    protected static final int ERROR_INVALID_PASSWORD = -9;
     43    protected static final int ERROR_INCORRECT_PASSWORD = -10;
     44    protected static final int ERROR_USER_ALREADY_EXISTS = -11;
     45    protected static final int ERROR_ADDING_USER = -12;
     46    protected static final int ERROR_REMOVING_USER = -13;
     47    protected static final int ERROR_CAPTCHA_DOES_NOT_MATCH = -14;
     48    protected static final int ERROR_CAPTCHA_MISSING = -15;
     49    protected static final int ERROR_NOT_AUTHORISED = -16;
     50    protected static final int ERROR_COULD_NOT_RESET_PASSWORD = -17;
     51
     52    protected static final HashMap<Integer, String> _errorMessageMap;
     53    static
     54    {
     55        //Corresponding error messages
     56        HashMap<Integer, String> errorMessageMap = new HashMap<Integer, String>();
     57        errorMessageMap.put(ERROR_REQUEST_HAS_NO_PARAM_LIST, "The list of parameters for this request was empty.");
     58        errorMessageMap.put(ERROR_NOT_LOGGED_IN, "You must be logged in to access this page.");
     59        errorMessageMap.put(ERROR_ADMIN_NOT_LOGGED_IN, "You must be logged in as an administrator to access this page.");
     60        errorMessageMap.put(ERROR_COULD_NOT_GET_USER_INFO, "There was a error getting the user information.");
     61        errorMessageMap.put(ERROR_USERNAME_NOT_SPECIFIED, "No username was specified.");
     62        errorMessageMap.put(ERROR_REQUESTED_USER_NOT_FOUND, "The requested user was not found in the database.");
     63        errorMessageMap.put(ERROR_SQL_EXCEPTION, "There was an SQL exception while accessing the database.");
     64        errorMessageMap.put(ERROR_INVALID_USERNAME, "The username specified was invalid.");
     65        errorMessageMap.put(ERROR_INVALID_PASSWORD, "The password specified was invalid.");
     66        errorMessageMap.put(ERROR_INCORRECT_PASSWORD, "The password specified was incorrect.");
     67        errorMessageMap.put(ERROR_USER_ALREADY_EXISTS, "This user already exists and therefore cannot be added.");
     68        errorMessageMap.put(ERROR_ADDING_USER, "There was an error adding this user to the database.");
     69        errorMessageMap.put(ERROR_REMOVING_USER, "There was an error removing this user from the database.");
     70        errorMessageMap.put(ERROR_CAPTCHA_DOES_NOT_MATCH, "The words you entered did not match the image, please try again.");
     71        errorMessageMap.put(ERROR_CAPTCHA_MISSING, "The information from the captcha is missing.");
     72        errorMessageMap.put(ERROR_NOT_AUTHORISED, "You are not authorised to access this page.");
     73        errorMessageMap.put(ERROR_COULD_NOT_RESET_PASSWORD, "Your password could not be reset, your email address may be invalid.");
     74
     75        _errorMessageMap = errorMessageMap;
     76    }
     77
     78    //Admin-required operations
     79    protected static final String LIST_USERS = "ListUsers";
     80    protected static final String PERFORM_ADD = "PerformAdd";
     81    protected static final String PERFORM_EDIT = "PerformEdit";
     82    protected static final String ADD_USER = "AddUser";
     83    protected static final String EDIT_USER = "EditUser";
     84    protected static final String PERFORM_DELETE_USER = "PerformDeleteUser";
     85
     86    protected static final ArrayList<String> _adminOpList;
     87    static
     88    {
     89        ArrayList<String> opList = new ArrayList<String>();
     90        opList.add(LIST_USERS);
     91        opList.add(PERFORM_ADD);
     92        opList.add(PERFORM_EDIT);
     93        opList.add(EDIT_USER);
     94        opList.add(PERFORM_DELETE_USER);
     95
     96        _adminOpList = opList;
     97    }
     98
     99    //User-required operations
     100    protected static final String ACCOUNT_SETTINGS = "AccountSettings";
     101    protected static final String PERFORM_ACCOUNT_EDIT = "PerformAccEdit";
     102    protected static final String PERFORM_RESET_PASSWORD = "PerformResetPassword";
     103    protected static final ArrayList<String> _userOpList;
     104    static
     105    {
     106        ArrayList<String> opList = new ArrayList<String>();
     107        opList.add(ACCOUNT_SETTINGS);
     108        opList.add(PERFORM_ACCOUNT_EDIT);
     109        opList.add(PERFORM_RESET_PASSWORD);
     110        opList.addAll(_adminOpList);
     111        _userOpList = opList;
     112    }
     113
     114    //Other operations
     115    protected static final String REGISTER = "Register";
     116    protected static final String PERFORM_REGISTER = "PerformRegister";
     117    protected static final String LOGIN = "Login";
     118
    20119    //the services on offer
    21120    protected static final String AUTHENTICATION_SERVICE = "Authentication";
    22121    protected static final String GET_USER_INFORMATION_SERVICE = "GetUserInformation";
     122
     123    protected DerbyWrapper _derbyWrapper = null;
    23124
    24125    /** constructor */
     
    109210        if (paramList == null)
    110211        {
    111             logger.error(GET_USER_INFORMATION_SERVICE + ": Param list does not exist ");
    112             return null;
     212            GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_REQUEST_HAS_NO_PARAM_LIST));
     213            return result;
    113214        }
    114215
     
    119220        if (username == null)
    120221        {
    121             logger.error(GET_USER_INFORMATION_SERVICE + ": No username specified");
     222            GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_USERNAME_NOT_SPECIFIED));
    122223            return result;
    123224        }
     
    136237            if (terms.size() == 0)
    137238            {
    138                 logger.error(GET_USER_INFORMATION_SERVICE + ": Requested user was not found");
     239                GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_REQUESTED_USER_NOT_FOUND));
    139240                return result;
    140241            }
     
    144245            result.appendChild(userInfoList);
    145246
    146             Element usernameField = GSXML.createParameter(this.doc, "username", userInfo.username_);
    147             Element passwordField = GSXML.createParameter(this.doc, "password", userInfo.password_);
    148             Element groupsField = GSXML.createParameter(this.doc, "groups", userInfo.groups_);
    149             Element accountStatusField = GSXML.createParameter(this.doc, "accountstatus", userInfo.accountstatus_);
    150             Element commentField = GSXML.createParameter(this.doc, "comment", userInfo.comment_);
     247            Element usernameField = GSXML.createParameter(this.doc, "username", userInfo.username);
     248            Element passwordField = GSXML.createParameter(this.doc, "password", userInfo.password);
     249            Element groupsField = GSXML.createParameter(this.doc, "groups", userInfo.groups);
     250            Element accountStatusField = GSXML.createParameter(this.doc, "accountstatus", userInfo.accountstatus);
     251            Element commentField = GSXML.createParameter(this.doc, "comment", userInfo.comment);
    151252
    152253            userInfoList.appendChild(usernameField);
     
    156257            userInfoList.appendChild(commentField);
    157258        }
    158         catch (Exception ex)
    159         {
     259        catch (SQLException ex)
     260        {
     261            GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_SQL_EXCEPTION));
    160262            ex.printStackTrace();
    161263        }
     
    164266    }
    165267
    166     protected Element processAuthentication(Element request) throws SQLException, UnsupportedEncodingException
    167     {
     268    protected Element processAuthentication(Element request)
     269    {
     270        checkAdminUserExists();
    168271
    169272        // Create a new (empty) result message
    170273        Element result = this.doc.createElement(GSXML.RESPONSE_ELEM);
    171 
    172274        result.setAttribute(GSXML.FROM_ATT, AUTHENTICATION_SERVICE);
    173275        result.setAttribute(GSXML.TYPE_ATT, GSXML.REQUEST_TYPE_PROCESS);
    174276
    175         String lang = request.getAttribute(GSXML.LANG_ATT);
     277        // Create an Authentication node put into the result
     278        Element authenNode = this.doc.createElement(GSXML.AUTHEN_NODE_ELEM);
     279        result.appendChild(authenNode);
     280        result.appendChild(getCollectList(this.site_home + File.separatorChar + "collect"));
     281
     282        // Create a service node added into the Authentication node
     283        Element serviceNode = this.doc.createElement(GSXML.SERVICE_ELEM);
     284        authenNode.appendChild(serviceNode);
     285
    176286        // Get the parameters of the request
    177287        Element param_list = (Element) GSXML.getChildByTagName(request, GSXML.PARAM_ELEM + GSXML.LIST_MODIFIER);
    178 
    179288        if (param_list == null)
    180289        {
    181             logger.error("AddUsers request had no paramList.");
     290            serviceNode.setAttribute("operation", LOGIN);
     291            GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_REQUEST_HAS_NO_PARAM_LIST));
    182292            return result; // Return the empty result
    183293        }
    184 
    185         String aup = null; //Actions: ListUsers, AddUser, ModifyPassword, DeleteUser, Login
    186         String un = ""; //login user's name
    187         String pw = ""; //login user's password
    188         String asn = ""; //whether a user is authenticated
    189         String uan = ""; //whether a authentication for a particular action is needed
    190         String cm = ""; //whether the action is confirmed
    191 
    192         String umun = ""; //the new user name
    193         String umpw = ""; //user's new password
    194         String umas = ""; //user account status
    195         String umgp = ""; //user greoups
    196         String umc = ""; // comments for the user
    197 
    198         String oumun = ""; //the original user's name
    199         String umpw1 = ""; //user's new password
    200         String umpw2 = ""; //user's retyped new password
    201 
    202         //used for adding a list of users at one time. Format: name,password,role]name,password,role]...
    203         //in which, role may be in the format: student:[teacher's username]
    204         String unpwlist = "";
    205         String service = "";
    206 
    207         // get parameters from the request
    208         NodeList params = param_list.getElementsByTagName(GSXML.PARAM_ELEM);
    209         for (int i = 0; i < params.getLength(); i++)
    210         {
    211             Element param = (Element) params.item(i);
    212             String p_name = param.getAttribute(GSXML.NAME_ATT);
    213             String p_value = GSXML.getValue(param);
    214 
    215             if (p_name.equals("aup"))
    216             {
    217                 aup = p_value;
    218             }
    219             else if (p_name.equals("un"))
    220             {
    221                 un = p_value;
    222             }
    223             else if (p_name.equals("pw"))
    224             {
    225                 pw = p_value;
    226             }
    227             else if (p_name.equals("umun"))
    228             {
    229                 umun = p_value;
    230             }
    231             else if (p_name.equals("umpw"))
    232             {
    233                 umpw = p_value;
    234             }
    235             else if (p_name.equals("umas"))
    236             {
    237                 umas = p_value;
    238             }
    239             else if (p_name.equals("umgp"))
    240             {
    241                 umgp = p_value;
    242             }
    243             else if (p_name.equals("umc"))
    244             {
    245                 umc = p_value;
    246             }
    247             else if (p_name.equals("asn"))
    248             {
    249                 asn = p_value;
    250             }
    251             else if (p_name.equals("uan"))
    252             {
    253                 uan = p_value;
    254             }
    255             else if (p_name.equals("cm"))
    256             {
    257                 cm = p_value;
    258             }
    259             else if (p_name.equals("umpw1"))
    260             {
    261                 umpw1 = p_value;
    262             }
    263             else if (p_name.equals("umpw2"))
    264             {
    265                 umpw2 = p_value;
    266             }
    267             else if (p_name.equals("oumun"))
    268             {
    269                 oumun = p_value;
    270             }
    271             else if (p_name.equals("unpwlist"))
    272             {
    273                 unpwlist = p_value;
    274             }
    275 
    276         }
    277 
    278         // create a Authentication node put into the result
    279         Element authen_node = this.doc.createElement(GSXML.AUTHEN_NODE_ELEM);
    280         result.appendChild(authen_node);
    281         result.appendChild(getCollectList(this.site_home + File.separatorChar + "collect"));
    282         // create a service node added into the Authentication node
    283         Element service_node = this.doc.createElement(GSXML.SERVICE_ELEM);
    284         authen_node.appendChild(service_node);
    285         service_node.setAttribute("aup", aup);
    286         // user's info
    287         UserQueryResult userQueryResult = null;
     294        HashMap paramMap = GSXML.extractParams(param_list, false);
     295        String op = (String) paramMap.get("authpage");
     296        serviceNode.setAttribute("operation", op);
     297
     298        String username = null;
     299        String groups = null;
     300
     301        Element userInformation = (Element) GSXML.getChildByTagName(request, GSXML.USER_INFORMATION_ELEM);
     302        if (userInformation == null && _userOpList.contains(op))
     303        {
     304            serviceNode.setAttribute("operation", LOGIN);
     305            GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_NOT_LOGGED_IN));
     306            return result;
     307        }
     308
     309        if (userInformation != null)
     310        {
     311            username = userInformation.getAttribute(GSXML.USERNAME_ATT);
     312            groups = userInformation.getAttribute(GSXML.GROUPS_ATT);
     313        }
     314
     315        if (username == null && _userOpList.contains(op))
     316        {
     317            serviceNode.setAttribute("operation", LOGIN);
     318            GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_NOT_LOGGED_IN));
     319            return result;
     320        }
     321
     322        if (_adminOpList.contains(op) && (groups == null || !groups.matches(".*\\badministrator\\b.*")))
     323        {
     324            serviceNode.setAttribute("operation", LOGIN);
     325            GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_ADMIN_NOT_LOGGED_IN));
     326            return result;
     327        }
     328
     329        if (op.equals(LIST_USERS))
     330        {
     331            int error = addUserInformationToNode(null, serviceNode);
     332            if (error != NO_ERROR)
     333            {
     334                GSXML.addError(this.doc, result, _errorMessageMap.get(error));
     335            }
     336        }
     337        else if (op.equals(PERFORM_ADD))
     338        {
     339            String newUsername = (String) paramMap.get("username");
     340            String newPassword = (String) paramMap.get("password");
     341            String newGroups = (String) paramMap.get("groups");
     342            String newStatus = (String) paramMap.get("status");
     343            String newComment = (String) paramMap.get("comment");
     344            String newEmail = (String) paramMap.get("email");
     345
     346            int error = addUser(newUsername, newPassword, newGroups, newStatus, newComment, newEmail);
     347            if (error != NO_ERROR)
     348            {
     349                serviceNode.setAttribute("operation", ADD_USER);
     350                GSXML.addError(this.doc, result, _errorMessageMap.get(error));
     351            }
     352            else
     353            {
     354                addUserInformationToNode(null, serviceNode);
     355                serviceNode.setAttribute("operation", LIST_USERS);
     356            }
     357        }
     358        else if (op.equals(PERFORM_REGISTER))
     359        {
     360            String newUsername = (String) paramMap.get("username");
     361            String newPassword = (String) paramMap.get("password");
     362            String newEmail = (String) paramMap.get("email");
     363
     364            ReCaptchaImpl reCaptcha = new ReCaptchaImpl();
     365            reCaptcha.setPrivateKey("6LckI88SAAAAAGnGy1PwuXYZzIMXZYoPxN51bWWG"); //TODO: MOVE TO SITECONFIG.XML FILE
     366
     367            String challenge = (String) paramMap.get("recaptcha_challenge_field");
     368            String uResponse = (String) paramMap.get("recaptcha_response_field");
     369
     370            if (challenge == null || uResponse == null)
     371            {
     372                serviceNode.setAttribute("operation", REGISTER);
     373                GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_CAPTCHA_MISSING));
     374                return result;
     375            }
     376
     377            ReCaptchaResponse reCaptchaResponse = reCaptcha.checkAnswer(request.getAttribute("remoteAddress"), challenge, uResponse);
     378
     379            if (!reCaptchaResponse.isValid())
     380            {
     381                serviceNode.setAttribute("operation", REGISTER);
     382                GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_CAPTCHA_DOES_NOT_MATCH));
     383                return result;
     384            }
     385
     386            int error = addUser(newUsername, newPassword, "", "true", "", newEmail);
     387            if (error != NO_ERROR)
     388            {
     389                serviceNode.setAttribute("operation", REGISTER);
     390                GSXML.addError(this.doc, result, _errorMessageMap.get(error));
     391            }
     392        }
     393        else if (op.equals(PERFORM_EDIT))
     394        {
     395            String previousUsername = (String) paramMap.get("prevUsername");
     396            String newUsername = (String) paramMap.get("newUsername");
     397            String newPassword = (String) paramMap.get("password");
     398            String newGroups = (String) paramMap.get("groups");
     399            String newStatus = (String) paramMap.get("status");
     400            String newComment = (String) paramMap.get("comment");
     401            String newEmail = (String) paramMap.get("email");
     402
     403            if (newPassword == null)
     404            {
     405                newPassword = retrieveDataForUser(previousUsername, "password");
     406            }
     407
     408            int error = removeUser(previousUsername);
     409            if (error != NO_ERROR)
     410            {
     411                if (error == ERROR_USERNAME_NOT_SPECIFIED)
     412                {
     413                    addUserInformationToNode(null, serviceNode);
     414                    serviceNode.setAttribute("operation", LIST_USERS);
     415                }
     416                else
     417                {
     418                    serviceNode.setAttribute("operation", EDIT_USER);
     419                    GSXML.addError(this.doc, result, _errorMessageMap.get(error));
     420                }
     421                return result;
     422            }
     423            error = addUser(newUsername, newPassword, newGroups, newStatus, newComment, newEmail);
     424            if (error != NO_ERROR)
     425            {
     426                serviceNode.setAttribute("operation", EDIT_USER);
     427                GSXML.addError(this.doc, result, _errorMessageMap.get(error));
     428            }
     429            else
     430            {
     431                addUserInformationToNode(null, serviceNode);
     432                serviceNode.setAttribute("operation", LIST_USERS);
     433            }
     434        }
     435        else if (op.equals(PERFORM_ACCOUNT_EDIT))
     436        {
     437            String previousUsername = (String) paramMap.get("prevUsername");
     438            String newUsername = (String) paramMap.get("newUsername");
     439            String oldPassword = (String) paramMap.get("oldPassword");
     440            String newPassword = (String) paramMap.get("newPassword");
     441            String newEmail = (String) paramMap.get("newEmail");
     442
     443            //Make sure the user name does not already exist
     444            if (!previousUsername.equals(newUsername) && checkUserExists(newUsername))
     445            {
     446                addUserInformationToNode(previousUsername, serviceNode);
     447                serviceNode.setAttribute("operation", ACCOUNT_SETTINGS);
     448                GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_USER_ALREADY_EXISTS));
     449                return result;
     450            }
     451
     452            String prevPassword = retrieveDataForUser(previousUsername, "password");
     453
     454            if (newPassword != null)
     455            {
     456                oldPassword = hashPassword(oldPassword);
     457
     458                if (oldPassword == null || !oldPassword.equals(prevPassword))
     459                {
     460                    addUserInformationToNode(previousUsername, serviceNode);
     461                    serviceNode.setAttribute("operation", ACCOUNT_SETTINGS);
     462                    GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_INCORRECT_PASSWORD));
     463                    return result;
     464                }
     465            }
     466            else
     467            {
     468                newPassword = prevPassword;
     469            }
     470
     471            String prevGroups = retrieveDataForUser(previousUsername, "groups");
     472            String prevStatus = retrieveDataForUser(previousUsername, "status");
     473            String prevComment = retrieveDataForUser(previousUsername, "comment");
     474
     475            int error = removeUser(previousUsername);
     476            if (error != NO_ERROR)
     477            {
     478                if (error == ERROR_USERNAME_NOT_SPECIFIED)
     479                {
     480                    addUserInformationToNode(null, serviceNode);
     481                    serviceNode.setAttribute("operation", LIST_USERS);
     482                }
     483                else
     484                {
     485                    addUserInformationToNode(previousUsername, serviceNode);
     486                    serviceNode.setAttribute("operation", ACCOUNT_SETTINGS);
     487                    GSXML.addError(this.doc, result, _errorMessageMap.get(error));
     488                }
     489                return result;
     490            }
     491
     492            error = addUser(newUsername, newPassword, prevGroups, prevStatus, prevComment, newEmail);
     493            if (error != NO_ERROR)
     494            {
     495                GSXML.addError(this.doc, result, _errorMessageMap.get(error));
     496            }
     497
     498            addUserInformationToNode(null, serviceNode);
     499            serviceNode.setAttribute("operation", LIST_USERS);
     500        }
     501        else if (op.equals(EDIT_USER))
     502        {
     503            String editUsername = (String) paramMap.get("username");
     504            int error = addUserInformationToNode(editUsername, serviceNode);
     505            if (error != NO_ERROR)
     506            {
     507                GSXML.addError(this.doc, result, _errorMessageMap.get(error));
     508            }
     509        }
     510        else if (op.equals(ACCOUNT_SETTINGS))
     511        {
     512            String editUsername = (String) paramMap.get("username");
     513           
     514            if(editUsername == null)
     515            {
     516                serviceNode.setAttribute("operation", "");
     517                GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_USERNAME_NOT_SPECIFIED));
     518                return result;
     519            }
     520           
     521            if(!editUsername.equals(username))
     522            {
     523                serviceNode.setAttribute("operation", LOGIN);
     524                GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_NOT_AUTHORISED));
     525                return result;
     526            }
     527            int error = addUserInformationToNode(editUsername, serviceNode);
     528            if (error != NO_ERROR)
     529            {
     530                GSXML.addError(this.doc, result, _errorMessageMap.get(error));
     531            }
     532        }
     533        else if (op.equals(PERFORM_RESET_PASSWORD))
     534        {
     535            String passwordResetUser = (String) paramMap.get("username");
     536           
     537            String newPassword = UUID.randomUUID().toString();
     538            newPassword = newPassword.substring(0, newPassword.indexOf("-"));
     539           
     540            String email = retrieveDataForUser(passwordResetUser, "email");
     541            String from = "[email protected]";
     542            String host = request.getAttribute("remoteAddress");
     543           
     544            Properties props = System.getProperties();
     545            props.setProperty("mail.smtp.host", host);
     546           
     547            Session session = Session.getDefaultInstance(props);
     548           
     549            try
     550            {
     551                MimeMessage message = new MimeMessage(session);
     552                message.setFrom(new InternetAddress(from));
     553                message.addRecipient(Message.RecipientType.TO, new InternetAddress(email));
     554                message.setSubject("Password reset");
     555                message.setText("Your password was reset to " + newPassword);
     556               
     557                Transport.send(message);
     558            }
     559            catch(Exception ex)
     560            {
     561                GSXML.addError(this.doc, result, _errorMessageMap.get(ERROR_COULD_NOT_RESET_PASSWORD));
     562                serviceNode.setAttribute("operation", ACCOUNT_SETTINGS);
     563                ex.printStackTrace();
     564                return result;
     565            }
     566           
     567            System.err.println("MAIL SUCCESS");
     568        }
     569        else if (op.equals(PERFORM_DELETE_USER))
     570        {
     571            String usernameToDelete = (String) paramMap.get("username");
     572            int error = removeUser(usernameToDelete);
     573            if (error != NO_ERROR)
     574            {
     575                GSXML.addError(this.doc, result, _errorMessageMap.get(error));
     576            }
     577            addUserInformationToNode(null, serviceNode);
     578            serviceNode.setAttribute("operation", LIST_USERS);
     579        }
     580
     581        return result;
     582    }
     583
     584    public static String hashPassword(String password)
     585    {
     586        String hashedPassword = null;
     587        try
     588        {
     589            MessageDigest digest = MessageDigest.getInstance("SHA-1");
     590            digest.reset();
     591            hashedPassword = new String(digest.digest(password.getBytes("UTF-8")));
     592        }
     593        catch (Exception ex)
     594        {
     595            ex.printStackTrace();
     596        }
     597        return hashedPassword;
     598    }
     599
     600    private void checkAdminUserExists()
     601    {
     602        if (_derbyWrapper == null)
     603        {
     604            openDatabase();
     605        }
     606
     607        UserQueryResult userQueryResult = _derbyWrapper.findUser(null, null);
     608        closeDatabase();
     609
     610        if (userQueryResult != null)
     611        {
     612            Vector userInfo = userQueryResult.users;
     613
     614            boolean adminFound = false;
     615            for (int i = 0; i < userQueryResult.getSize(); i++)
     616            {
     617                if (((UserTermInfo) userInfo.get(i)).groups != null && ((UserTermInfo) userInfo.get(i)).groups.matches(".*\\badministrator\\b.*"))
     618                {
     619                    adminFound = true;
     620                }
     621            }
     622
     623            if (!adminFound)
     624            {
     625                addUser("admin", "admin", "administrator", "true", "Change the password for this account as soon as possible", "");
     626            }
     627        }
     628
     629        closeDatabase();
     630    }
     631
     632    private boolean openDatabase()
     633    {
     634        _derbyWrapper = new DerbyWrapper();
    288635
    289636        // check the usersDb database, if it isn't existing, check the etc dir, create the etc dir if it isn't existing, then create the  user database and add a "admin" user
    290637        String usersDB_dir = this.site_home + File.separatorChar + "etc" + File.separatorChar + "usersDB";
    291         DerbyWrapper derbyWrapper = new DerbyWrapper();
    292638        File usersDB_file = new File(usersDB_dir);
    293639        if (!usersDB_file.exists())
     
    301647                {
    302648                    logger.error("Couldn't create the etc dir under " + this.site_home + ".");
    303                     return result;
    304                 }
    305             }
    306             derbyWrapper.connectDatabase(usersDB_dir, true);
    307             derbyWrapper.createDatabase();
     649                    return false;
     650                }
     651            }
     652            _derbyWrapper.connectDatabase(usersDB_dir, true);
     653            _derbyWrapper.createDatabase();
    308654        }
    309655        else
    310656        {
    311             derbyWrapper.connectDatabase(usersDB_dir, false);
    312         }
    313 
    314         // Action: login
    315         if (aup.equals("Login"))
    316         {
    317             if (uan.equals(""))
    318             { //return a login page, if the user's name is not given
    319                 service_node.setAttribute("info", "Login");
    320                 derbyWrapper.closeDatabase();
    321                 return result;
    322             }
    323             String groups = "";
    324             // if the authentication(uan=1) is required,but the user hasn't been authenticated(asn=0),the user is asked to login first
    325             if ((uan.equals("1") && asn.equals("0")))
    326             {
    327                 if ((un.length() == 0) && (pw.length() == 0))
    328                 {
    329                     service_node.setAttribute("asn", "0");
    330                     service_node.setAttribute("info", "Login");
    331                     derbyWrapper.closeDatabase();
    332                     return result;
    333                 }
    334                 if ((un.length() == 0) || (pw.length() == 0))
    335                 {
    336                     service_node.setAttribute("asn", "0");
    337                     service_node.setAttribute("info", "Login");
    338                     service_node.setAttribute("err", "un-pw-err");
    339                     derbyWrapper.closeDatabase();
    340                     return result;
    341                 }
    342                 else
    343                 {
    344                     userQueryResult = derbyWrapper.findUser(un, pw);//looking for the user from the users table
    345                     service_node.setAttribute(GSXML.NAME_ATT, "Authentication");
    346                     service_node.setAttribute("un", un);
    347                     if (userQueryResult == null)
    348                     {
    349                         //the user isn't a vaild user
    350                         service_node.setAttribute("asn", "0");
    351                         service_node.setAttribute("err", "un-pw-err");// either unsername or password is wrong
    352                         service_node.setAttribute("info", "Login");
    353                         derbyWrapper.closeDatabase();
    354                         return result;
    355                     }
    356                     else
    357                     {
    358                         // asn="1"; //the user is a member of the "administrator" group
    359                         Vector userInfo = userQueryResult.users_;
    360                         groups = ((UserTermInfo) userInfo.get(0)).groups_;
    361                         String accountstatus = ((UserTermInfo) userInfo.get(0)).accountstatus_;
    362                         if (accountstatus.trim().equals("false"))
    363                         {
    364                             service_node.setAttribute("asn", "0");
    365                             service_node.setAttribute("err", "as-false");//the account status is false
    366                             service_node.setAttribute("info", "Login");
    367                             derbyWrapper.closeDatabase();
    368                             return result;
    369                         }
    370                         String[] groups_array = groups.split(",");
    371                         for (int i = 0; i < groups_array.length; i++)
    372                         {
    373                             if ((groups_array[i].trim().toLowerCase()).equals("administrator"))
    374                             {// check whether the user is in the administrator group
    375                                 asn = "1";
    376                                 service_node.setAttribute("asn", "1");
    377                                 break;
    378                             }
    379                         }
    380                         if (!asn.equals("1"))
    381                         {
    382                             asn = "2";
    383                             service_node.setAttribute("asn", "2");//the user is authenticated                           
    384                         }
    385                     }
    386                 }
    387             }
    388 
    389             //asn!=0 This is a valid user
    390             if (!asn.equals("0"))
    391             {
    392                 service_node.setAttribute("info", "Login");
    393                 service_node.setAttribute("un", un);
    394                 service_node.setAttribute("pw", pw);
    395                 service_node.setAttribute("asn", asn);
    396                 service_node.setAttribute("umgp", groups);
    397                 derbyWrapper.closeDatabase();
    398                 return result;
    399             }
    400         }
    401 
    402         //Action: listuser
    403         if (aup.equals("ListUsers"))
    404         {
    405             if (asn.equals("") && un.equals(""))
    406             {
    407                 service_node.setAttribute("info", "Login");
    408                 derbyWrapper.closeDatabase();
    409                 return result;
    410             }
    411 
    412             //valid users but not in the administrator group(asn=2), they cannot list all users
    413             if (asn.equals("2"))
    414             {
    415                 service_node.setAttribute("info", "Login");
    416                 service_node.setAttribute("err", "no-permission");
    417                 service_node.setAttribute("un", un);
    418                 service_node.setAttribute("asn", asn);
    419                 derbyWrapper.closeDatabase();
    420                 return result;
    421             }
    422             //valid users belong to the administrator group(asn=1), they can list all users
    423             if (asn.equals("1"))
    424             {
    425                 userQueryResult = derbyWrapper.findUser(null, null);
    426                 derbyWrapper.closeDatabase();
    427                 service_node.setAttribute(GSXML.NAME_ATT, "Authentication");
    428                 service_node.setAttribute("un", un);
    429                 service_node.setAttribute("asn", asn);
    430 
    431                 if (userQueryResult != null && userQueryResult.getSize() > 0)
    432                 {
    433                     service_node.setAttribute("info", "all-un"); // got a user list
    434                     Element user_node = getUserNode(userQueryResult);
    435                     service_node.appendChild(user_node);
    436                     derbyWrapper.closeDatabase();
    437                     return result;
    438                 }
    439                 else
    440                 {
    441                     service_node.setAttribute("err", "no-un"); // no user returned
    442                     derbyWrapper.closeDatabase();
    443                     return result;
    444                 }
    445             }
    446         }
    447         //TODO: Action : addStudents (bulk adding)
    448         if (aup.equals("AddStudents"))
    449         {
    450             String[] users = unpwlist.split("]");
    451             for (int i = 0; i < users.length; i++)
    452             {
    453                 String[] user = users[i].split(",");
    454                 String uname = user[0];
    455                 String password = user[1];
    456                 String group = user[2].split(":")[0];
    457                 String add_user = derbyWrapper.addUser(uname, password, group, "true", "");
    458                 if (add_user.equals("succeed"))
    459                 {
    460                     userQueryResult = derbyWrapper.findUser(null, null);
    461                     derbyWrapper.closeDatabase();
    462                     service_node.setAttribute("info", "all-un"); // return a list of all users if the user has been added
    463                     Element user_node = getUserNode(userQueryResult);
    464                     service_node.appendChild(user_node);
    465                     derbyWrapper.closeDatabase();
    466                     return result;
    467                 }
    468             }
    469         }
    470 
    471         //Action : adduder
    472         if (aup.equals("AddUser"))
    473         {
    474             if (asn.equals("") && un.equals(""))
    475             {
    476                 service_node.setAttribute("info", "Login");
    477                 derbyWrapper.closeDatabase();
    478                 return result;
    479             }
    480             //valid users can't add a new user because they aren't in the administrator group(asn=2)
    481             if (asn.equals("2"))
    482             {
    483                 service_node.setAttribute("info", "Login");
    484                 service_node.setAttribute("err", "no-permission");
    485                 service_node.setAttribute("un", un);
    486                 service_node.setAttribute("asn", asn);
    487                 derbyWrapper.closeDatabase();
    488                 return result;
    489             }
    490             //valid users are in the administrator group, they can add a new user(asn=1)
    491             if (asn.equals("1"))
    492             {
    493                 service_node.setAttribute(GSXML.NAME_ATT, "Authentication");
    494                 service_node.setAttribute("un", un);
    495                 service_node.setAttribute("asn", asn);
    496 
    497                 if (umun.length() == 0 && umpw.length() == 0 && umgp.length() == 0 && umas.length() == 0 && umc.length() == 0)
    498                 {
    499                     service_node.setAttribute("info", "adduser_interface");
    500                     derbyWrapper.closeDatabase();
    501                     return result;
    502                 }
    503 
    504                 //check the strings of username and password
    505                 if ((umun == null) || (umun.length() < 2) || (umun.length() > 30) || (!(Pattern.matches("[a-zA-Z0-9//_//.]+", umun))))
    506                 {
    507                     service_node.setAttribute("err", "un-err"); //the input username string is illegal
    508                     service_node.setAttribute("info", "adduser_interface");
    509                     derbyWrapper.closeDatabase();
    510                     return result;
    511                 }
    512 
    513                 if ((umpw == null) || (umpw.length() < 3) || (umpw.length() > 8) || (!(Pattern.matches("[\\p{ASCII}]+", umpw))))
    514                 {
    515                     service_node.setAttribute("err", "pw-err"); //the input passwrod string is illegal
    516                     service_node.setAttribute("info", "adduser_interface");
    517                     derbyWrapper.closeDatabase();
    518                     return result;
    519                 }
    520 
    521                 // add the new users into the users table
    522                 umgp = umgp.replaceAll(" ", "");//get rid of the space of the groups string
    523                 userQueryResult = derbyWrapper.findUser(umun, null);// check whether the new user name has existed in the table.
    524                 if (userQueryResult != null)
    525                 {
    526                     service_node.setAttribute("err", "un-exist"); //the new username string is duplicated
    527                     service_node.setAttribute("info", "adduser_interface");
    528                     derbyWrapper.closeDatabase();
    529                     return result;
    530                 }
    531                 else
    532                 {
    533                     String add_user = derbyWrapper.addUser(umun, umpw, umgp, umas, umc);
    534                     if (add_user.equals("succeed"))
    535                     {
    536                         userQueryResult = derbyWrapper.findUser(null, null);
    537                         derbyWrapper.closeDatabase();
    538                         service_node.setAttribute("info", "all-un"); // return a list of all users if the user has been added
    539                         Element user_node = getUserNode(userQueryResult);
    540                         service_node.appendChild(user_node);
    541                         derbyWrapper.closeDatabase();
    542                         return result;
    543                     }
    544                     else
    545                     {
    546                         derbyWrapper.closeDatabase();
    547                         service_node.setAttribute("err", add_user);// return the error message if the user couldn't be added
    548                         derbyWrapper.closeDatabase();
    549                         return result;
    550                     }
    551                 }
    552             }
    553         }
    554 
    555         //Action: edituser
    556         if (aup.equals("EditUser"))
    557         {
    558             service_node.setAttribute(GSXML.NAME_ATT, "Authentication");
    559             service_node.setAttribute("un", un);
    560             service_node.setAttribute("asn", asn);
    561 
    562             //Get the user's info from the database
    563             if (cm.length() == 0)
    564             {
    565                 service_node.setAttribute("info", "edituser-interface");
    566                 userQueryResult = derbyWrapper.findUser(umun, null);
    567                 derbyWrapper.closeDatabase();
    568                 Vector userInfo = userQueryResult.users_;
    569                 String username = ((UserTermInfo) userInfo.get(0)).username_;
    570                 String password = ((UserTermInfo) userInfo.get(0)).password_;
    571                 String groups = ((UserTermInfo) userInfo.get(0)).groups_;
    572                 String accountstatus = ((UserTermInfo) userInfo.get(0)).accountstatus_;
    573                 String comment = ((UserTermInfo) userInfo.get(0)).comment_;
    574 
    575                 service_node.setAttribute("oumun", oumun);
    576                 service_node.setAttribute("umun", username);
    577                 service_node.setAttribute("umpw", password);
    578                 service_node.setAttribute("umgp", groups);
    579                 service_node.setAttribute("umas", accountstatus);
    580                 service_node.setAttribute("umc", comment);
    581                 derbyWrapper.closeDatabase();
    582                 return result;
    583             }
    584 
    585             //Commit the modified user's info to the database
    586             if (cm.toLowerCase().equals("submit"))
    587             {
    588                 if (oumun.equals(umun))
    589                 {// the user's name hasn't been changed, update the user's info
    590                     if (umpw.length() == 0)
    591                     {
    592                         derbyWrapper.modifyUserInfo(umun, null, umgp, umas, umc);
    593                         userQueryResult = derbyWrapper.findUser(null, null);
    594                         derbyWrapper.closeDatabase();
    595                         service_node.setAttribute("info", "all-un"); // the user's info has been updated, return a list of all users
    596                         Element user_node = getUserNode(userQueryResult);
    597                         service_node.appendChild(user_node);
    598                         derbyWrapper.closeDatabase();
    599                         return result;
    600                     }
    601                     else
    602                     {
    603                         if ((umpw.length() == 0) || (umpw.length() < 3) || (umpw.length() > 8) || (!(Pattern.matches("[\\p{ASCII}]+", umpw))))
    604                         {
    605                             service_node.setAttribute("err", "umpw-err"); //the input passwrod string is illegal
    606                             service_node.setAttribute("info", "edituser-interface");
    607                             service_node.setAttribute("umun", umun);
    608                             service_node.setAttribute("umpw", umpw);
    609                             service_node.setAttribute("umgp", umgp);
    610                             service_node.setAttribute("umas", umas);
    611                             service_node.setAttribute("umc", umc);
    612                             service_node.setAttribute("oumun", oumun);
    613                             derbyWrapper.closeDatabase();
    614                             return result;
    615                         }
    616                         umgp = umgp.replaceAll(" ", "");// get rid of the space
    617                         derbyWrapper.modifyUserInfo(umun, umpw, umgp, umas, umc);
    618                         userQueryResult = derbyWrapper.listAllUser();
    619                         derbyWrapper.closeDatabase();
    620                         service_node.setAttribute("info", "all-un"); // if the new user has been added successfully, return a list of all users
    621                         Element user_node = getUserNode(userQueryResult);
    622                         service_node.appendChild(user_node);
    623                         derbyWrapper.closeDatabase();
    624                         return result;
    625                     }
    626                 }
    627                 // The user's name has been changed, add a new user record to the database
    628                 else
    629                 {
    630                     if ((umun.length() == 0) || (umun.length() < 2) || (umun.length() > 30) || (!(Pattern.matches("[a-zA-Z0-9//_//.]+", umun))))
    631                     {
    632                         service_node.setAttribute("err", "umun-err"); //the input username string is illegal
    633                         service_node.setAttribute("umun", umun);
    634                         service_node.setAttribute("umpw", umpw);
    635                         service_node.setAttribute("umgp", umgp);
    636                         service_node.setAttribute("umas", umas);
    637                         service_node.setAttribute("umc", umc);
    638                         service_node.setAttribute("oumun", oumun);
    639                         service_node.setAttribute("info", "edituser-interface");
    640                         derbyWrapper.closeDatabase();
    641                         return result;
    642                     }
    643                     if (umpw.length() == 0)
    644                     {
    645                         service_node.setAttribute("err", "ini-umpw-err"); //the input passwrod string is illegal
    646                         service_node.setAttribute("info", "edituser-interface");
    647                         service_node.setAttribute("umun", umun);
    648                         service_node.setAttribute("umpw", umpw);
    649                         service_node.setAttribute("umgp", umgp);
    650                         service_node.setAttribute("umas", umas);
    651                         service_node.setAttribute("umc", umc);
    652                         service_node.setAttribute("oumun", oumun);
    653                         derbyWrapper.closeDatabase();
    654                         return result;
    655                     }
    656                     if ((umpw.length() < 3) || (umpw.length() > 8) || (!(Pattern.matches("[\\p{ASCII}]+", umpw))))
    657                     {
    658                         service_node.setAttribute("err", "umpw-err"); //the input passwrod string is illegal
    659                         service_node.setAttribute("info", "edituser-interface");
    660                         service_node.setAttribute("umun", umun);
    661                         service_node.setAttribute("umpw", umpw);
    662                         service_node.setAttribute("umgp", umgp);
    663                         service_node.setAttribute("umas", umas);
    664                         service_node.setAttribute("umc", umc);
    665                         service_node.setAttribute("oumun", oumun);
    666                         derbyWrapper.closeDatabase();
    667                         return result;
    668                     }
    669                     umgp = umgp.replaceAll(" ", "");// get rid of the space
    670                     userQueryResult = derbyWrapper.findUser(umun, null);// check whether the new user name has existed in the table.
    671                     if (userQueryResult != null)
    672                     {
    673                         service_node.setAttribute("err", "un-exist"); //the new username string is duplicated
    674                         service_node.setAttribute("info", "edituser-interface");
    675                         service_node.setAttribute("umun", "");
    676                         service_node.setAttribute("umpw", "");
    677                         service_node.setAttribute("umgp", umgp);
    678                         service_node.setAttribute("umas", umas);
    679                         service_node.setAttribute("umc", umc);
    680                         service_node.setAttribute("oumun", oumun);
    681                         derbyWrapper.closeDatabase();
    682                         return result;
    683                     }
    684                     else
    685                     {
    686                         derbyWrapper.addUser(umun, umpw, umgp, umas, umc);
    687                         userQueryResult = derbyWrapper.listAllUser();
    688                         derbyWrapper.closeDatabase();
    689                         service_node.setAttribute("info", "all-un"); // if the new user has been added successfully, return a list of all users
    690                         Element user_node = getUserNode(userQueryResult);
    691                         service_node.appendChild(user_node);
    692                         derbyWrapper.closeDatabase();
    693                         return result;
    694                     }
    695                 }
    696             }
    697 
    698             if (cm.toLowerCase().equals("cancel"))
    699             {
    700                 userQueryResult = derbyWrapper.listAllUser();
    701                 derbyWrapper.closeDatabase();
    702                 service_node.setAttribute("info", "all-un"); // if the new user has been added successfully, return a list of all users
    703                 Element user_node = getUserNode(userQueryResult);
    704                 service_node.appendChild(user_node);
    705                 derbyWrapper.closeDatabase();
    706                 return result;
    707             }
    708         }
    709 
    710         //Action: modifypassword
    711         if (aup.equals("ModifyPassword"))
    712         {
    713             if (un.equals(""))
    714             {
    715                 service_node.setAttribute("info", "Login");
    716                 derbyWrapper.closeDatabase();
    717                 return result;
    718             }
    719 
    720             service_node.setAttribute(GSXML.NAME_ATT, "Authentication");
    721             service_node.setAttribute("un", un);
    722             service_node.setAttribute("asn", asn);
    723 
    724             userQueryResult = derbyWrapper.findUser(un, null);
    725             Vector userInfo = userQueryResult.users_;
    726             pw = ((UserTermInfo) userInfo.get(0)).password_;
    727 
    728             if ((umpw1.length() == 0) && (umpw2.length() == 0) && (umpw.length() == 0))
    729             {
    730                 service_node.setAttribute("info", "modify_interface");// call the interface of the modifying password
    731                 derbyWrapper.closeDatabase();
    732                 return result;
    733             }
    734 
    735             if (!pw.equals(umpw) && umpw.length() > 0)
    736             {
    737                 service_node.setAttribute("info", "modify_interface");
    738                 service_node.setAttribute("err", "pw-umpw-nm-err");//if the original password is not match
    739                 derbyWrapper.closeDatabase();
    740                 return result;
    741             }
    742 
    743             if ((umpw1.length() == 0) || (umpw2.length() == 0))
    744             {
    745                 service_node.setAttribute("info", "modify_interface");
    746                 service_node.setAttribute("err", "umpw1-umpw2-null-err");//if one of the password strings is none,return the err info back
    747                 derbyWrapper.closeDatabase();
    748                 return result;
    749             }
    750 
    751             if (!umpw1.equals(umpw2))
    752             {
    753                 service_node.setAttribute("info", "modify_interface");
    754                 service_node.setAttribute("err", "umpw1-umpw2-nm-err");//if one of the password strings is none,return the err info back
    755                 derbyWrapper.closeDatabase();
    756                 return result;
    757             }
    758 
    759             if (umpw.length() == 0)
    760             {
    761                 service_node.setAttribute("info", "modify_interface");
    762                 service_node.setAttribute("err", "umpw-null-err");//if one of the password strings is none,return the err info back
    763                 derbyWrapper.closeDatabase();
    764                 return result;
    765             }
    766             //check the new password and the retyped password
    767             if ((umpw1 == null) || (umpw1.length() < 3) || (umpw1.length() > 8) || (!(Pattern.matches("[\\p{ASCII}]+", umpw1))))
    768             {
    769                 service_node.setAttribute("info", "modify_interface");
    770                 service_node.setAttribute("err", "umpw1-err");// the new password is illegal
    771                 derbyWrapper.closeDatabase();
    772                 return result;
    773             }
    774 
    775             if ((umpw2 == null) || (umpw2.length() < 3) || (umpw2.length() > 8) || (!(Pattern.matches("[\\p{ASCII}]+", umpw2))))
    776             {
    777                 service_node.setAttribute("info", "modify_interface");
    778                 service_node.setAttribute("err", "umpw2-err"); // the retyped password is illegal
    779                 derbyWrapper.closeDatabase();
    780                 return result;
    781             }
    782             String modify_user_info = derbyWrapper.modifyUserInfo(un, umpw1, null, null, null);
    783             if (modify_user_info.equals("succeed"))
    784             {
    785                 service_node.setAttribute("err", "");// the passsword has been changed successfully
    786                 derbyWrapper.closeDatabase();
    787                 return result;
     657            _derbyWrapper.connectDatabase(usersDB_dir, false);
     658        }
     659        return true;
     660    }
     661
     662    private void closeDatabase()
     663    {
     664        if (_derbyWrapper != null)
     665        {
     666            _derbyWrapper.closeDatabase();
     667            _derbyWrapper = null;
     668        }
     669    }
     670
     671    private int addUserInformationToNode(String username, Element serviceNode)
     672    {
     673        if (_derbyWrapper == null)
     674        {
     675            openDatabase();
     676        }
     677
     678        UserQueryResult userQueryResult = _derbyWrapper.findUser(username, null);
     679        closeDatabase();
     680
     681        if (userQueryResult != null)
     682        {
     683            Element user_node = getUserNode(userQueryResult);
     684            serviceNode.appendChild(user_node);
     685            closeDatabase();
     686            return NO_ERROR;
     687        }
     688
     689        closeDatabase();
     690        return ERROR_COULD_NOT_GET_USER_INFO;
     691    }
     692
     693    private int removeUser(String username)
     694    {
     695        if (username == null)
     696        {
     697            return ERROR_USERNAME_NOT_SPECIFIED;
     698        }
     699
     700        if (_derbyWrapper == null)
     701        {
     702            openDatabase();
     703        }
     704
     705        boolean success = _derbyWrapper.deleteUser(username);
     706        closeDatabase();
     707
     708        if (success)
     709        {
     710            return NO_ERROR;
     711        }
     712
     713        return ERROR_REMOVING_USER;
     714    }
     715
     716    private int addUser(String newUsername, String newPassword, String newGroups, String newStatus, String newComment, String newEmail)
     717    {
     718        if (_derbyWrapper == null)
     719        {
     720            openDatabase();
     721        }
     722
     723        //Check the given user name
     724        if ((newUsername == null) || (newUsername.length() < 2) || (newUsername.length() > 30) || (!(Pattern.matches("[a-zA-Z0-9//_//.]+", newUsername))))
     725        {
     726            closeDatabase();
     727            return ERROR_INVALID_USERNAME;
     728        }
     729
     730        //Check the given password
     731        if ((newPassword == null) || (newPassword.length() < 3) || (newPassword.length() > 8) || (!(Pattern.matches("[\\p{ASCII}]+", newPassword))))
     732        {
     733            closeDatabase();
     734            return ERROR_INVALID_PASSWORD;
     735        }
     736
     737        newPassword = hashPassword(newPassword);
     738
     739        newGroups = newGroups.replaceAll(" ", "");
     740
     741        //Check if the user already exists
     742        UserQueryResult userQueryResult = _derbyWrapper.findUser(newUsername, null);
     743        if (userQueryResult != null)
     744        {
     745            return ERROR_USER_ALREADY_EXISTS;
     746        }
     747        else
     748        {
     749            System.err.println("ADDING " + newUsername + " " + newPassword);
     750            boolean success = _derbyWrapper.addUser(newUsername, newPassword, newGroups, newStatus, newComment, newEmail);
     751            if (!success)
     752            {
     753                closeDatabase();
     754                return ERROR_ADDING_USER;
     755            }
     756        }
     757        closeDatabase();
     758        return NO_ERROR;
     759    }
     760
     761    private boolean checkUserExists(String username)
     762    {
     763        if (_derbyWrapper == null)
     764        {
     765            openDatabase();
     766        }
     767
     768        try
     769        {
     770            UserQueryResult result = _derbyWrapper.findUser(username);
     771
     772            if (result != null)
     773            {
     774                return true;
    788775            }
    789776            else
    790777            {
    791                 service_node.setAttribute("err", modify_user_info);// return the error message of the pasword couldn't be modified
    792                 derbyWrapper.closeDatabase();
    793                 return result;
    794             }
    795         }
    796 
    797         //Action: deleteuser
    798         if (aup.equals("DeleteUser"))
    799         {
    800             service_node.setAttribute("un", un);
    801             service_node.setAttribute("asn", asn);
    802             service_node.setAttribute("umun", umun);
    803             if (cm.equals("yes"))
    804             {
    805                 String delete_user = derbyWrapper.deleteUser(umun);
    806                 if (delete_user.equals("succeed"))
    807                 {
    808                     service_node.setAttribute("err", "");
    809                     userQueryResult = derbyWrapper.listAllUser();
    810                     service_node.setAttribute("info", "all-un"); //  return a list of all users
    811                     Element user_node = getUserNode(userQueryResult);
    812                     service_node.appendChild(user_node);
    813                 }
    814                 else
    815                 {
    816                     service_node.setAttribute("err", delete_user);//return the error message
    817                     derbyWrapper.closeDatabase();
    818                     return result;
    819                 }
    820             }
    821             else if (cm.equals("no"))
    822             {
    823                 service_node.setAttribute("err", "");
    824                 userQueryResult = derbyWrapper.listAllUser();
    825                 service_node.setAttribute("info", "all-un"); //  return a list of all users
    826                 Element user_node = getUserNode(userQueryResult);
    827                 service_node.appendChild(user_node);
    828                 derbyWrapper.closeDatabase();
    829                 return result;
    830             }
    831             else
    832             {
    833                 service_node.setAttribute("info", "confirm");
    834                 derbyWrapper.closeDatabase();
    835                 return result;
    836             }
    837         }
    838 
    839         return result;
     778                return false;
     779            }
     780
     781        }
     782        catch (Exception ex)
     783        {
     784            return false;
     785        }
     786        finally
     787        {
     788            closeDatabase();
     789        }
     790    }
     791
     792    private String retrieveDataForUser(String username, String dataType)
     793    {
     794        if (_derbyWrapper == null)
     795        {
     796            openDatabase();
     797        }
     798
     799        String password = null;
     800
     801        try
     802        {
     803            UserQueryResult result = _derbyWrapper.findUser(username);
     804            Vector userInfo = result.users;
     805
     806            for (int i = 0; i < result.getSize(); i++)
     807            {
     808                if (dataType.equals("password"))
     809                {
     810                    return ((UserTermInfo) userInfo.get(i)).password;
     811                }
     812                else if (dataType.equals("groups"))
     813                {
     814                    return ((UserTermInfo) userInfo.get(i)).groups;
     815                }
     816                else if (dataType.equals("status"))
     817                {
     818                    return ((UserTermInfo) userInfo.get(i)).accountstatus;
     819                }
     820                else if (dataType.equals("comment"))
     821                {
     822                    return ((UserTermInfo) userInfo.get(i)).comment;
     823                }
     824                else if (dataType.equals("email"))
     825                {
     826                    return ((UserTermInfo) userInfo.get(i)).email;
     827                }
     828            }
     829        }
     830        catch (Exception ex)
     831        {
     832            ex.printStackTrace();
     833        }
     834
     835        closeDatabase();
     836        return password;
    840837    }
    841838
     
    844841        Element user_list_node = this.doc.createElement(GSXML.USER_NODE_ELEM + "List");
    845842
    846         Vector userInfo = userQueryResult.users_;
     843        Vector userInfo = userQueryResult.users;
    847844
    848845        for (int i = 0; i < userQueryResult.getSize(); i++)
    849846        {
    850847            Element user_node = this.doc.createElement(GSXML.USER_NODE_ELEM);
    851             String username = ((UserTermInfo) userInfo.get(i)).username_;
    852             String password = ((UserTermInfo) userInfo.get(i)).password_;
    853             String groups = ((UserTermInfo) userInfo.get(i)).groups_;
    854             String accountstatus = ((UserTermInfo) userInfo.get(i)).accountstatus_;
    855             String comment = ((UserTermInfo) userInfo.get(i)).comment_;
    856             user_node.setAttribute("umun", username);
    857             user_node.setAttribute("umpw", password);
    858             user_node.setAttribute("umgp", groups);
    859             user_node.setAttribute("umas", accountstatus);
    860             user_node.setAttribute("umc", comment);
     848            String username = ((UserTermInfo) userInfo.get(i)).username;
     849            String groups = ((UserTermInfo) userInfo.get(i)).groups;
     850            String accountstatus = ((UserTermInfo) userInfo.get(i)).accountstatus;
     851            String comment = ((UserTermInfo) userInfo.get(i)).comment;
     852            String email = ((UserTermInfo) userInfo.get(i)).email;
     853            user_node.setAttribute("username", username);
     854            user_node.setAttribute("groups", groups);
     855            user_node.setAttribute("status", accountstatus);
     856            user_node.setAttribute("comment", comment);
     857            user_node.setAttribute("email", email);
    861858
    862859            user_list_node.appendChild(user_node);
Note: See TracChangeset for help on using the changeset viewer.