private void handleOpenArticle( Request request, HttpServletResponse httpServletResponse, String target) throws Exception { try { int k1 = target.indexOf('/', 1); int k2 = target.indexOf('/', k1 + 1); String feedId = target.substring(k1 + 1, k2); String strSeq = target.substring(k2 + 1); int seq = Integer.parseInt(strSeq); Article article = articleDb.get(feedId, seq); LoginInfo loginInfo = userHelpers.getLoginInfo(request); // ttt2 using the link from a non-authenticated browser causes a NPE; maybe do something // better, e.g. sign up ReadArticlesColl readArticlesColl = readArticlesCollDb.get(loginInfo.userId, feedId); if (readArticlesColl == null) { readArticlesColl = new ReadArticlesColl(loginInfo.userId, feedId); } if (!readArticlesColl.isRead(seq)) { readArticlesColl.markRead(seq, Config.getConfig().maxSizeForReadArticles); readArticlesCollDb.add(readArticlesColl); } String s = URIUtil.encodePath(article.url) .replace("%3F", "?") .replace("%23", "#"); // ttt2 see how to do this right httpServletResponse.sendRedirect(s); } catch (Exception e) { WebUtils.showResult( String.format("Failed to get article for path %s. %s", target, e), "/", request, httpServletResponse); } }
// !!! IDEA reports this as unused, but it is called from JSP public static String getStyle(LoginInfo loginInfo) { StringBuilder bld = new StringBuilder(); bld.append("<style media=\"screen\" type=\"text/css\">\n\n"); if (loginInfo == null) { bld.append(Config.getConfig().defaultStyle); } else { bld.append(loginInfo.style); // ttt3 detect broken styles and return default } bld.append("</style>\n"); return bld.toString(); }
private void handleSignupPost(Request request, HttpServletResponse httpServletResponse) throws Exception { String userId = request.getParameter(PARAM_USER_ID); String userName = request.getParameter(PARAM_USER_NAME); String email = request.getParameter(PARAM_EMAIL); String stringPassword = request.getParameter(PARAM_PASSWORD); String stringPasswordConfirm = request.getParameter(PARAM_PASSWORD_CONFIRM); if (!stringPassword.equals(stringPasswordConfirm)) { WebUtils.redirectToError( "Mismatch between password and password confirmation", request, httpServletResponse); return; } SecureRandom secureRandom = new SecureRandom(); String salt = "" + secureRandom.nextLong(); byte[] password = User.computeHashedPassword(stringPassword, salt); User user = userDb.get(userId); if (user != null) { WebUtils.redirectToError( "There already exists a user with the ID " + userId, request, httpServletResponse); return; } user = new User( userId, userName, password, salt, email, new ArrayList<String>(), Config.getConfig().activateAccountsAtCreation, false); // ttt2 add confirmation by email, captcha, ... List<String> fieldErrors = user.checkFields(); if (!fieldErrors.isEmpty()) { StringBuilder bld = new StringBuilder("Invalid values when trying to create user with ID ") .append(userId) .append("<br/>"); for (String s : fieldErrors) { bld.append(s).append("<br/>"); } WebUtils.redirectToError(bld.toString(), request, httpServletResponse); return; } // ttt2 2 clients can add the same userId simultaneously userDb.add(user); httpServletResponse.sendRedirect("/"); }
private void handleAddFeedPost(Request request, HttpServletResponse httpServletResponse) throws Exception { LOG.info("adding feed"); User user = userHelpers.getUser(request); try { if (user == null) { LOG.error("User not found"); return; } String url = request.getParameter(PARAM_NEW_FEED_URL); // ttt1 add some validation; probably best try to actually get data, set the title, ... if (url == null || url.equals("")) { LOG.error("New feed not specified"); // ttt1 show some error return; } MessageDigest digest = MessageDigest.getInstance("MD5"); String feedId = PrintUtils.byteArrayAsUrlString(digest.digest(url.getBytes("UTF-8"))); feedId = feedId.substring(0, Config.getConfig().feedIdSize); Feed feed = feedDb.get(feedId); if (feed == null) { feed = new Feed(feedId, url); feedDb.add(feed); } if (user.feedIds.contains(feedId)) { LOG.error(String.format("Trying to add existing feed %s to user %s", feedId, user)); } else { user.feedIds.add(feedId); userDb.updateFeeds(user); } } finally { httpServletResponse.sendRedirect(PATH_FEED_ADMIN); } }
/** * Figure out what kind of static adapter type was specified. By default it's a 10genDEFAULT app */ protected void _setStaticAdapterType() { /* * app configuration steps could have set this already. If so, don't bother doing anything */ if (_staticAdapterType != AdapterType.UNSET) { log("Static adapter type has already been directly set to " + _staticAdapterType); return; } /* * check to see if overridden in 10gen.properties */ String override = Config.get().getProperty(INIT_ADAPTER_TYPE); if (override != null) { AdapterType t = getAdapterTypeFromString(override); if (t == null) { log( "Static adapter type specified as override [" + override + "] unknown - will use _init file specified or default"); } else { log("Static adapter type overridden by 10gen.properties or env. Value : " + override); _staticAdapterType = t; return; } } /* * if not, use the one from _init file if specified */ _staticAdapterType = AdapterType.DIRECT_10GEN; Object o = getFromInitScope(INIT_ADAPTER_TYPE); if (o == null) { log("Static adapter type not specified in _init file - using default value of DIRECT_10GEN"); return; } if (!(o instanceof JSString)) { log("Static adapter type from _init file not a string - using default value of DIRECT_10GEN"); return; } _staticAdapterType = getAdapterTypeFromString(o.toString()); if (_staticAdapterType == null) { log( "Static adapter type from _init file [" + o.toString() + "] unknown - using default value of DIRECT_10GEN"); _staticAdapterType = AdapterType.DIRECT_10GEN; return; } log("Static adapter type specified in _init file = " + _staticAdapterType); return; }
private void handleLoginPost( Request request, HttpServletResponse httpServletResponse, boolean secured) throws Exception { String userId = request.getParameter(PARAM_USER_ID); String password = request.getParameter(PARAM_PASSWORD); String rememberAccountStr = request.getParameter(PARAM_REMEMBER_ACCOUNT); boolean rememberAccount = Boolean.parseBoolean(rememberAccountStr); LoginInfo.SessionInfo sessionInfo = UserHelpers.getSessionInfo(request); logOut(sessionInfo.browserId); User user = userDb.get(userId); if (user == null) { WebUtils.redirectToError("User " + userId + " not found", request, httpServletResponse); return; } if (!user.checkPassword(password)) { WebUtils.redirectToError("Invalid password", request, httpServletResponse); return; } if (!user.active) { WebUtils.redirectToError( "Account for User " + userId + " needs to be activated", request, httpServletResponse); return; } LOG.info("Logged in user " + userId); sessionInfo.sessionId = null; if (sessionInfo.browserId == null) { sessionInfo.browserId = getRandomId(); } else { for (LoginInfo loginInfo : loginInfoDb.getLoginsForBrowser(sessionInfo.browserId)) { if (userId.equals(loginInfo.userId)) { sessionInfo.sessionId = loginInfo.sessionId; break; } } } long expireOn = System.currentTimeMillis() + Config.getConfig().loginExpireInterval; if (sessionInfo.sessionId == null) { sessionInfo.sessionId = getRandomId(); Config config = Config.getConfig(); loginInfoDb.add( new LoginInfo( sessionInfo.browserId, sessionInfo.sessionId, userId, expireOn, rememberAccount, config.defaultStyle, config.defaultItemsPerPage, config.defaultFeedDateFormat)); LOG.info(String.format("Logging in in a new session. User: %s", user)); } else { loginInfoDb.updateExpireTime(sessionInfo.browserId, sessionInfo.sessionId, expireOn); LOG.info(String.format("Logging in in an existing session. User: %s", user)); } WebUtils.saveCookies( httpServletResponse, secured, sessionInfo.browserId, sessionInfo.sessionId); httpServletResponse.sendRedirect("/"); }
/** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { Long timeIni = System.currentTimeMillis(); HttpSession sesion = request.getSession(); try { // usuario actual Usuario usuario = new Usuario(); if (sesion.getAttribute("usuario") != null) { usuario = (Usuario) sesion.getAttribute("usuario"); } // configuración de paginación String path = getServletContext().getRealPath("WEB-INF/config.xml"); int docsPagina = Config.getInitPages(usuario.getId(), path, "documents"); sesion.setAttribute("configPath", path); // privacidad de los documentos String cond = "(PRIVADO = 0 OR (PRIVADO = 1 AND ID_USUARIO = " + usuario.getId() + "))"; // filtro de búsqueda String buscar = request.getParameter("buscar"); if (buscar != null) { if (Convert.isValidDate(buscar)) { buscar = Utiles.dateToMySQLDate(Convert.parseDate(buscar), false); } cond += " AND (TITULO LIKE('%" + buscar + "%') "; cond += " OR CONTENIDO LIKE('%" + buscar + "%') "; cond += " OR ETIQUETAS LIKE('%" + buscar + "%') "; cond += " OR FECHA LIKE ('%" + buscar + "%') "; for (Usuario u : new UsuarioDAO().findAllUsuario()) { if (u.getNombre().toLowerCase().contains(buscar.toLowerCase()) || u.getApe1().toLowerCase().contains(buscar.toLowerCase()) || u.getApe2().toLowerCase().contains(buscar.toLowerCase())) { cond += " OR ID_USUARIO = " + u.getId(); } } cond += ") "; } DocumentoDAO documentoDAO = new DocumentoDAO(); sesion.setAttribute( "allDocuments", (ArrayList) documentoDAO.findAllDocumento(docsPagina, cond)); if (count == 1) { sesion.setAttribute("dataMenu", (ArrayList) documentoDAO.findAllDocumento(cond)); count++; } } catch (Exception ex) { Logger.getLogger(Login.class.getName()).log(Level.SEVERE, null, ex); } finally { Long timeEnd = System.currentTimeMillis(); System.out.println("Duración de procesado " + getServletName() + ": " + (timeEnd - timeIni)); ServletContext cont = getServletConfig().getServletContext(); RequestDispatcher reqDispatcher = cont.getRequestDispatcher("/index.jsp"); reqDispatcher.forward(request, response); } }