List of usage examples for javax.servlet.http Cookie Cookie
public Cookie(String name, String value)
From source file:com.persistent.cloudninja.controller.AuthFilterUtils.java
/** * // w w w. j a v a 2s . c o m * @param cloudNinjaUser * @param cookieName * @return */ public static Cookie createNewCookieForACSAuthenticatedUser(CloudNinjaUser cloudNinjaUser, String cookieName) { Collection<GrantedAuthority> authorities = cloudNinjaUser.getUser().getAuthorities(); if (authorities != null) { GrantedAuthority[] grantedAuthorities = new GrantedAuthority[authorities.size()]; authorities.toArray(grantedAuthorities); } StringBuffer sb = new StringBuffer(5); sb.append(CloudNinjaConstants.COOKIE_TENANTID_PREFIX) .append(CloudNinjaConstants.COOKIE_FIELD_AND_VALUE_SEPARATOR).append(cloudNinjaUser.getTenantId()) .append(CloudNinjaConstants.COOKIE_FIELDS_SEPARATOR); sb.append(CloudNinjaConstants.COOKIE_USERNAME_PREFIX) .append(CloudNinjaConstants.COOKIE_FIELD_AND_VALUE_SEPARATOR) .append(cloudNinjaUser.getUser().getUsername()).append(CloudNinjaConstants.COOKIE_FIELDS_SEPARATOR); sb.append(CloudNinjaConstants.COOKIE_AUTHORITIES_PREFIX) .append(CloudNinjaConstants.COOKIE_FIELD_AND_VALUE_SEPARATOR).append(authorities.toString()) .append(CloudNinjaConstants.COOKIE_FIELDS_SEPARATOR); sb.append(CloudNinjaConstants.COOKIE_AUTH_SESSION_START_PREFIX) .append(CloudNinjaConstants.COOKIE_FIELD_AND_VALUE_SEPARATOR) .append(cloudNinjaUser.getAuthenticatedSessionStartTime().getTime()) .append(CloudNinjaConstants.COOKIE_FIELDS_SEPARATOR); sb.append(CloudNinjaConstants.COOKIE_AUTH_SESSION_END_PREFIX) .append(CloudNinjaConstants.COOKIE_FIELD_AND_VALUE_SEPARATOR) .append(cloudNinjaUser.getAuthenticatedSessionExpiryTime().getTime()) .append(CloudNinjaConstants.COOKIE_FIELDS_SEPARATOR); String newCookieValue = sb.toString(); Cookie newCookie = new Cookie(cookieName, newCookieValue); newCookie.setPath("/"); return newCookie; }
From source file:blog.BlogController.java
private void initializeRoutes() throws IOException { // this is the blog home page get(new FreemarkerBasedRoute("/", "blog_template.ftl") { @Override/*from w w w. j a v a 2s. co m*/ public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); List<Document> posts = blogPostDAO.findByDateDescending(10); SimpleHash root = new SimpleHash(); root.put("myposts", posts); if (username != null) { root.put("username", username); } template.process(root, writer); } }); // used to display actual blog post detail page get(new FreemarkerBasedRoute("/post/:permalink", "entry_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String permalink = request.params(":permalink"); System.out.println("/post: get " + permalink); Document post = blogPostDAO.findByPermalink(permalink); if (post == null) { response.redirect("/post_not_found"); } else { // empty comment to hold new comment in form at bottom of blog entry detail page SimpleHash newComment = new SimpleHash(); newComment.put("name", ""); newComment.put("email", ""); newComment.put("body", ""); SimpleHash root = new SimpleHash(); root.put("post", post); root.put("comments", newComment); template.process(root, writer); } } }); // handle the signup post post(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String email = request.queryParams("email"); String username = request.queryParams("username"); String password = request.queryParams("password"); String verify = request.queryParams("verify"); HashMap<String, String> root = new HashMap<String, String>(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("email", StringEscapeUtils.escapeHtml4(email)); if (validateSignup(username, password, verify, email, root)) { // good user System.out.println("Signup: Creating user with: " + username + " " + password); if (!userDAO.addUser(username, password, email)) { // duplicate user root.put("username_error", "Username already in use, Please choose another"); template.process(root, writer); } else { // good user, let's start a session String sessionID = sessionDAO.startSession(username); System.out.println("Session ID is" + sessionID); response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/welcome"); } } else { // bad signup System.out.println("User Registration did not validate"); template.process(root, writer); } } }); // present signup form for blog get(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); // initialize values for the form. root.put("username", ""); root.put("password", ""); root.put("email", ""); root.put("password_error", ""); root.put("username_error", ""); root.put("email_error", ""); root.put("verify_error", ""); template.process(root, writer); } }); get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String cookie = getSessionCookie(request); String username = sessionDAO.findUserNameBySessionId(cookie); if (username == null) { System.out.println("welcome() can't identify the user, redirecting to signup"); response.redirect("/signup"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // will present the form used to process new blog posts get(new FreemarkerBasedRoute("/newpost", "newpost_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { // get cookie String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); if (username == null) { // looks like a bad request. user is not logged in response.redirect("/login"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // handle the new post submission post(new FreemarkerBasedRoute("/newpost", "newpost_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String title = StringEscapeUtils.escapeHtml4(request.queryParams("subject")); String post = StringEscapeUtils.escapeHtml4(request.queryParams("body")); String tags = StringEscapeUtils.escapeHtml4(request.queryParams("tags")); String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); if (username == null) { response.redirect("/login"); // only logged in users can post to blog } else if (title.equals("") || post.equals("")) { // redisplay page with errors HashMap<String, String> root = new HashMap<String, String>(); root.put("errors", "post must contain a title and blog entry."); root.put("subject", title); root.put("username", username); root.put("tags", tags); root.put("body", post); template.process(root, writer); } else { // extract tags ArrayList<String> tagsArray = extractTags(tags); // substitute some <p> for the paragraph breaks post = post.replaceAll("\\r?\\n", "<p>"); String permalink = blogPostDAO.addPost(title, post, tagsArray, username); // now redirect to the blog permalink response.redirect("/post/" + permalink); } } }); get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String cookie = getSessionCookie(request); String username = sessionDAO.findUserNameBySessionId(cookie); if (username == null) { System.out.println("welcome() can't identify the user, redirecting to signup"); response.redirect("/signup"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // process a new comment post(new FreemarkerBasedRoute("/newcomment", "entry_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String name = StringEscapeUtils.escapeHtml4(request.queryParams("commentName")); String email = StringEscapeUtils.escapeHtml4(request.queryParams("commentEmail")); String body = StringEscapeUtils.escapeHtml4(request.queryParams("commentBody")); String permalink = request.queryParams("permalink"); Document post = blogPostDAO.findByPermalink(permalink); if (post == null) { response.redirect("/post_not_found"); } // check that comment is good else if (name.equals("") || body.equals("")) { // bounce this back to the user for correction SimpleHash root = new SimpleHash(); SimpleHash comment = new SimpleHash(); comment.put("name", name); comment.put("email", email); comment.put("body", body); root.put("comments", comment); root.put("post", post); root.put("errors", "Post must contain your name and an actual comment"); template.process(root, writer); } else { blogPostDAO.addPostComment(name, email, body, permalink); response.redirect("/post/" + permalink); } } }); // present the login page get(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("username", ""); root.put("login_error", ""); template.process(root, writer); } }); // process output coming from login form. On success redirect folks to the welcome page // on failure, just return an error and let them try again. post(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = request.queryParams("username"); String password = request.queryParams("password"); System.out.println("Login: User submitted: " + username + " " + password); Document user = userDAO.validateLogin(username, password); if (user != null) { // valid user, let's log them in String sessionID = sessionDAO.startSession(user.get("_id").toString()); if (sessionID == null) { response.redirect("/internal_error"); } else { // set the cookie for the user's browser response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/welcome"); } } else { SimpleHash root = new SimpleHash(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("password", ""); root.put("login_error", "Invalid Login"); template.process(root, writer); } } }); // tells the user that the URL is dead get(new FreemarkerBasedRoute("/post_not_found", "post_not_found.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); template.process(root, writer); } }); // allows the user to logout of the blog get(new FreemarkerBasedRoute("/logout", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String sessionID = getSessionCookie(request); if (sessionID == null) { // no session to end response.redirect("/login"); } else { // deletes from session table sessionDAO.endSession(sessionID); // this should delete the cookie Cookie c = getSessionCookieActual(request); c.setMaxAge(0); response.raw().addCookie(c); response.redirect("/login"); } } }); // used to process internal errors get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("error", "System has encountered an error."); template.process(root, writer); } }); }
From source file:iddb.web.security.service.CommonUserService.java
protected void invalidateUserSession(HttpServletRequest request, HttpServletResponse response) { context.removeSubject();// w ww . j a v a 2 s. co m String sessionKey = null; HttpSession session = request.getSession(false); if (session != null) { session.removeAttribute(UserService.SUBJECT); sessionKey = (String) session.getAttribute(UserService.SESSION_KEY); session.removeAttribute(UserService.SESSION_KEY); } // remove cookie Cookie cookie = new Cookie("iddb-u", ""); cookie.setPath(request.getContextPath() + "/"); cookie.setMaxAge(0); response.addCookie(cookie); cookie = new Cookie("iddb-k", ""); cookie.setPath(request.getContextPath() + "/"); cookie.setMaxAge(0); response.addCookie(cookie); if (sessionKey != null) { removeSession(sessionKey); } }
From source file:ai.susi.server.api.aaa.LoginService.java
@Override public JSONObject serviceImpl(Query post, HttpServletResponse response, Authorization authorization, final JsonObjectWithDefault permissions) throws APIException { // login check for app if (post.get("checkLogin", false)) { JSONObject result = new JSONObject(); if (authorization.getIdentity().isEmail()) { result.put("loggedIn", true); result.put("message", "You are logged in as " + authorization.getIdentity().getName()); } else {//from w ww . ja v a 2s. co m result.put("loggedIn", false); result.put("message", "Not logged in"); } return result; } // do logout if requested boolean logout = post.get("logout", false); boolean delete = post.get("delete", false); if (logout || delete) { // logout if requested // invalidate session post.getRequest().getSession().invalidate(); // delete cookie if set deleteLoginCookie(response); if (delete) { ClientCredential pwcredential = new ClientCredential(authorization.getIdentity()); delete = DAO.authentication.has(pwcredential.toString()); if (delete) DAO.authentication.remove(pwcredential.toString()); } JSONObject result = new JSONObject(); result.put("message", delete ? "Account deletion successful" : "Logout successful"); return result; } // check login type by checking which parameters are set boolean passwordLogin = false; boolean pubkeyHello = false; boolean pubkeyLogin = false; if (post.get("login", null) != null && post.get("password", null) != null && post.get("type", null) != null) { passwordLogin = true; } else if (post.get("login", null) != null && post.get("keyhash", null) != null) { pubkeyHello = true; } else if (post.get("sessionID", null) != null && post.get("response", null) != null) { pubkeyLogin = true; } else { throw new APIException(400, "Bad login parameters."); } // check if user is blocked because of too many invalid login attempts checkInvalidLogins(post, authorization, permissions); if (passwordLogin) { // do login via password String login = post.get("login", null); String password = post.get("password", null); String type = post.get("type", null); ClientCredential pwcredential = new ClientCredential(ClientCredential.Type.passwd_login, login); Authentication authentication = getAuthentication(post, authorization, pwcredential); ClientIdentity identity = authentication.getIdentity(); // check if the password is valid String passwordHash; String salt; try { passwordHash = authentication.getString("passwordHash"); salt = authentication.getString("salt"); } catch (Throwable e) { Log.getLog().info("Invalid login try for user: " + identity.getName() + " from host: " + post.getClientHost() + " : password or salt missing in database"); throw new APIException(422, "Invalid credentials"); } if (!passwordHash.equals(getHash(password, salt))) { // save invalid login in accounting object authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); Log.getLog().info("Invalid login try for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); throw new APIException(422, "Invalid credentials"); } JSONObject result = new JSONObject(); switch (type) { case "session": // create a browser session post.getRequest().getSession().setAttribute("identity", identity); break; case "cookie": // set a long living cookie // create random string as token String loginToken = createRandomString(30); // create cookie Cookie loginCookie = new Cookie("login", loginToken); loginCookie.setPath("/"); loginCookie.setMaxAge(defaultCookieTime.intValue()); // write cookie to database ClientCredential cookieCredential = new ClientCredential(ClientCredential.Type.cookie, loginToken); JSONObject user_obj = new JSONObject(); user_obj.put("id", identity.toString()); user_obj.put("expires_on", Instant.now().getEpochSecond() + defaultCookieTime); DAO.authentication.put(cookieCredential.toString(), user_obj, cookieCredential.isPersistent()); response.addCookie(loginCookie); break; case "access-token": // create and display an access token long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); break; default: throw new APIException(400, "Invalid type"); } Log.getLog().info( "login for user: " + identity.getName() + " via passwd from host: " + post.getClientHost()); result.put("message", "You are logged in as " + identity.getName()); return result; } else if (pubkeyHello) { // first part of pubkey login: if the key hash is known, create a challenge String login = post.get("login", null); String keyHash = post.get("keyhash", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.passwd_login, login)); ClientIdentity identity = authentication.getIdentity(); if (!DAO.login_keys.has(identity.toString()) || !DAO.login_keys.getJSONObject(identity.toString()).has(keyHash)) throw new APIException(400, "Unknown key"); String challengeString = createRandomString(30); String newSessionID = createRandomString(30); ClientCredential credential = new ClientCredential(ClientCredential.Type.pubkey_challange, newSessionID); Authentication challenge_auth = new Authentication(credential, DAO.authentication); challenge_auth.setIdentity(identity); challenge_auth.put("activated", true); challenge_auth.put("challenge", challengeString); challenge_auth.put("key", DAO.login_keys.getJSONObject(identity.toString()).getString(keyHash)); challenge_auth.setExpireTime(60 * 10); JSONObject result = new JSONObject(); result.put("challenge", challengeString); result.put("sessionID", newSessionID); result.put("message", "Found valid key for this user. Sign the challenge with you public key and send it back, together with the sessionID"); return result; } else if (pubkeyLogin) { // second part of pubkey login: verify if the response to the challange is valid String sessionID = post.get("sessionID", null); String challangeResponse = post.get("response", null); Authentication authentication = getAuthentication(post, authorization, new ClientCredential(ClientCredential.Type.pubkey_challange, sessionID)); ClientIdentity identity = authentication.getIdentity(); String challenge = authentication.getString("challenge"); PublicKey key = IO.decodePublicKey(authentication.getString("key"), "RSA"); Signature sig; boolean verified; try { sig = Signature.getInstance("SHA256withRSA"); sig.initVerify(key); sig.update(challenge.getBytes()); verified = sig.verify(Base64.getDecoder().decode(challangeResponse)); } catch (NoSuchAlgorithmException e) { throw new APIException(400, "No such algorithm"); } catch (InvalidKeyException e) { throw new APIException(400, "Invalid key"); } catch (Throwable e) { throw new APIException(400, "Bad signature"); } if (verified) { long valid_seconds; try { valid_seconds = post.get("valid_seconds", defaultAccessTokenExpireTime); } catch (Throwable e) { throw new APIException(400, "Invalid value for 'valid_seconds'"); } String token = createAccessToken(identity, valid_seconds); JSONObject result = new JSONObject(); if (valid_seconds == -1) result.put("valid_seconds", "forever"); else result.put("valid_seconds", valid_seconds); result.put("access_token", token); return result; } else { authorization.getAccounting().addRequest(this.getClass().getCanonicalName(), "invalid login"); throw new APIException(400, "Bad Signature"); } } throw new APIException(500, "Server error"); }
From source file:MyServlet.UserController.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // processRequest(request, response); Object message;/* w ww . j av a 2 s .c o m*/ Object userResetToken; String url = "/main.jsp"; action = request.getParameter("action"); System.out.println("action" + action); PrintWriter writer = response.getWriter(); HttpSession session = request.getSession(); User theUser = (User) session.getAttribute("theUser"); writer.println("Inside get" + action); if (theUser != null) { //writer.println("Inside user"); if (action.equals("about")) { url = "/aboutl.jsp"; } if (action.equals("how")) { url = "/main.jsp"; } if (action.equals("home")) { url = "/main.jsp"; } if (action.equals("main")) { url = "/main.jsp"; } if (action.equals("login")) { url = "/login.jsp"; } if (action.equals("create")) { try { String currentTime = sdf.format(dt); String token = request.getParameter("token"); String expiryTime = UserDB.getTime(token); Date date1 = sdf.parse(expiryTime); Date date2 = sdf.parse(currentTime); long differenceInMillis = date2.getTime() - date1.getTime(); if (differenceInMillis < 3600000) { request.setAttribute("token", token); url = "/signup.jsp"; } } catch (ParseException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } if (action.equals("activation")) { String currentTime = sdf.format(dt); String value; String userToken; String password; userToken = request.getParameter("activationcode"); System.out.println("userToken if" + userToken); String expiryTime = UserDB.getTime(userToken); try { Date date1 = sdf.parse(expiryTime); Date date2 = sdf.parse(currentTime); long differenceInMillis = date2.getTime() - date1.getTime(); if (differenceInMillis < 3600000) { User user = UserDB.activateUser(userToken); if (user != null) { value = userPassword.get(user.getEmail()); session.setAttribute("theUser", user); try { password = hashAndSalt(value); userDB.addUser(user, password, salt); userDB.addUser(user); userDB.deleteTemp(userToken); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } url = "/login.jsp"; } else { url = "/signup.jsp"; } } } catch (ParseException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } if (action.equals("resetpassword")) { try { String token; String currentTime = sdf.format(dt); token = request.getParameter("token"); System.out.println("userToken else" + token); String expiryTime = UserDB.getTime(token); Date date1 = sdf.parse(expiryTime); Date date2 = sdf.parse(currentTime); long differenceInMillis = date2.getTime() - date1.getTime(); if (differenceInMillis < 3600000) { User user = UserDB.activateUser(token); if (user != null) { request.setAttribute("user", user); request.setAttribute("userResetToken", token); url = "/resetpassword.jsp"; } else { url = "/signup.jsp"; } } else { message = "Token is expired!!"; request.setAttribute("message", message); url = "/signup.jsp"; } //url="/login.jsp"; } catch (ParseException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } } else { if (action.equals("about")) { url = "/about.jsp"; } if (action.equals("how")) { url = "/how.jsp"; } if (action.equals("home")) { if (flag == 0) { int i = request.getServerPort(); String port = String.valueOf(i); Cookie myCookie = new Cookie("HostName", request.getServerName()); myCookie.setMaxAge(60 * 60 * 24 * 365); myCookie.setPath("/"); response.addCookie(myCookie); Cookie cookiePort = new Cookie("Port", port); myCookie.setMaxAge(60 * 60 * 24 * 365); myCookie.setPath("/"); response.addCookie(cookiePort); } url = "/home.jsp"; flag++; } if (action.equals("main")) { url = "/login.jsp"; } if (action.equals("login")) { url = "/login.jsp"; } if (action.equals("activation")) { String currentTime = sdf.format(dt); String value; String userToken; String password; userToken = request.getParameter("activationcode"); System.out.println("userToken else" + userToken); String expiryTime = UserDB.getTime(userToken); try { Date date1 = sdf.parse(expiryTime); Date date2 = sdf.parse(currentTime); long differenceInMillis = date2.getTime() - date1.getTime(); if (differenceInMillis < 3600000) { User user = UserDB.activateUser(userToken); if (user != null) { value = userPassword.get(user.getEmail()); session.setAttribute("theUser", user); try { password = hashAndSalt(value); userDB.addUser(user, password, salt); userDB.addUser(user); userDB.deleteTemp(userToken); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } url = "/login.jsp"; } else { url = "/signup.jsp"; } } } catch (ParseException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } if (action.equals("resetpassword")) { try { String token; String currentTime = sdf.format(dt); token = request.getParameter("token"); System.out.println("userToken else" + token); String expiryTime = UserDB.getTime(token); Date date1 = sdf.parse(expiryTime); Date date2 = sdf.parse(currentTime); long differenceInMillis = date2.getTime() - date1.getTime(); if (differenceInMillis < 3600000) { User user = UserDB.activateUser(token); if (user != null) { request.setAttribute("user", user); request.setAttribute("userResetToken", token); url = "/resetpassword.jsp"; } else { url = "/signup.jsp"; } } else { message = "Token is expired!!"; request.setAttribute("message", message); url = "/signup.jsp"; } //url="/login.jsp"; } catch (ParseException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } } getServletContext().getRequestDispatcher(url).forward(request, response); }
From source file:es.iesnervion.Week3.Ex3_2Ex3_3.BlogController.java
private void initializeRoutes() throws IOException { // this is the blog home page get(new FreemarkerBasedRoute("/", "blog_template.ftl") { @Override// w ww. jav a 2 s .c o m public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); List<Document> posts = blogPostDAO.findByDateDescending(10); SimpleHash root = new SimpleHash(); root.put("myposts", posts); if (username != null) { root.put("username", username); } template.process(root, writer); } }); // used to display actual blog post detail page get(new FreemarkerBasedRoute("/post/:permalink", "entry_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String permalink = request.params(":permalink"); System.out.println("/post: get " + permalink); Document post = blogPostDAO.findByPermalink(permalink); if (post == null) { response.redirect("/post_not_found"); } else { // empty comment to hold new comment in form at bottom of blog entry detail page SimpleHash newComment = new SimpleHash(); newComment.put("name", ""); newComment.put("email", ""); newComment.put("body", ""); SimpleHash root = new SimpleHash(); root.put("post", post); root.put("comments", newComment); template.process(root, writer); } } }); // handle the signup post post(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String email = request.queryParams("email"); String username = request.queryParams("username"); String password = request.queryParams("password"); String verify = request.queryParams("verify"); HashMap<String, String> root = new HashMap<String, String>(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("email", StringEscapeUtils.escapeHtml4(email)); if (validateSignup(username, password, verify, email, root)) { // good user System.out.println("Signup: Creating user with: " + username + " " + password); if (!userDAO.addUser(username, password, email)) { // duplicate user root.put("username_error", "Username already in use, Please choose another"); template.process(root, writer); } else { // good user, let's start a session String sessionID = sessionDAO.startSession(username); System.out.println("Session ID is" + sessionID); response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/welcome"); } } else { // bad signup System.out.println("User Registration did not validate"); template.process(root, writer); } } }); // present signup form for blog get(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); // initialize values for the form. root.put("username", ""); root.put("password", ""); root.put("email", ""); root.put("password_error", ""); root.put("username_error", ""); root.put("email_error", ""); root.put("verify_error", ""); template.process(root, writer); } }); get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String cookie = getSessionCookie(request); String username = sessionDAO.findUserNameBySessionId(cookie); if (username == null) { System.out.println("welcome() can't identify the user, redirecting to signup"); response.redirect("/signup"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // will present the form used to process new blog posts get(new FreemarkerBasedRoute("/newpost", "newpost_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { // get cookie String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); if (username == null) { // looks like a bad request. user is not logged in response.redirect("/login"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // handle the new post submission post(new FreemarkerBasedRoute("/newpost", "newpost_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String title = StringEscapeUtils.escapeHtml4(request.queryParams("subject")); String post = StringEscapeUtils.escapeHtml4(request.queryParams("body")); String tags = StringEscapeUtils.escapeHtml4(request.queryParams("tags")); String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); if (username == null) { response.redirect("/login"); // only logged in users can post to blog } else if (title.equals("") || post.equals("")) { // redisplay page with errors HashMap<String, String> root = new HashMap<String, String>(); root.put("errors", "post must contain a title and blog entry."); root.put("subject", title); root.put("username", username); root.put("tags", tags); root.put("body", post); template.process(root, writer); } else { // extract tags ArrayList<String> tagsArray = extractTags(tags); // substitute some <p> for the paragraph breaks post = post.replaceAll("\\r?\\n", "<p>"); String permalink = blogPostDAO.addPost(title, post, tagsArray, username); // now redirect to the blog permalink response.redirect("/post/" + permalink); } } }); get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String cookie = getSessionCookie(request); String username = sessionDAO.findUserNameBySessionId(cookie); if (username == null) { System.out.println("welcome() can't identify the user, redirecting to signup"); response.redirect("/signup"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // process a new comment post(new FreemarkerBasedRoute("/newcomment", "entry_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String name = StringEscapeUtils.escapeHtml4(request.queryParams("commentName")); String email = StringEscapeUtils.escapeHtml4(request.queryParams("commentEmail")); String body = StringEscapeUtils.escapeHtml4(request.queryParams("commentBody")); String permalink = request.queryParams("permalink"); Document post = blogPostDAO.findByPermalink(permalink); if (post == null) { response.redirect("/post_not_found"); } // check that comment is good else if (name.equals("") || body.equals("")) { // bounce this back to the user for correction SimpleHash root = new SimpleHash(); SimpleHash comment = new SimpleHash(); comment.put("name", name); comment.put("email", email); comment.put("body", body); root.put("comment", comment); root.put("post", post); root.put("errors", "Post must contain your name and an actual comment"); template.process(root, writer); } else { blogPostDAO.addPostComment(name, email, body, permalink); response.redirect("/post/" + permalink); } } }); // present the login page get(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("username", ""); root.put("login_error", ""); template.process(root, writer); } }); // process output coming from login form. On success redirect folks to the welcome page // on failure, just return an error and let them try again. post(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = request.queryParams("username"); String password = request.queryParams("password"); System.out.println("Login: User submitted: " + username + " " + password); Document user = userDAO.validateLogin(username, password); if (user != null) { // valid user, let's log them in String sessionID = sessionDAO.startSession(user.get("_id").toString()); if (sessionID == null) { response.redirect("/internal_error"); } else { // set the cookie for the user's browser response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/welcome"); } } else { SimpleHash root = new SimpleHash(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("password", ""); root.put("login_error", "Invalid Login"); template.process(root, writer); } } }); // tells the user that the URL is dead get(new FreemarkerBasedRoute("/post_not_found", "post_not_found.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); template.process(root, writer); } }); // allows the user to logout of the blog get(new FreemarkerBasedRoute("/logout", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String sessionID = getSessionCookie(request); if (sessionID == null) { // no session to end response.redirect("/login"); } else { // deletes from session table sessionDAO.endSession(sessionID); // this should delete the cookie Cookie c = getSessionCookieActual(request); c.setMaxAge(0); response.raw().addCookie(c); response.redirect("/login"); } } }); // used to process internal errors get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("error", "System has encountered an error."); template.process(root, writer); } }); }
From source file:com.kingcore.framework.util.CookieUtils.java
/** * domain,path ? clearCookie/*from ww w . j a v a 2s. c o m*/ * The form of the domain name is specified by RFC 2109. A domain name begins with a dot (.foo.com) * and means that the cookie is visible to servers in a specified Domain Name System (DNS) zone * (for example, www.foo.com, but not a.b.foo.com). By default, cookies are only returned to * the server that sent them. * @param name ?Cookie?? * @param response ? * @param domain Cookie?? * @param path Cookie? */ public static void clearCookie(String name, HttpServletResponse response, String domain, String path) { Cookie cookie = new Cookie(name, null); cookie.setMaxAge(0); cookie.setPath(path); cookie.setDomain(domain); response.addCookie(cookie); }
From source file:com.aurel.track.master.ModuleBL.java
public static Cookie cretaeCookie(String cookieValue, String path, String url) { Cookie myCookie = new Cookie("JSESSIONID", cookieValue); myCookie.setPath(path);/*from ww w . j av a2 s. co m*/ URI uri; try { uri = new URI(url); String domain = uri.getHost(); myCookie.setDomain(domain); } catch (URISyntaxException e) { LOGGER.debug(ExceptionUtils.getStackTrace(e)); } return myCookie; }
From source file:alxpez.blog.BlogController.java
private void initializeRoutes() throws IOException { // this is the blog home page get(new FreemarkerBasedRoute("/", "blog_template.ftl") { @Override/* ww w.java 2 s.co m*/ public void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); List<Document> posts = blogPostDAO.findByDateDescending(10); SimpleHash root = new SimpleHash(); root.put("myposts", posts); if (username != null) { root.put("username", username); } template.process(root, writer); } }); // used to display actual blog post detail page get(new FreemarkerBasedRoute("/post/:permalink", "entry_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String permalink = request.params(":permalink"); System.out.println("/post: get " + permalink); Document post = blogPostDAO.findByPermalink(permalink); if (post == null) { response.redirect("/post_not_found"); } else { // empty comment to hold new comment in form at bottom of blog entry detail page SimpleHash newComment = new SimpleHash(); newComment.put("name", ""); newComment.put("email", ""); newComment.put("body", ""); SimpleHash root = new SimpleHash(); root.put("post", post); root.put("comment", newComment); template.process(root, writer); } } }); // handle the signup post post(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String email = request.queryParams("email"); String username = request.queryParams("username"); String password = request.queryParams("password"); String verify = request.queryParams("verify"); HashMap<String, String> root = new HashMap<String, String>(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("email", StringEscapeUtils.escapeHtml4(email)); if (validateSignup(username, password, verify, email, root)) { // good user System.out.println("Signup: Creating user with: " + username + " " + password); if (!userDAO.addUser(username, password, email)) { // duplicate user root.put("username_error", "Username already in use, Please choose another"); template.process(root, writer); } else { // good user, let's start a session String sessionID = sessionDAO.startSession(username); System.out.println("Session ID is" + sessionID); response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/welcome"); } } else { // bad signup System.out.println("User Registration did not validate"); template.process(root, writer); } } }); // present signup form for blog get(new FreemarkerBasedRoute("/signup", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); // initialize values for the form. root.put("username", ""); root.put("password", ""); root.put("email", ""); root.put("password_error", ""); root.put("username_error", ""); root.put("email_error", ""); root.put("verify_error", ""); template.process(root, writer); } }); // will present the form used to process new blog posts get(new FreemarkerBasedRoute("/newpost", "newpost_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { // get cookie String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); if (username == null) { // looks like a bad request. user is not logged in response.redirect("/login"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // handle the new post submission post(new FreemarkerBasedRoute("/newpost", "newpost_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String title = StringEscapeUtils.escapeHtml4(request.queryParams("subject")); String post = StringEscapeUtils.escapeHtml4(request.queryParams("body")); String tags = StringEscapeUtils.escapeHtml4(request.queryParams("tags")); String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); if (username == null) { response.redirect("/login"); // only logged in users can post to blog } else if (title.equals("") || post.equals("")) { // redisplay page with errors HashMap<String, String> root = new HashMap<String, String>(); root.put("errors", "post must contain a title and blog entry."); root.put("subject", title); root.put("username", username); root.put("tags", tags); root.put("body", post); template.process(root, writer); } else { // extract tags ArrayList<String> tagsArray = extractTags(tags); // substitute some <p> for the paragraph breaks post = post.replaceAll("\\r?\\n", "<p>"); String permalink = blogPostDAO.addPost(title, post, tagsArray, username); // now redirect to the blog permalink response.redirect("/post/" + permalink); } } }); get(new FreemarkerBasedRoute("/welcome", "welcome.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String cookie = getSessionCookie(request); String username = sessionDAO.findUserNameBySessionId(cookie); if (username == null) { System.out.println("welcome() can't identify the user, redirecting to signup"); response.redirect("/signup"); } else { SimpleHash root = new SimpleHash(); root.put("username", username); template.process(root, writer); } } }); // process a new comment post(new FreemarkerBasedRoute("/newcomment", "entry_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String name = StringEscapeUtils.escapeHtml4(request.queryParams("commentName")); String email = StringEscapeUtils.escapeHtml4(request.queryParams("commentEmail")); String body = StringEscapeUtils.escapeHtml4(request.queryParams("commentBody")); String permalink = request.queryParams("permalink"); Document post = blogPostDAO.findByPermalink(permalink); if (post == null) { response.redirect("/post_not_found"); } // check that comment is good else if (name.equals("") || body.equals("")) { // bounce this back to the user for correction SimpleHash root = new SimpleHash(); SimpleHash comment = new SimpleHash(); comment.put("name", name); comment.put("email", email); comment.put("body", body); root.put("comment", comment); root.put("post", post); root.put("errors", "Post must contain your name and an actual comment"); template.process(root, writer); } else { blogPostDAO.addPostComment(name, email, body, permalink); response.redirect("/post/" + permalink); } } }); // present the login page get(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("username", ""); root.put("login_error", ""); template.process(root, writer); } }); // process output coming from login form. On success redirect folks to the welcome page // on failure, just return an error and let them try again. post(new FreemarkerBasedRoute("/login", "login.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = request.queryParams("username"); String password = request.queryParams("password"); System.out.println("Login: User submitted: " + username + " " + password); Document user = userDAO.validateLogin(username, password); if (user != null) { // valid user, let's log them in String sessionID = sessionDAO.startSession(user.get("_id").toString()); if (sessionID == null) { response.redirect("/internal_error"); } else { // set the cookie for the user's browser response.raw().addCookie(new Cookie("session", sessionID)); response.redirect("/welcome"); } } else { SimpleHash root = new SimpleHash(); root.put("username", StringEscapeUtils.escapeHtml4(username)); root.put("password", ""); root.put("login_error", "Invalid Login"); template.process(root, writer); } } }); // Show the posts filed under a certain tag get(new FreemarkerBasedRoute("/tag/:thetag", "blog_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); SimpleHash root = new SimpleHash(); String tag = StringEscapeUtils.escapeHtml4(request.params(":thetag")); List<Document> posts = blogPostDAO.findByTagDateDescending(tag); root.put("myposts", posts); if (username != null) { root.put("username", username); } template.process(root, writer); } }); // will allow a user to click Like on a post post(new FreemarkerBasedRoute("/like", "entry_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String permalink = request.queryParams("permalink"); String commentOrdinalStr = request.queryParams("comment_ordinal"); // look up the post in question int ordinal = Integer.parseInt(commentOrdinalStr); // TODO: check return or have checkSession throw String username = sessionDAO.findUserNameBySessionId(getSessionCookie(request)); Document post = blogPostDAO.findByPermalink(permalink); // if post not found, redirect to post not found error if (post == null) { response.redirect("/post_not_found"); } else { blogPostDAO.likePost(permalink, ordinal); response.redirect("/post/" + permalink); } } }); // tells the user that the URL is dead get(new FreemarkerBasedRoute("/post_not_found", "post_not_found.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); template.process(root, writer); } }); // allows the user to logout of the blog get(new FreemarkerBasedRoute("/logout", "signup.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { String sessionID = getSessionCookie(request); if (sessionID == null) { // no session to end response.redirect("/login"); } else { // deletes from session table sessionDAO.endSession(sessionID); // this should delete the cookie Cookie c = getSessionCookieActual(request); c.setMaxAge(0); response.raw().addCookie(c); response.redirect("/login"); } } }); // used to process internal errors get(new FreemarkerBasedRoute("/internal_error", "error_template.ftl") { @Override protected void doHandle(Request request, Response response, Writer writer) throws IOException, TemplateException { SimpleHash root = new SimpleHash(); root.put("error", "System has encountered an error."); template.process(root, writer); } }); }
From source file:com.streamsets.lib.security.http.SSOUserAuthenticator.java
Cookie createAuthCookie(HttpServletRequest httpReq, String authToken, long expiresMillis) { Cookie authCookie = new Cookie(getAuthCookieName(httpReq), authToken); authCookie.setPath("/"); // if positive it is a persistent session, else a transient one and we don't have to set the cookie age if (expiresMillis > 0) { int secondsToLive = (int) ((expiresMillis - System.currentTimeMillis()) / 1000); authCookie.setMaxAge(secondsToLive); } else if (expiresMillis == 0) { // to delete the cookie authCookie.setMaxAge(0);/* www . j a v a 2 s .c o m*/ } if (isDataCollector) { // When an SDC is accessing SCH, set the cookie based on the SDC's scheme authCookie.setSecure(httpReq.isSecure()); } else { // When a browser accesses SCH, set the cookie based on the SCH endpoint authCookie.setSecure(dpmBaseUrl.startsWith("https")); } return authCookie; }