package de.srsoftware.widerhall.web; import de.srsoftware.widerhall.Configuration; import de.srsoftware.widerhall.Constants; import de.srsoftware.widerhall.Util; import de.srsoftware.widerhall.data.ListMember; import de.srsoftware.widerhall.data.MailingList; import de.srsoftware.widerhall.data.User; import org.antlr.runtime.MismatchedTokenException; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.stringtemplate.v4.STGroup; import org.stringtemplate.v4.STRawGroupDir; import javax.mail.MessagingException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.File; import java.io.IOException; import java.nio.file.Files; import java.security.InvalidKeyException; import java.sql.SQLException; import java.util.HashMap; import java.util.Map; import static de.srsoftware.widerhall.Constants.*; import static de.srsoftware.widerhall.Util.t; public class Web extends TemplateServlet { public static final String WEB_ROOT = "/web"; private static final String ADD_LIST = "add_list"; private static final String CONFIRM = "confirm"; private static final Logger LOG = LoggerFactory.getLogger(Web.class); private static final String ADMIN = "admin"; private static final String LOGIN = "login"; private static final String LOGOUT = "logout"; private static final String REGISTER = "register"; private static final String RELOAD = "reload"; private static final String SUBSCRIBE = "subscribe"; private static final String UNSUBSCRIBE = "unsubscribe"; private static final String IMAP_HOST = "imap_host"; private static final String IMAP_PORT = "imap_port"; private static final String IMAP_USER = "imap_user"; private static final String IMAP_PASS = "imap_pass"; private static final String SMTP_HOST = "smtp_host"; private static final String SMTP_PORT = "smtp_port"; private static final String SMTP_USER = "smtp_user"; private static final String SMTP_PASS = "smtp_pass"; private static final int PRIMARY_KEY_CONSTRAINT = 19; private String addList(HttpServletRequest req, HttpServletResponse resp) { var o = req.getSession().getAttribute(USER); if (!(o instanceof User user)) { return redirectTo(LOGIN,resp); } var data = new HashMap(); data.put(USER, user); if (!user.hashPermission(User.PERMISSION_CREATE_LISTS)){ data.put(ERROR,t("You are not allowed to create new mailing lists!")); return loadTemplate(ADMIN,data,resp); } var name = req.getParameter(NAME); data.put(NAME, name); var email = req.getParameter(EMAIL); data.put(EMAIL, email); var imapHost = req.getParameter(IMAP_HOST); data.put(IMAP_HOST, imapHost); var imapUser = req.getParameter(IMAP_USER); data.put(IMAP_USER, imapUser); var imapPass = req.getParameter(IMAP_PASS); var smtpHost = req.getParameter(SMTP_HOST); data.put(SMTP_HOST, smtpHost); var smtpUser = req.getParameter(SMTP_USER); data.put(SMTP_USER, smtpUser); var smtpPass = req.getParameter(SMTP_PASS); Integer imapPort = 993; data.put(IMAP_PORT, imapPort); Integer smtpPort = 465; data.put(SMTP_PORT, smtpPort); if (name == null || name.isBlank() || email == null || email.isBlank()) { data.put(ERROR, "List name and address are required!"); return loadTemplate(ADD_LIST, data, resp); } if (!Util.isEmail(email)) { data.put(ERROR, t("List email ({}) is not a valid email address!", email)); return loadTemplate(ADD_LIST, data, resp); } if (imapHost == null || imapHost.isBlank() || imapUser == null || imapUser.isBlank() || imapPass == null || imapPass.isBlank()) { data.put(ERROR, "IMAP credentials are required!"); return loadTemplate(ADD_LIST, data, resp); } try { imapPort = Integer.parseInt(req.getParameter(IMAP_PORT)); data.put(IMAP_PORT, imapPort); } catch (NumberFormatException nfe) { data.put(ERROR, t("'{}' is not a proper port number!", req.getParameter(IMAP_PORT))); return loadTemplate(ADD_LIST, data, resp); } if (smtpHost == null || smtpHost.isBlank() || smtpUser == null || smtpUser.isBlank() || smtpPass == null || smtpPass.isBlank()) { data.put(ERROR, "SMTP credentials are required!"); return loadTemplate(ADD_LIST, data, resp); } try { smtpPort = Integer.parseInt(req.getParameter(SMTP_PORT)); data.put(SMTP_PORT, smtpPort); } catch (NumberFormatException nfe) { data.put(ERROR, t("'{}' is not a proper port number!", req.getParameter(SMTP_PORT))); return loadTemplate(ADD_LIST, data, resp); } try { var list = MailingList.create(email, name, imapHost, imapPort, imapUser, imapPass, smtpHost, smtpPort, smtpUser, smtpPass); ListMember.create(list, user, ListMember.STATE_OWNER); return redirectTo(INDEX, resp); } catch (SQLException e) { return t("Failed to create list '{}': {}", name, e.getMessage()); } } private String confirm(HttpServletRequest req, HttpServletResponse resp) { try { var token = req.getParameter(TOKEN); if (token== null || token.isBlank()) return t("Invalid or missing token!"); var user = ListMember.confirm(token); if (user != null) return loadTemplate(INDEX,Map.of(USER,user.safeMap(),NOTES,"Confirmed list subscription!"),resp); return t("Unknown user or token"); } catch (Exception e) { LOG.debug("Failed to confirm list membership:",e); return t("Confirmation of list membership failed!"); } } @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException { String error = handleGet(req, resp); if (error != null) resp.sendError(400,error); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String error = handlePost(req, resp); if (error != null) resp.sendError(400,error); } private SQLException getCausingException(SQLException sqle) { Throwable cause = sqle.getCause(); while (cause instanceof SQLException){ sqle = (SQLException) cause; cause = sqle.getCause(); } return sqle; } private User getSessionUser(HttpServletRequest req) { return req.getSession().getAttribute(USER) instanceof User user ? user : null; } private String handleGet(HttpServletRequest req, HttpServletResponse resp) { var path = req.getPathInfo(); if (path == null) return redirectTo(INDEX,resp); var o = req.getSession().getAttribute("user"); User user = o instanceof User ? (User) o : null; var data = new HashMap(); if (user != null) data.put(USER,user.safeMap()); path = path.equals("/") ? INDEX : path.substring(1); String notes = null; var listEmail = req.getParameter(LIST); var list = MailingList.load(listEmail); if (list != null) data.put(LIST,list.minimalMap()); switch (path){ case CONFIRM: return confirm(req,resp); case RELOAD: loadTemplates(); data.put(NOTES,t("Templates have been reloaded")); path = INDEX; case "css": case INDEX: case UNSUBSCRIBE: return loadTemplate(path,data,resp); case SUBSCRIBE: if (list.isOpenFor(user)) { data.put(LIST,listEmail); return loadTemplate(path, data, resp); } return t("You are not allowed to subscribe to '{}'!",list.email()); case "js": resp.setContentType("text/javascript"); return loadTemplate(path,data,resp); case LOGIN: try { if (User.noUsers()) return loadTemplate(REGISTER, Map.of(NOTES,t("User database is empty. Create admin user first:")), resp); return loadTemplate(path,null,resp); } catch (SQLException e) { return "Error reading user database!"; } case LOGOUT: req.getSession().invalidate(); return redirectTo(INDEX,resp); case "jquery": resp.setContentType("text/javascript"); return loadFile("jquery-3.6.0.min.js",resp); } if (user != null){ if (list != null) data.put(LIST,req.getParameter(LIST)); //data.put(NOTES,notes); return loadTemplate(path,data,resp); } return redirectTo(LOGIN,resp); } private String handleLogin(HttpServletRequest req, HttpServletResponse resp) { var email = req.getParameter("email"); var pass = req.getParameter("pass"); if (email == null || pass == null) return loadTemplate("login", Map.of("error",t("Missing username or password!")), resp); if (!Util.isEmail(email)) return loadTemplate("login", Map.of("error",t("'{}' is not a valid email address!",email)), resp); try { var user = User.loadUser(email,pass); req.getSession().setAttribute("user",user); // loading user successfull: goto index resp.sendRedirect(String.join("/",WEB_ROOT,"admin")); } catch (Exception e) { try { LOG.warn("Static.handleLogin failed:",e); Thread.sleep(10000); } finally { return loadTemplate("login", Map.of(ERROR,t("Invalid username/password"),EMAIL,email), resp); } } return null; } private String handlePost(HttpServletRequest req, HttpServletResponse resp) { var path = req.getPathInfo(); path = path == null ? INDEX : path.substring(1); switch (path){ case ADD_LIST: return addList(req,resp); case LOGIN: return handleLogin(req,resp); case REGISTER: return registerUser(req,resp); case SUBSCRIBE: return subscribe(req,resp); case UNSUBSCRIBE: return unsubscribe(req,resp); } return t("No handler for path {}!",path); } private String redirectTo(String page, HttpServletResponse resp) { try { resp.sendRedirect(String.join("/",WEB_ROOT,page)); return null; } catch (IOException e) { return t("Was not able to redirect to {} page: {}", page, e.getMessage()); } } private String registerUser(HttpServletRequest req, HttpServletResponse resp) { var email = req.getParameter("email"); var pass = req.getParameter("pass"); var pass_repeat = req.getParameter("pass_repeat"); var name = req.getParameter("name"); if (email == null || email.isBlank() || name == null || name.isBlank() || pass == null || pass.isBlank() || pass_repeat == null || pass_repeat.isBlank()) return loadTemplate(REGISTER,Map.of(ERROR,"Fill all fields, please!",NAME,name,EMAIL,email),resp); if (!pass.equals(pass_repeat)) return loadTemplate(REGISTER,Map.of(ERROR,"Passwords do not match!",NAME,name,EMAIL,email),resp); if (Util.simplePassword(pass)) return loadTemplate(REGISTER,Map.of(ERROR,"Password to short or to simple!",NAME,name,EMAIL,email),resp); var firstUser = false; try { firstUser = User.noUsers(); } catch (SQLException e) { return t("Failed to access user database: {}",e.getMessage()); } try { var user = User.create(email, name, pass); if (firstUser) user.addPermission(User.PERMISSION_ADMIN|User.PERMISSION_CREATE_LISTS); req.getSession().setAttribute("user",user); return redirectTo(INDEX,resp); } catch (SQLException e) { LOG.warn("Failed to create new user:",e); return t("Failed to create new user: {}",e.getMessage()); } } private String subscribe(HttpServletRequest req, HttpServletResponse resp) { var name = req.getParameter(NAME); var email = req.getParameter(EMAIL); var pass = req.getParameter(PASSWORD); var listEmail = req.getParameter(LIST); var data = new HashMap(); data.put(NAME,name); data.put(EMAIL,email); data.put(LIST,listEmail); var skipConfirmation = false; var list = MailingList.load(listEmail); if (list == null){ data.put(ERROR,"No list provided by form data!"); return loadTemplate(SUBSCRIBE,data,resp); } if (name == null || name.isBlank() || email == null || email.isBlank()){ data.put(ERROR,"Name and email are required fields for list subscription!"); return loadTemplate(SUBSCRIBE,data,resp); } if (pass != null && pass.isBlank()) pass = null; User user = null; try { user = User.create(email,name,pass); } catch (SQLException sqle) { var cause = getCausingException(sqle); int code = cause.getErrorCode(); if (code == PRIMARY_KEY_CONSTRAINT) try {// user already exists user = User.loadUser(email,pass); skipConfirmation = pass != null; // subscription with email address already known to database // success → subscribe } catch (InvalidKeyException | SQLException e) { // invalid credentials data.put(ERROR,t("'{}' already in database, but with different password!",email)); return loadTemplate(SUBSCRIBE,data,resp); } } data.put(USER,user.safeMap()); if (!list.isOpenFor(user)){ data.put(ERROR,t("You are not allowed to join {}!",list.email())); return loadTemplate(SUBSCRIBE,data,resp); } try { list.requestSubscription(user,skipConfirmation); if (skipConfirmation) { data.put(NOTES, t("Successfully subscribed '{}' to '{}'.", user.email(), list.email())); } else { data.put(NOTES, t("Sent confirmation mail to '{}.", user.email())); } return loadTemplate(INDEX,data,resp); } catch (SQLException sqle) { LOG.debug("List subscription failed: ",sqle); var cause = getCausingException(sqle); int code = cause.getErrorCode(); if (code == PRIMARY_KEY_CONSTRAINT) {// user already exists data.put(ERROR,t("You already are member of this list!",sqle.getMessage())); } else data.put(ERROR,t("Subscription failed: {}",sqle.getMessage())); return loadTemplate(SUBSCRIBE,data,resp); } catch (MessagingException e) { LOG.warn("Failed to send request confirmation email:",e); data.put(ERROR,t("Failed to send request confirmation email: {}",e.getMessage())); return loadTemplate(SUBSCRIBE,data,resp); } } private String unsubscribe(HttpServletRequest req, HttpServletResponse resp) { var data = new HashMap(); var user = getSessionUser(req); var email = req.getParameter(EMAIL); var pass = req.getParameter(PASSWORD); var listEmail = req.getParameter(LIST); data.put(EMAIL,email); data.put(LIST,listEmail); var list = MailingList.load(listEmail); if (user != null) data.put(USER,user.safeMap()); if (list == null){ data.put(ERROR,"No list provided by form data!"); return loadTemplate(UNSUBSCRIBE,data,resp); } if (user == null) { if (email == null || email.isBlank()) { data.put(ERROR, "Email is required for list un-subscription!"); return loadTemplate(UNSUBSCRIBE, data, resp); } if (pass != null && pass.isBlank()) pass = null; try { user = User.loadUser(email,pass); req.getSession().setAttribute(USER,user); data.put(USER,user.safeMap()); } catch (InvalidKeyException | SQLException e) { data.put(ERROR,"Invalid email/password combination!"); return loadTemplate(UNSUBSCRIBE,data,resp); } } // if we get here, we should have a valid user try { ListMember.unsubscribe(list,user); data.put(NOTES,t("Sucessfully un-subscribed from '{}'.",list.email())); return loadTemplate(INDEX,data,resp); } catch (SQLException e) { LOG.warn("Problem during unscubsription of {} from {}:",user.email(),list.email(),e); data.put(ERROR,"Failed to unsubscribe!"); return loadTemplate(UNSUBSCRIBE,data,resp); } } }