Search in sources :

Example 16 with WikiSecurityException

use of org.apache.wiki.auth.WikiSecurityException in project jspwiki by apache.

the class JDBCUserDatabase method getWikiNames.

/**
 * Returns all WikiNames that are stored in the UserDatabase as an array of
 * WikiPrincipal objects. If the database does not contain any profiles,
 * this method will return a zero-length array.
 *
 * @return the WikiNames
 */
public Principal[] getWikiNames() throws WikiSecurityException {
    Set<Principal> principals = new HashSet<Principal>();
    Connection conn = null;
    try {
        conn = m_ds.getConnection();
        PreparedStatement ps = conn.prepareStatement(m_findAll);
        ResultSet rs = ps.executeQuery();
        while (rs.next()) {
            String wikiName = rs.getString(m_wikiName);
            if (wikiName == null) {
                log.warn("Detected null wiki name in XMLUserDataBase. Check your user database.");
            } else {
                Principal principal = new WikiPrincipal(wikiName, WikiPrincipal.WIKI_NAME);
                principals.add(principal);
            }
        }
        ps.close();
    } catch (SQLException e) {
        throw new WikiSecurityException(e.getMessage(), e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
    return principals.toArray(new Principal[principals.size()]);
}
Also used : WikiSecurityException(org.apache.wiki.auth.WikiSecurityException) WikiPrincipal(org.apache.wiki.auth.WikiPrincipal) SQLException(java.sql.SQLException) Connection(java.sql.Connection) ResultSet(java.sql.ResultSet) PreparedStatement(java.sql.PreparedStatement) WikiPrincipal(org.apache.wiki.auth.WikiPrincipal) Principal(java.security.Principal) NamingException(javax.naming.NamingException) SQLException(java.sql.SQLException) WikiSecurityException(org.apache.wiki.auth.WikiSecurityException) NoRequiredPropertyException(org.apache.wiki.api.exceptions.NoRequiredPropertyException) NoSuchPrincipalException(org.apache.wiki.auth.NoSuchPrincipalException) IOException(java.io.IOException) HashSet(java.util.HashSet)

Example 17 with WikiSecurityException

use of org.apache.wiki.auth.WikiSecurityException in project jspwiki by apache.

the class JDBCUserDatabase method save.

/**
 * @see org.apache.wiki.auth.user.UserDatabase#save(org.apache.wiki.auth.user.UserProfile)
 */
public void save(UserProfile profile) throws WikiSecurityException {
    String initialRole = "Authenticated";
    // Figure out which prepared statement to use & execute it
    String loginName = profile.getLoginName();
    PreparedStatement ps = null;
    UserProfile existingProfile = null;
    try {
        existingProfile = findByLoginName(loginName);
    } catch (NoSuchPrincipalException e) {
    // Existing profile will be null
    }
    // Get a clean password from the passed profile.
    // Blank password is the same as null, which means we re-use the
    // existing one.
    String password = profile.getPassword();
    String existingPassword = (existingProfile == null) ? null : existingProfile.getPassword();
    if (NOTHING.equals(password)) {
        password = null;
    }
    if (password == null) {
        password = existingPassword;
    }
    // If password changed, hash it before we save
    if (!StringUtils.equals(password, existingPassword)) {
        password = getHash(password);
    }
    Connection conn = null;
    try {
        // Open the database connection
        conn = m_ds.getConnection();
        if (m_supportsCommits) {
            conn.setAutoCommit(false);
        }
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        Date modDate = new Date(ts.getTime());
        java.sql.Date lockExpiry = profile.getLockExpiry() == null ? null : new java.sql.Date(profile.getLockExpiry().getTime());
        if (existingProfile == null) {
            // User is new: insert new user record
            ps = conn.prepareStatement(m_insertProfile);
            ps.setString(1, profile.getUid());
            ps.setString(2, profile.getEmail());
            ps.setString(3, profile.getFullname());
            ps.setString(4, password);
            ps.setString(5, profile.getWikiName());
            ps.setTimestamp(6, ts);
            ps.setString(7, profile.getLoginName());
            try {
                ps.setString(8, Serializer.serializeToBase64(profile.getAttributes()));
            } catch (IOException e) {
                throw new WikiSecurityException("Could not save user profile attribute. Reason: " + e.getMessage(), e);
            }
            ps.setTimestamp(9, ts);
            ps.execute();
            ps.close();
            // Insert new role record
            ps = conn.prepareStatement(m_findRoles);
            ps.setString(1, profile.getLoginName());
            ResultSet rs = ps.executeQuery();
            int roles = 0;
            while (rs.next()) {
                roles++;
            }
            ps.close();
            if (roles == 0) {
                ps = conn.prepareStatement(m_insertRole);
                ps.setString(1, profile.getLoginName());
                ps.setString(2, initialRole);
                ps.execute();
                ps.close();
            }
            // Set the profile creation time
            profile.setCreated(modDate);
        } else {
            // User exists: modify existing record
            ps = conn.prepareStatement(m_updateProfile);
            ps.setString(1, profile.getUid());
            ps.setString(2, profile.getEmail());
            ps.setString(3, profile.getFullname());
            ps.setString(4, password);
            ps.setString(5, profile.getWikiName());
            ps.setTimestamp(6, ts);
            ps.setString(7, profile.getLoginName());
            try {
                ps.setString(8, Serializer.serializeToBase64(profile.getAttributes()));
            } catch (IOException e) {
                throw new WikiSecurityException("Could not save user profile attribute. Reason: " + e.getMessage(), e);
            }
            ps.setDate(9, lockExpiry);
            ps.setString(10, profile.getLoginName());
            ps.execute();
            ps.close();
        }
        // Set the profile mod time
        profile.setLastModified(modDate);
        // Commit and close connection
        if (m_supportsCommits) {
            conn.commit();
        }
    } catch (SQLException e) {
        throw new WikiSecurityException(e.getMessage(), e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}
Also used : SQLException(java.sql.SQLException) Connection(java.sql.Connection) PreparedStatement(java.sql.PreparedStatement) NoSuchPrincipalException(org.apache.wiki.auth.NoSuchPrincipalException) IOException(java.io.IOException) Timestamp(java.sql.Timestamp) Date(java.util.Date) NamingException(javax.naming.NamingException) SQLException(java.sql.SQLException) WikiSecurityException(org.apache.wiki.auth.WikiSecurityException) NoRequiredPropertyException(org.apache.wiki.api.exceptions.NoRequiredPropertyException) NoSuchPrincipalException(org.apache.wiki.auth.NoSuchPrincipalException) IOException(java.io.IOException) WikiSecurityException(org.apache.wiki.auth.WikiSecurityException) ResultSet(java.sql.ResultSet)

Example 18 with WikiSecurityException

use of org.apache.wiki.auth.WikiSecurityException in project jspwiki by apache.

the class JDBCUserDatabase method rename.

/**
 * @see org.apache.wiki.auth.user.UserDatabase#rename(String, String)
 */
public void rename(String loginName, String newName) throws NoSuchPrincipalException, DuplicateUserException, WikiSecurityException {
    // Get the existing user; if not found, throws NoSuchPrincipalException
    UserProfile profile = findByLoginName(loginName);
    // Get user with the proposed name; if found, it's a collision
    try {
        UserProfile otherProfile = findByLoginName(newName);
        if (otherProfile != null) {
            throw new DuplicateUserException("security.error.cannot.rename", newName);
        }
    } catch (NoSuchPrincipalException e) {
    // Good! That means it's safe to save using the new name
    }
    Connection conn = null;
    try {
        // Open the database connection
        conn = m_ds.getConnection();
        if (m_supportsCommits) {
            conn.setAutoCommit(false);
        }
        Timestamp ts = new Timestamp(System.currentTimeMillis());
        Date modDate = new Date(ts.getTime());
        // Change the login ID for the user record
        PreparedStatement ps = conn.prepareStatement(m_renameProfile);
        ps.setString(1, newName);
        ps.setTimestamp(2, ts);
        ps.setString(3, loginName);
        ps.execute();
        ps.close();
        // Change the login ID for the role records
        ps = conn.prepareStatement(m_renameRoles);
        ps.setString(1, newName);
        ps.setString(2, loginName);
        ps.execute();
        ps.close();
        // Set the profile name and mod time
        profile.setLoginName(newName);
        profile.setLastModified(modDate);
        // Commit and close connection
        if (m_supportsCommits) {
            conn.commit();
        }
    } catch (SQLException e) {
        throw new WikiSecurityException(e.getMessage(), e);
    } finally {
        try {
            if (conn != null)
                conn.close();
        } catch (Exception e) {
        }
    }
}
Also used : WikiSecurityException(org.apache.wiki.auth.WikiSecurityException) SQLException(java.sql.SQLException) Connection(java.sql.Connection) NoSuchPrincipalException(org.apache.wiki.auth.NoSuchPrincipalException) PreparedStatement(java.sql.PreparedStatement) Timestamp(java.sql.Timestamp) Date(java.util.Date) NamingException(javax.naming.NamingException) SQLException(java.sql.SQLException) WikiSecurityException(org.apache.wiki.auth.WikiSecurityException) NoRequiredPropertyException(org.apache.wiki.api.exceptions.NoRequiredPropertyException) NoSuchPrincipalException(org.apache.wiki.auth.NoSuchPrincipalException) IOException(java.io.IOException)

Example 19 with WikiSecurityException

use of org.apache.wiki.auth.WikiSecurityException in project jspwiki by apache.

the class XMLUserDatabase method saveDOM.

private void saveDOM() throws WikiSecurityException {
    if (c_dom == null) {
        log.fatal("User database doesn't exist in memory.");
    }
    File newFile = new File(c_file.getAbsolutePath() + ".new");
    try {
        BufferedWriter io = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(newFile), "UTF-8"));
        // Write the file header and document root
        io.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
        io.write("<users>\n");
        // Write each profile as a <user> node
        Element root = c_dom.getDocumentElement();
        NodeList nodes = root.getElementsByTagName(USER_TAG);
        for (int i = 0; i < nodes.getLength(); i++) {
            Element user = (Element) nodes.item(i);
            io.write("    <" + USER_TAG + " ");
            io.write(UID);
            io.write("=\"" + user.getAttribute(UID) + "\" ");
            io.write(LOGIN_NAME);
            io.write("=\"" + user.getAttribute(LOGIN_NAME) + "\" ");
            io.write(WIKI_NAME);
            io.write("=\"" + user.getAttribute(WIKI_NAME) + "\" ");
            io.write(FULL_NAME);
            io.write("=\"" + user.getAttribute(FULL_NAME) + "\" ");
            io.write(EMAIL);
            io.write("=\"" + user.getAttribute(EMAIL) + "\" ");
            io.write(PASSWORD);
            io.write("=\"" + user.getAttribute(PASSWORD) + "\" ");
            io.write(CREATED);
            io.write("=\"" + user.getAttribute(CREATED) + "\" ");
            io.write(LAST_MODIFIED);
            io.write("=\"" + user.getAttribute(LAST_MODIFIED) + "\" ");
            io.write(LOCK_EXPIRY);
            io.write("=\"" + user.getAttribute(LOCK_EXPIRY) + "\" ");
            io.write(">");
            NodeList attributes = user.getElementsByTagName(ATTRIBUTES_TAG);
            for (int j = 0; j < attributes.getLength(); j++) {
                Element attribute = (Element) attributes.item(j);
                String value = extractText(attribute);
                io.write("\n        <" + ATTRIBUTES_TAG + ">");
                io.write(value);
                io.write("</" + ATTRIBUTES_TAG + ">");
            }
            io.write("\n    </" + USER_TAG + ">\n");
        }
        io.write("</users>");
        io.close();
    } catch (IOException e) {
        throw new WikiSecurityException(e.getLocalizedMessage(), e);
    }
    // Copy new file over old version
    File backup = new File(c_file.getAbsolutePath() + ".old");
    if (backup.exists()) {
        if (!backup.delete()) {
            log.error("Could not delete old user database backup: " + backup);
        }
    }
    if (!c_file.renameTo(backup)) {
        log.error("Could not create user database backup: " + backup);
    }
    if (!newFile.renameTo(c_file)) {
        log.error("Could not save database: " + backup + " restoring backup.");
        if (!backup.renameTo(c_file)) {
            log.error("Restore failed. Check the file permissions.");
        }
        log.error("Could not save database: " + c_file + ". Check the file permissions");
    }
}
Also used : WikiSecurityException(org.apache.wiki.auth.WikiSecurityException) FileOutputStream(java.io.FileOutputStream) Element(org.w3c.dom.Element) NodeList(org.w3c.dom.NodeList) OutputStreamWriter(java.io.OutputStreamWriter) IOException(java.io.IOException) File(java.io.File) BufferedWriter(java.io.BufferedWriter)

Example 20 with WikiSecurityException

use of org.apache.wiki.auth.WikiSecurityException in project jspwiki by apache.

the class XMLUserDatabase method save.

/**
 * Saves a {@link UserProfile}to the user database, overwriting the
 * existing profile if it exists. The user name under which the profile
 * should be saved is returned by the supplied profile's
 * {@link UserProfile#getLoginName()}method.
 * @param profile the user profile to save
 * @throws WikiSecurityException if the profile cannot be saved
 */
public synchronized void save(UserProfile profile) throws WikiSecurityException {
    if (c_dom == null) {
        log.fatal("Could not save profile " + profile + " database does not exist");
        throw new IllegalStateException("FATAL: database does not exist");
    }
    checkForRefresh();
    DateFormat c_format = new SimpleDateFormat(DATE_FORMAT);
    String index = profile.getLoginName();
    NodeList users = c_dom.getElementsByTagName(USER_TAG);
    Element user = null;
    for (int i = 0; i < users.getLength(); i++) {
        Element currentUser = (Element) users.item(i);
        if (currentUser.getAttribute(LOGIN_NAME).equals(index)) {
            user = currentUser;
            break;
        }
    }
    boolean isNew = false;
    Date modDate = new Date(System.currentTimeMillis());
    if (user == null) {
        // Create new user node
        profile.setCreated(modDate);
        log.info("Creating new user " + index);
        user = c_dom.createElement(USER_TAG);
        c_dom.getDocumentElement().appendChild(user);
        setAttribute(user, CREATED, c_format.format(profile.getCreated()));
        isNew = true;
    } else {
        // To update existing user node, delete old attributes first...
        NodeList attributes = user.getElementsByTagName(ATTRIBUTES_TAG);
        for (int i = 0; i < attributes.getLength(); i++) {
            user.removeChild(attributes.item(i));
        }
    }
    setAttribute(user, UID, profile.getUid());
    setAttribute(user, LAST_MODIFIED, c_format.format(modDate));
    setAttribute(user, LOGIN_NAME, profile.getLoginName());
    setAttribute(user, FULL_NAME, profile.getFullname());
    setAttribute(user, WIKI_NAME, profile.getWikiName());
    setAttribute(user, EMAIL, profile.getEmail());
    Date lockExpiry = profile.getLockExpiry();
    setAttribute(user, LOCK_EXPIRY, lockExpiry == null ? "" : c_format.format(lockExpiry));
    // Hash and save the new password if it's different from old one
    String newPassword = profile.getPassword();
    if (newPassword != null && !newPassword.equals("")) {
        String oldPassword = user.getAttribute(PASSWORD);
        if (!oldPassword.equals(newPassword)) {
            setAttribute(user, PASSWORD, getHash(newPassword));
        }
    }
    // Save the attributes as as Base64 string
    if (profile.getAttributes().size() > 0) {
        try {
            String encodedAttributes = Serializer.serializeToBase64(profile.getAttributes());
            Element attributes = c_dom.createElement(ATTRIBUTES_TAG);
            user.appendChild(attributes);
            Text value = c_dom.createTextNode(encodedAttributes);
            attributes.appendChild(value);
        } catch (IOException e) {
            throw new WikiSecurityException("Could not save user profile attribute. Reason: " + e.getMessage(), e);
        }
    }
    // Set the profile timestamps
    if (isNew) {
        profile.setCreated(modDate);
    }
    profile.setLastModified(modDate);
    // Commit to disk
    saveDOM();
}
Also used : WikiSecurityException(org.apache.wiki.auth.WikiSecurityException) SimpleDateFormat(java.text.SimpleDateFormat) DateFormat(java.text.DateFormat) NodeList(org.w3c.dom.NodeList) Element(org.w3c.dom.Element) Text(org.w3c.dom.Text) IOException(java.io.IOException) SimpleDateFormat(java.text.SimpleDateFormat) Date(java.util.Date)

Aggregations

WikiSecurityException (org.apache.wiki.auth.WikiSecurityException)28 NoSuchPrincipalException (org.apache.wiki.auth.NoSuchPrincipalException)10 IOException (java.io.IOException)8 Principal (java.security.Principal)7 NoRequiredPropertyException (org.apache.wiki.api.exceptions.NoRequiredPropertyException)7 WikiPrincipal (org.apache.wiki.auth.WikiPrincipal)7 NamingException (javax.naming.NamingException)6 Connection (java.sql.Connection)5 PreparedStatement (java.sql.PreparedStatement)5 SQLException (java.sql.SQLException)5 Date (java.util.Date)5 UserProfile (org.apache.wiki.auth.user.UserProfile)3 Element (org.w3c.dom.Element)3 NodeList (org.w3c.dom.NodeList)3 BufferedWriter (java.io.BufferedWriter)2 File (java.io.File)2 FileOutputStream (java.io.FileOutputStream)2 OutputStreamWriter (java.io.OutputStreamWriter)2 ResultSet (java.sql.ResultSet)2 Timestamp (java.sql.Timestamp)2