Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions teamengine-core/src/main/java/com/occamlab/te/util/XMLUtils.java
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,26 @@
*/
package com.occamlab.te.util;

import java.io.File;
import java.io.FileOutputStream;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.xerces.impl.Constants;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.bootstrap.DOMImplementationRegistry;
import org.w3c.dom.ls.DOMImplementationLS;
import org.w3c.dom.ls.LSOutput;
import org.w3c.dom.ls.LSSerializer;

/**
* @author lbermudez
Expand Down Expand Up @@ -72,4 +83,66 @@ public static NodeList getAllNodes(Document doc, String xPathExpression) {
return null;
}

/**
* This method is used to parse xml document and will return document object.
* @param xmlFile Input should XML file with File object.
* @return doc Return document object.
*/
public static Document parseDocument(File xmlFile) {
try {
DocumentBuilderFactory dbf = DocumentBuilderFactory.newInstance();
dbf.setNamespaceAware(true);
dbf.setExpandEntityReferences(false);
DocumentBuilder db = dbf.newDocumentBuilder();
Document doc = db.parse(xmlFile);
return doc;
}
catch (Exception e) {
throw new RuntimeException("Failed to parse xml file: " + xmlFile + " Error: " + e.getMessage());
}
}

/**
* This method is used to write the DOM object to XML file.
* @param xmlFile
* @return
*/
public static void transformDocument(Document doc, File xmlFile) {
try {
DOMImplementationRegistry domRegistry = DOMImplementationRegistry.newInstance();
DOMImplementationLS lsFactory = (DOMImplementationLS) domRegistry.getDOMImplementation("LS 3.0");

LSSerializer serializer = lsFactory.createLSSerializer();
serializer.getDomConfig().setParameter(Constants.DOM_XMLDECL, Boolean.FALSE);
serializer.getDomConfig().setParameter(Constants.DOM_FORMAT_PRETTY_PRINT, Boolean.TRUE);
LSOutput output = lsFactory.createLSOutput();
output.setEncoding("UTF-8");

FileOutputStream os = new FileOutputStream(xmlFile, false);
output.setByteStream(os);
serializer.write(doc, output);
os.close();
}
catch (Exception e) {
throw new RuntimeException("Failed to update user details. " + e.getMessage());
}
}

/**
* This method removes the element from the document.
* @param doc
* @param element Object of root element
* @param elementName The name of element to remove.
* @return
*/
public static Document removeElement(Document doc, Element element, String elementName) {
NodeList elementList = element.getElementsByTagName(elementName);
if (elementList.getLength() != 0) {
Element elementToRemove = (Element) doc.getElementsByTagName(elementName).item(0);
Node parent = elementToRemove.getParentNode();
parent.removeChild(elementToRemove);
}
return doc;
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ public class PBKDF2Realm extends RealmBase {

private DocumentBuilder DB = null;

private final HashMap<String, Principal> principals = new HashMap<>();
private HashMap<String, Principal> principals = UserGenericPrincipal.getInstance().getPrincipals();

private String password;

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package com.occamlab.te.realm;

import java.security.Principal;
import java.util.HashMap;
import java.util.logging.Logger;

public class UserGenericPrincipal {

private static final Logger logger = Logger.getLogger(UserGenericPrincipal.class.getPackage().getName());

private HashMap<String, Principal> principals = new HashMap<String, Principal>();

private static volatile UserGenericPrincipal userPrincipal = null;

public static UserGenericPrincipal getInstance() {

if (null == userPrincipal) {
synchronized (UserGenericPrincipal.class) {
// check again, because the thread might have been preempted
// just after the outer if was processed but before the
// synchronized statement was executed
if (userPrincipal == null) {
userPrincipal = new UserGenericPrincipal();
}
}
}
return userPrincipal;
}

public Principal removePrincipal(String username) {

synchronized (principals) {
return (Principal) principals.remove(username);
}

}

public HashMap<String, Principal> getPrincipals() {
return principals;
}

}
78 changes: 78 additions & 0 deletions teamengine-web/RegistrationHandlerServlet.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,78 @@
/****************************************************************************

The Original Code is TEAM Engine.

The Initial Developer of the Original Code is Northrop Grumman Corporation
jointly with The National Technology Alliance. Portions created by
Northrop Grumman Corporation are Copyright (C) 2005-2006, Northrop
Grumman Corporation. All Rights Reserved.

Contributor(s): No additional contributors to date

****************************************************************************/
package com.occamlab.te.web;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.occamlab.te.realm.PasswordStorage;

import java.io.File;
import java.io.FileOutputStream;
import java.io.PrintStream;

/**
* Handles requests to register new users.
*
*/
public class RegistrationHandlerServlet extends HttpServlet {

private static final long serialVersionUID = 7428127065308163495L;

Config conf;

public void init() throws ServletException {
conf = new Config();
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {
try {
String username = request.getParameter("username");
String password = request.getParameter("password");
String hashedPassword = PasswordStorage.createHash(password);
String email = request.getParameter("email");
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
String organization = request.getParameter("organization");
File userDir = new File(conf.getUsersDir(), username);
if (userDir.exists()) {
String url = "register.jsp?error=duplicate&username=" + username;
if (email != null) {
url += "&email=" + email;
}
response.sendRedirect(url);
} else {
userDir.mkdirs();
File xmlfile = new File(userDir, "user.xml");
PrintStream out = new PrintStream(new FileOutputStream(xmlfile));
out.println("<user>");
out.println(" <name>" + username + "</name>");
out.println(" <roles>");
out.println(" <name>user</name>");
out.println(" </roles>");
out.println(" <password>" + hashedPassword + "</password>");
out.println(" <email>" + email + "</email>");
out.println(" <firstName>" + firstName + "</firstName>");
out.println(" <lastName>" + lastName + "</lastName>");
out.println(" <organization>" + organization + "</organization>");
out.println("</user>");
out.close();
response.sendRedirect("registered.jsp");
}
} catch (Exception e) {
throw new ServletException(e);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
package com.occamlab.te.web;

import java.io.File;
import java.security.Principal;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;

import com.occamlab.te.config.Config;
import com.occamlab.te.realm.PasswordStorage;
import com.occamlab.te.realm.UserGenericPrincipal;
import com.occamlab.te.util.XMLUtils;

import jakarta.servlet.ServletException;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

/**
* Handles requests to change password.
*
*/
public class ChangePasswordHandler extends HttpServlet {

Config conf;

public void init() throws ServletException {
conf = new Config();
}

public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException {

try {
String oldPass = request.getParameter("oldPass");
String username = request.getParameter("username");
String newPassword = request.getParameter("newPassword");

File userDir = new File(conf.getUsersDir(), username);
if (!userDir.exists()) {
String url = "changePassword.jsp?error=userNotExists&username=" + username;
response.sendRedirect(url);
}
else {
File xmlfile = new File(userDir, "user.xml");
Document doc = XMLUtils.parseDocument(xmlfile);
Element userDetails = (Element) (doc.getElementsByTagName("user").item(0));

NodeList oldPwdList = userDetails.getElementsByTagName("password");
String storedOldPassword = null;
if (oldPwdList.getLength() > 0) {
Element oldePwdElement = (Element) oldPwdList.item(0);
storedOldPassword = oldePwdElement.getTextContent();
}

Boolean isValid = PasswordStorage.verifyPassword(oldPass, storedOldPassword);
if (isValid) {
doc = XMLUtils.removeElement(doc, userDetails, "password");
Element pwdElement = doc.createElement("password");
pwdElement.setTextContent(PasswordStorage.createHash(newPassword));
userDetails.appendChild(pwdElement);
XMLUtils.transformDocument(doc, new File(userDir, "user.xml"));
Principal userPrincipal = UserGenericPrincipal.getInstance().removePrincipal(username);
if (userPrincipal == null) {
throw new RuntimeException("Failed update old credentials");
}
request.getSession().invalidate();
response.sendRedirect(request.getContextPath());
}
else {
String url = "changePassword.jsp?error=invalidOldPwd";
response.sendRedirect(url);
}
}
}
catch (Exception e) {
throw new ServletException(e);
}
}

}
59 changes: 59 additions & 0 deletions teamengine-web/src/main/java/com/occamlab/te/web/EmailUtility.java
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
package com.occamlab.te.web;

import java.util.Date;
import java.util.Properties;
import java.util.Random;

import javax.mail.Authenticator;
import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.PasswordAuthentication;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.AddressException;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

public class EmailUtility {

public static void sendEmail(String host, String portNo, final String userName, final String pwd, String toAddress,
String subject, String message) throws AddressException, MessagingException {

Properties properties = new Properties();
properties.put("mail.smtp.host", host);
properties.put("mail.smtp.port", portNo);
properties.put("mail.smtp.auth", "true");
properties.put("mail.smtp.starttls.enable", "true");
// see https://bugs.openjdk.org/browse/JDK-8202343
properties.put("mail.smtp.ssl.protocols", "TLSv1.2");

Authenticator auth = new Authenticator() {
public PasswordAuthentication getPasswordAuthentication() {
return new PasswordAuthentication(userName, pwd);
}
};

Session session = Session.getInstance(properties, auth);
Message msg = new MimeMessage(session);
try {
msg.setFrom(new InternetAddress(userName));
InternetAddress[] toAddresses = { new InternetAddress(toAddress) };
msg.setRecipients(Message.RecipientType.TO, toAddresses);
msg.setSubject(subject);
msg.setSentDate(new Date());
msg.setContent(message, "text/html; charset=utf-8");

Transport.send(msg);
}
catch (Exception e) {
throw new RuntimeException("Failed send mail : " + e.getMessage());
}
}

public static String getRandomNumberString() {
Random randomNo = new Random();
int number = randomNo.nextInt(999999);
return String.format("%06d", number);
}

}
Loading