package de.srsoftware.widerhall.web; import de.srsoftware.widerhall.Util; import de.srsoftware.widerhall.data.ListMember; import de.srsoftware.widerhall.data.MailingList; import de.srsoftware.widerhall.data.Post; import de.srsoftware.widerhall.data.User; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import javax.mail.MessagingException; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.nio.file.Files; import java.security.InvalidKeyException; import java.sql.SQLException; import java.util.*; import static de.srsoftware.widerhall.Constants.*; import static de.srsoftware.widerhall.Util.t; import static de.srsoftware.widerhall.data.MailingList.*; import static de.srsoftware.widerhall.data.User.PERMISSION_ADMIN; 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 String CSS = "css"; private static final Logger LOG = LoggerFactory.getLogger(Web.class); private static final String ADMIN = "admin"; private static final String EDIT_LIST = "edit_list"; private static final String INSPECT = "inspect"; private static final String LOGIN = "login"; private static final String LOGOUT = "logout"; private static final String POST = "post"; private static final String REGISTER = "register"; private static final String RELOAD = "reload"; private static final String RESET_PASSWORD = "reset-pw"; 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, boolean isGet) { var user = Util.getUser(req); if (user == null) return redirectTo(LOGIN,resp); var data = new HashMap(); data.put(USER, user.safeMap()); 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 inbox = req.getParameter(INBOX); if (inbox == null || inbox.isBlank()) inbox = DEFAULT_INBOX; data.put(INBOX, inbox); 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, inbox, smtpHost, smtpPort, smtpUser, smtpPass, null); ListMember.create(list, user, ListMember.STATE_OWNER); return redirectTo(ADMIN, resp); } catch (SQLException e) { return t("Failed to create list '{}': {}", name, e.getMessage()); } } private String archive(MailingList list, User user, HttpServletRequest req, HttpServletResponse resp) { if (list == null) return t("The mailing list you are trying to view does not exist!"); var allowed = list.hasPublicArchive() || list.mayBeAlteredBy(user); if (!allowed) return t("You are not allowed to access the archive of this list"); var data = new HashMap(); if (user != null) data.put(USER,user); data.put(LIST,list.email()); var month = req.getParameter(MONTH); if (month != null && !month.isBlank()){ data.put(MONTH,month); data.put(MODERATOR,list.mayBeAlteredBy(user)); } return loadTemplate(ARCHIVE,data,resp); } 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 listMember = ListMember.confirm(token); if (listMember != null) { listMember.sendConfirmationMail(getTemplate("confirmation_mail")); return loadTemplate(INDEX,Map.of(USER,listMember.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 = handleRequest(req, resp, true); if (error != null) resp.sendError(400,error); } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws IOException { String error = handleRequest(req, resp, false); if (error != null) resp.sendError(400,error); } public String editList(HttpServletRequest req, HttpServletResponse resp, boolean isGet) { var user = Util.getUser(req); if (user == null) return redirectTo(LOGIN,resp); var data = new HashMap(); data.put(USER,user.safeMap()); var list = Util.getMailingList(req); data.put(LIST,list.safeMap()); if (isGet) return loadTemplate(EDIT_LIST,data,resp); try { var allowed = user.hashPermission(PERMISSION_ADMIN) || ListMember.load(list,user).isOwner(); if (!allowed) 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 inbox = req.getParameter(INBOX); if (inbox == null || inbox.isBlank()) inbox = DEFAULT_INBOX; data.put(INBOX, inbox); 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(EDIT_LIST, data, resp); } if (!Util.isEmail(email)) { data.put(ERROR, t("List email ({}) is not a valid email address!", email)); return loadTemplate(EDIT_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(EDIT_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(EDIT_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(EDIT_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(EDIT_LIST, data, resp); } list.update(name,email,imapHost,imapPort,imapUser,imapPass,inbox,smtpHost,smtpPort,smtpUser,smtpPass); return loadTemplate(ADMIN,data,resp); } catch (SQLException e) { LOG.warn("Editing list {} by {} failed",list.email(),user.email(),e); return t("Editing list {} by {} failed!",list.email(),user.email()); } } private SQLException getCausingException(SQLException sqle) { Throwable cause = sqle.getCause(); while (cause instanceof SQLException){ sqle = (SQLException) cause; cause = sqle.getCause(); } return sqle; } private String handleLogin(HttpServletRequest req, HttpServletResponse resp,boolean isGet) { if (isGet) return loadTemplate(LOGIN,null,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 handleNewPassword(HttpServletRequest req, HttpServletResponse resp, boolean isGet) { var user = Util.getUser(req); if (user == null) return redirectTo(LOGIN,resp); var data = new HashMap(); data.put(USER,user.safeMap()); if (!isGet) { var pass = req.getParameter(PASSWORD); var repeat = req.getParameter(PASSWORD_REPEAT); if (pass == null || pass.isBlank()) { data.put(ERROR, "Please set a password!"); } else if (!pass.equals(repeat)) { data.put(ERROR, "Passwords do not match"); } else if (Util.simplePassword(pass)) { data.put(ERROR, "Your password is to simple"); } else { try { user.setPassword(pass); data.put(NOTES,"Your password has been updated!"); return loadTemplate(ADMIN,data,resp); } catch (SQLException e) { data.put(ERROR,t("Failed to update password in database: {}",e.getMessage())); } } } return loadTemplate(NEW_PASSWORD_FORM,data,resp); } private String handleRequest(HttpServletRequest req, HttpServletResponse resp, boolean isGet){ var path = Util.getPath(req); var user = Util.getUser(req); var data = new HashMap(); var list = Util.getMailingList(req); if (user != null) data.put(USER,user.safeMap()); if (list != null) data.put(LIST,list.minimalMap()); var interesting = !Set.of("js","jquery","css","OpenSans-Regular.woff","Bhineka.ttf").contains(path); LOG.debug("{}",interesting?"interesting":"boring"); if (user != null){ switch (path){ case ADD_LIST: return addList(req,resp,isGet); case ADMIN: return loadTemplate(path,data,resp); case EDIT_LIST: return editList(req,resp,isGet); case INSPECT: return inspect(req,resp,isGet); case NEW_PASSWORD_FORM: return handleNewPassword(req,resp,isGet); } } switch (path){ case ARCHIVE: return archive(list,user,req,resp); case CSS: case INDEX: return loadTemplate(path,data,resp); case CONFIRM: return confirm(req,resp); case LOGIN: return handleLogin(req,resp,isGet); case LOGOUT: req.getSession().invalidate(); return redirectTo(INDEX,resp); case POST: return post(req,resp); case REGISTER: return registerUser(req,resp,isGet); case RELOAD: loadTemplates(); data.put(NOTES,t("Templates have been reloaded!")); return loadTemplate(INDEX,data,resp); case RESET_PASSWORD: if (!isGet) return resetPassword(req,resp); // TODO: move following code into resetPassword method var token = req.getParameter(TOKEN); if (token != null){ try { user = User.byToken(req.getParameter(TOKEN)); if (user == null) return loadTemplate(path,Map.of(ERROR,"Failed to find user for token!"),resp); user.dropPasswordToken(); req.getSession().setAttribute("user",user); return redirectTo(NEW_PASSWORD_FORM,resp); } catch (SQLException sqle){ return loadTemplate(path,Map.of(ERROR,"Failed to add user for token!"),resp); } } var email = req.getParameter(EMAIL); return loadTemplate(path,email == null ? null : Map.of(EMAIL,email),resp); case SUBSCRIBE: if (!isGet) { return subscribe(req, resp); } // TODO: Code für GET-Request mit in subscribe-Methode verschieben if (list.isOpenFor(user)) { data.put(LIST,list.email()); return loadTemplate(path, data, resp); } return t("You are not allowed to subscribe to '{}'!",list.email()); case UNSUBSCRIBE: return unsubscribe(req,resp,isGet); } /* uninteresting paths */ switch (path){ case "js": resp.setContentType("text/javascript"); return loadTemplate(path,data,resp); case "jquery": resp.setContentType("text/javascript"); return loadFile("jquery-3.6.0.min.js",resp); case "OpenSans-Regular.woff": resp.setContentType("font/woff"); return loadFile("OpenSans-Regular.woff",resp); case "Bhineka.ttf": resp.setContentType("font/ttf"); return loadFile("Bhineka.ttf",resp); case UNSUBSCRIBE: data.put(LIST,list.email()); return loadTemplate(path,data,resp); } return redirectTo(LOGIN,resp); } private String inspect(HttpServletRequest req, HttpServletResponse resp, boolean isGet) { var user = Util.getUser(req); if (user == null) return redirectTo(LOGIN,resp); var data = new HashMap(); data.put(USER,user); var error = false; var list = Util.getMailingList(req); if (list == null) { error = true; data.put(ERROR, t("No valid mailing list provided!")); } else data.put(LIST, list.email()); if (isGet) return loadTemplate(INSPECT,data,resp); if (!error && !list.mayBeAlteredBy(user)) { error = true; data.put(ERROR,t("You are not allowed to alter settings of this list!")); } if (!error){ try { list.forwardFrom(Util.getCheckbox(req, KEY_FORWARD_FROM)) .forwardAttached(Util.getCheckbox(req, KEY_FORWARD_ATTACHED)) .hideReceivers(Util.getCheckbox(req, KEY_HIDE_RECEIVERS)) .replyToList(Util.getCheckbox(req, KEY_REPLY_TO_LIST)) .modsMayNominateMods(Util.getCheckbox(req, KEY_MODS_CAN_EDIT_MODS)) .openForGuests(Util.getCheckbox(req,KEY_OPEN_FOR_GUESTS)) .openForSubscribers(Util.getCheckbox(req,KEY_OPEN_FOR_SUBSCRIBERS)) .archive(Util.getCheckbox(req,KEY_ARCHIVE)) .deleteMessages(Util.getCheckbox(req,KEY_DELETE_MESSAGES),req.getParameter(HOLD_TIME)); data.put(NOTES,t("Sucessfully updated MailingList!")); } catch (SQLException e){ LOG.warn("Failed to update MailingList:",e); data.put(ERROR,t("Failed to update MailingList!")); } } return loadTemplate(INSPECT,data,resp); } private String post(HttpServletRequest req, HttpServletResponse resp) { var id = req.getParameter(ID); if (id == null) return t("Could not find email with id!"); try { var post = Post.load(id); var map = new HashMap(); map.putAll(post.safeMap()); String content = Files.readString(post.file().toPath()); map.put("text",Util.dropEmail(content)); return loadTemplate("post",map,resp); } catch (SQLException | IOException e) { LOG.debug("Failed to load post from file!",e); return t("Failed to load post from file!"); } } 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, boolean isGet) { if (isGet) return loadTemplate(REGISTER,null,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,t("Fill all fields, please!"),NAME,name,EMAIL,email),resp); if (!pass.equals(pass_repeat)) return loadTemplate(REGISTER,Map.of(ERROR,t("Passwords do not match!"),NAME,name,EMAIL,email),resp); if (Util.simplePassword(pass)) return loadTemplate(REGISTER,Map.of(ERROR,t("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(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 resetPassword(HttpServletRequest req, HttpServletResponse resp) { var email = req.getParameter("email"); if (email == null) return loadTemplate("login", Map.of("error",t("Missing email address!")), resp); if (!Util.isEmail(email)) return loadTemplate("login", Map.of("error",t("'{}' is not a valid email address!",email)), resp); try { var user = User.load(email); if (user != null) { MailingList list = ListMember.listsOf(user).stream().map(ListMember::list).filter(ml -> ml.hasState(STATE_ENABLED)).findAny().orElse(null); if (list == null) list = MailingList.listActive().stream().findAny().orElse(null); if (list == null) throw new NullPointerException("no active List found!"); String token = user.generateToken(); var host = Arrays.stream(req.getRequestURL().toString().split("/")).filter(s -> !s.isEmpty() && !s.startsWith("http")).findFirst().orElse("unknwon host"); var link = req.getRequestURL().toString()+"?token="+token; var subject = t("Reset your password at {}",host); var text = t("Somebody asked to reset your account password at {}.\n\nIf that was you, please open the following link in your web browser:\n\n{}\n\nIf you did not expect this email, please ignore it.",host,link); list.sendPasswordReset(email,subject,text); return loadTemplate("reset_link_sent",null,resp); } } catch (Exception e){ return loadTemplate(Util.getPath(req),Map.of(EMAIL,email,ERROR,t("Failed to send reset email:")+" "+e.getMessage()),resp); } return null; } private String subscribe(HttpServletRequest req, HttpServletResponse resp) { var name = req.getParameter(NAME); var email = req.getParameter(EMAIL); var pass = req.getParameter(PASSWORD); var list = Util.getMailingList(req); var data = new HashMap(); data.put(NAME,name); data.put(EMAIL,email); if (list != null) data.put(LIST,list.email()); var skipConfirmation = false; 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); req.getSession().setAttribute("user",user); 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,getTemplate("subscribe_mail")); 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, boolean isGet) { var data = new HashMap(); var user = Util.getUser(req); var email = req.getParameter(EMAIL); var list = Util.getMailingList(req); data.put(EMAIL,email); if (user != null) data.put(USER,user.safeMap()); if (list == null){ data.put(ERROR,t("No list provided by form data!")); return loadTemplate(UNSUBSCRIBE,data,resp); } else data.put(LIST,list.email()); if (isGet) return loadTemplate(UNSUBSCRIBE,data,resp); if (user == null) { if (email == null || email.isBlank()) { data.put(ERROR, t("Email is required for list un-subscription!")); return loadTemplate(UNSUBSCRIBE, data, resp); } var pass = req.getParameter(PASSWORD); 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,t("Invalid email/password combination!")); return loadTemplate(UNSUBSCRIBE,data,resp); } } ListMember member = null; try { member = ListMember.load(list,user); } catch (SQLException e) { LOG.debug("Failed to load list member for {}/{}",user.email(),list.email(),e); data.put(ERROR, t("Failed to load list member for {}/{}",user.email(),list.email())); return loadTemplate(UNSUBSCRIBE,data,resp); } if (member == null){ data.put(ERROR, t("{} is no member of {}",user.email(),list.email())); return loadTemplate(UNSUBSCRIBE,data,resp); } // if we get here, we should have a valid member object try { member.unsubscribe(); 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); } } }