List of usage examples for javax.servlet.http HttpSession invalidate
public void invalidate();
From source file:MyServlet.UserController.java
/** * Handles the HTTP <code>POST</code> method. * * @param request servlet request/*from w ww. j a va 2 s . c om*/ * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ @Override protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //processRequest(request, response); String url = "/main.jsp"; Object message; action = request.getServletPath(); PrintWriter writer = response.getWriter(); String formName = request.getParameter("formname"); HttpSession session = request.getSession(); writer.println("formName :" + formName); System.out.println("Inside post user"); if (formName.equals("create")) { String hosturl = request.getRequestURL().toString(); String baseURL = hosturl.substring(0, hosturl.length() - request.getRequestURI().length()) + request.getContextPath() + "/"; System.out.println("hosturl" + hosturl); System.out.println("baseURL" + baseURL); String name = request.getParameter("name"); String email = request.getParameter("email"); String password = request.getParameter("password"); String cpass = request.getParameter("cpass"); String token = request.getParameter("token"); User user = new User(); user.setName(name); user.setEmail(email); request.setAttribute("user", user); if (password.equals(cpass)) { if (userDB.getUser(email) == null) { if (token != null) { int recomCoins; User userRecom, newUser; userRecom = UserDB.activateUser(token); if (userRecom != null) { newUser = UserDB.getUser(userRecom.getEmail()); recomCoins = newUser.getCoins(); newUser.setCoins(recomCoins + 2); UserDB.update(newUser); UserDB.deleteTemp(token); } } UUID uId = UUID.randomUUID(); System.out.println("UUID One: " + uId); //session.setAttribute("theUser", user); userPassword.put(email, password); userDB.tempUser(user, uId); /* userDB.addUser(user,password); userDB.addUser(user);*/ String to = email; String from = email; String subject = "Activation Link"; String body = baseURL + "user?action=activation&activationcode=" + uId; boolean bodyIsHTML = false; try { MailUtilLocal.sendMail(to, from, subject, body, bodyIsHTML); System.out.println("mail sent"); message = "Activation link sent to your email account"; request.setAttribute("message", message); url = "/login.jsp"; } catch (MessagingException e) { String errorMessage = "ERROR: Unable to send email." + "ERROR MESSAGE:" + e.getMessage(); System.out.println(errorMessage); request.setAttribute("errorMessage", errorMessage); url = "/contact.jsp"; } } else { message = "Email address already exist!!"; request.setAttribute("message", message); url = "/signup.jsp"; } } else { writer.println("Error"); message = "Confirm Password doesnot match"; request.setAttribute("message", message); url = "/signup.jsp"; } } else if (formName.equals("login")) { User userLogin; String email = request.getParameter("email"); String password = request.getParameter("password"); writer.println("inside login" + userPassword.get(email)); userLogin = userDB.getUser(email); if (userLogin == null) { writer.println("no user"); message = "Not found email address : " + email; request.setAttribute("message", message); url = "/login.jsp"; } else { writer.println("inside else"); try { String salt = UserDB.getSalt(email); if (salt != null) { password = hashPassword(password + salt); if (userDB.validateUser(email, password)) { if (session.getAttribute("theUser") != null) { session.invalidate(); } session = request.getSession(); session.setAttribute("theUser", userLogin); url = "/main.jsp"; } else { message = "Password is incorrect!!"; request.setAttribute("message", message); url = "/login.jsp"; } } } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } } } else if (formName.equals("forgetpassword")) { String name = "name"; String email = request.getParameter("email"); System.out.println("email" + email); if (userDB.getUser(email) != null) { UUID uId = UUID.randomUUID(); System.out.println("UUID One: " + uId); //session.setAttribute("theUser", user); String to = email; String from = email; String subject = "Password Reset Link"; String hosturl = request.getRequestURL().toString(); String baseURL = hosturl.substring(0, hosturl.length() - request.getRequestURI().length()) + request.getContextPath() + "/"; String body = baseURL + "user?action=resetpassword&token=" + uId; boolean bodyIsHTML = false; try { User user = new User(); user.setName(name); user.setEmail(email); userDB.tempUser(user, uId); MailUtilLocal.sendMail(to, from, subject, body, bodyIsHTML); System.out.println("mail sent"); message = "Please check your email account"; request.setAttribute("message", message); url = "/login.jsp"; } catch (MessagingException e) { String errorMessage = "ERROR: Unable to send email." + "ERROR MESSAGE:" + e.getMessage(); System.out.println(errorMessage); request.setAttribute("errorMessage", errorMessage); url = "/contact.jsp"; } } } else if (formName.equals("resetpassword")) { try { String currentTime = sdf.format(dt); String password = request.getParameter("password"); String cpass = request.getParameter("cpass"); String email = request.getParameter("email"); 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) { User user = new User(); user.setEmail(email); if (password.equals(cpass)) { try { password = hashAndSalt(password); } catch (NoSuchAlgorithmException ex) { Logger.getLogger(UserController.class.getName()).log(Level.SEVERE, null, ex); } UserDB.updatePassword(user, password, salt); UserDB.deleteTempEmail(email); url = "/login.jsp"; } else { request.setAttribute("user", user); request.setAttribute("userResetToken", token); url = "/resetpassword.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:com.sammyun.controller.shop.RegisterController.java
/** * ??/* w w w. j a v a2 s . co m*/ */ @RequestMapping(value = "/registSubmit", method = RequestMethod.POST) public @ResponseBody Message registSubmit(String firstName, String givenName, String email, String mobile, RegMode regMode, Long areaId, boolean thirdPart, HttpServletRequest request, HttpServletResponse response, HttpSession session) { String password = rsaService.decryptParameter("enPassword", request); rsaService.removePrivateKey(request); Setting setting = SettingUtils.get(); if (!setting.getIsRegisterEnabled()) { return Message.error("shop.register.disabled"); } if (password.length() < setting.getPasswordMinLength()) { return Message.error("shop.login.password.length.lessThan", setting.getPasswordMinLength()); } if (password.length() > setting.getPasswordMaxLength()) { return Message.error("shop.login.password.length.greater", setting.getPasswordMaxLength()); } if (!setting.getIsDuplicateEmail() && memberService.emailExists(email)) { return Message.error("shop.register.emailExist"); } Member member = new Member(); List<MemberAttribute> memberAttributes = memberAttributeService.findList(); for (MemberAttribute memberAttribute : memberAttributes) { String parameter = request.getParameter("memberAttribute_" + memberAttribute.getId()); if (memberAttribute.getType() == Type.name || memberAttribute.getType() == Type.address || memberAttribute.getType() == Type.zipCode || memberAttribute.getType() == Type.phone || memberAttribute.getType() == Type.mobile || memberAttribute.getType() == Type.text || memberAttribute.getType() == Type.select) { if (memberAttribute.getIsRequired() && StringUtils.isEmpty(parameter)) { return Message.error("shop.common.invalid"); } member.setAttributeValue(memberAttribute, parameter); } else if (memberAttribute.getType() == Type.gender) { Gender gender = StringUtils.isNotEmpty(parameter) ? Gender.valueOf(parameter) : null; if (memberAttribute.getIsRequired() && gender == null) { return Message.error("shop.common.invalid"); } member.setGender(gender); } else if (memberAttribute.getType() == Type.birth) { try { Date birth = StringUtils.isNotEmpty(parameter) ? DateUtils.parseDate(parameter, CommonAttributes.DATE_PATTERNS) : null; if (memberAttribute.getIsRequired() && birth == null) { return Message.error("shop.common.invalid"); } member.setBirth(birth); } catch (ParseException e) { return Message.error("shop.common.invalid"); } } else if (memberAttribute.getType() == Type.area) { Area area = StringUtils.isNotEmpty(parameter) ? areaService.find(Long.valueOf(parameter)) : null; if (area != null) { member.setArea(area); } else if (memberAttribute.getIsRequired()) { return Message.error("shop.common.invalid"); } } else if (memberAttribute.getType() == Type.checkbox) { String[] parameterValues = request.getParameterValues("memberAttribute_" + memberAttribute.getId()); List<String> options = parameterValues != null ? Arrays.asList(parameterValues) : null; if (memberAttribute.getIsRequired() && (options == null || options.isEmpty())) { return Message.error("shop.common.invalid"); } member.setAttributeValue(memberAttribute, options); } } Area area = this.areaService.find(areaId); if (RegMode.email == regMode) { member.setUsername(email); } else if (RegMode.mobile == regMode) { member.setUsername(mobile); } else { member.setUsername(email); } member.setPassword(DigestUtils.md5Hex(password)); member.setEmail(email); member.setMobile(mobile); member.setArea(area); member.setPoint(setting.getRegisterPoint()); member.setIsEnabled(true); member.setIsLocked(false); member.setLoginFailureCount(0); member.setLockedDate(null); member.setRegisterIp(EduUtil.getAddr(request)); member.setLoginIp(EduUtil.getAddr(request)); member.setLoginDate(new Date()); member.setSafeKey(null); member.setAddress(area.getFullName()); memberService.save(member); Map<String, Object> attributes = new HashMap<String, Object>(); Enumeration<?> keys = session.getAttributeNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); attributes.put(key, session.getAttribute(key)); } session.invalidate(); session = request.getSession(); for (Entry<String, Object> entry : attributes.entrySet()) { session.setAttribute(entry.getKey(), entry.getValue()); } session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), member.getUsername())); WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername()); return Message.success("shop.register.success"); }
From source file:com.sammyun.controller.shop.RegisterController.java
/** * ??/* www. jav a 2 s . co m*/ */ @RequestMapping(value = "/submit", method = RequestMethod.POST) public @ResponseBody Message submit(String captchaId, String captcha, String username, String email, HttpServletRequest request, HttpServletResponse response, HttpSession session) { String password = rsaService.decryptParameter("enPassword", request); rsaService.removePrivateKey(request); if (!captchaService.isValid(CaptchaType.memberRegister, captchaId, captcha)) { return Message.error("shop.captcha.invalid"); } Setting setting = SettingUtils.get(); if (!setting.getIsRegisterEnabled()) { return Message.error("shop.register.disabled"); } if (!isValid(Member.class, "username", username, Save.class) || !isValid(Member.class, "password", password, Save.class) || !isValid(Member.class, "email", email, Save.class)) { return Message.error("shop.common.invalid"); } if (username.length() < setting.getUsernameMinLength() || username.length() > setting.getUsernameMaxLength()) { return Message.error("shop.common.invalid"); } if (password.length() < setting.getPasswordMinLength() || password.length() > setting.getPasswordMaxLength()) { return Message.error("shop.common.invalid"); } if (memberService.usernameDisabled(username) || memberService.usernameExists(username)) { return Message.error("shop.register.disabledExist"); } if (!setting.getIsDuplicateEmail() && memberService.emailExists(email)) { return Message.error("shop.register.emailExist"); } Member member = new Member(); List<MemberAttribute> memberAttributes = memberAttributeService.findList(); for (MemberAttribute memberAttribute : memberAttributes) { String parameter = request.getParameter("memberAttribute_" + memberAttribute.getId()); if (memberAttribute.getType() == Type.name || memberAttribute.getType() == Type.address || memberAttribute.getType() == Type.zipCode || memberAttribute.getType() == Type.phone || memberAttribute.getType() == Type.mobile || memberAttribute.getType() == Type.text || memberAttribute.getType() == Type.select) { if (memberAttribute.getIsRequired() && StringUtils.isEmpty(parameter)) { return Message.error("shop.common.invalid"); } member.setAttributeValue(memberAttribute, parameter); } else if (memberAttribute.getType() == Type.gender) { Gender gender = StringUtils.isNotEmpty(parameter) ? Gender.valueOf(parameter) : null; if (memberAttribute.getIsRequired() && gender == null) { return Message.error("shop.common.invalid"); } member.setGender(gender); } else if (memberAttribute.getType() == Type.birth) { try { Date birth = StringUtils.isNotEmpty(parameter) ? DateUtils.parseDate(parameter, CommonAttributes.DATE_PATTERNS) : null; if (memberAttribute.getIsRequired() && birth == null) { return Message.error("shop.common.invalid"); } member.setBirth(birth); } catch (ParseException e) { return Message.error("shop.common.invalid"); } } else if (memberAttribute.getType() == Type.area) { Area area = StringUtils.isNotEmpty(parameter) ? areaService.find(Long.valueOf(parameter)) : null; if (area != null) { member.setArea(area); } else if (memberAttribute.getIsRequired()) { return Message.error("shop.common.invalid"); } } else if (memberAttribute.getType() == Type.checkbox) { String[] parameterValues = request.getParameterValues("memberAttribute_" + memberAttribute.getId()); List<String> options = parameterValues != null ? Arrays.asList(parameterValues) : null; if (memberAttribute.getIsRequired() && (options == null || options.isEmpty())) { return Message.error("shop.common.invalid"); } member.setAttributeValue(memberAttribute, options); } } member.setUsername(username.toLowerCase()); member.setPassword(DigestUtils.md5Hex(password)); member.setEmail(email); member.setPoint(setting.getRegisterPoint()); member.setIsEnabled(true); member.setIsLocked(false); member.setLoginFailureCount(0); member.setLockedDate(null); member.setRegisterIp(EduUtil.getAddr(request)); member.setLoginIp(EduUtil.getAddr(request)); member.setLoginDate(new Date()); member.setSafeKey(null); memberService.save(member); Map<String, Object> attributes = new HashMap<String, Object>(); Enumeration<?> keys = session.getAttributeNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); attributes.put(key, session.getAttribute(key)); } session.invalidate(); session = request.getSession(); for (Entry<String, Object> entry : attributes.entrySet()) { session.setAttribute(entry.getKey(), entry.getValue()); } session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), member.getUsername())); WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername()); return Message.success("shop.register.success"); }
From source file:com.liferay.portal.events.ServicePreActionExt.java
protected void servicePre(HttpServletRequest request, HttpServletResponse response) throws Exception { HttpSession session = request.getSession(); // Company/*from www . j a va 2 s.co m*/ Company company = PortalUtil.getCompany(request); long companyId = company.getCompanyId(); // CDN host String cdnHost = null; if (request.isSecure()) { cdnHost = PortalUtil.getCDNHostHttps(); } else { cdnHost = PortalUtil.getCDNHostHttp(); } cdnHost = ParamUtil.getString(request, "cdn_host", cdnHost); // Portal URL String portalURL = PortalUtil.getPortalURL(request); // Paths String contextPath = PortalUtil.getPathContext(); String friendlyURLPrivateGroupPath = PortalUtil.getPathFriendlyURLPrivateGroup(); String friendlyURLPrivateUserPath = PortalUtil.getPathFriendlyURLPrivateUser(); String friendlyURLPublicPath = PortalUtil.getPathFriendlyURLPublic(); String imagePath = cdnHost.concat(PortalUtil.getPathImage()); String mainPath = PortalUtil.getPathMain(); String i18nPath = (String) request.getAttribute(WebKeys.I18N_PATH); if (Validator.isNotNull(i18nPath)) { if (Validator.isNotNull(contextPath)) { String i18nContextPath = contextPath.concat(i18nPath); friendlyURLPrivateGroupPath = StringUtil.replaceFirst(friendlyURLPrivateGroupPath, contextPath, i18nContextPath); friendlyURLPrivateUserPath = StringUtil.replaceFirst(friendlyURLPrivateUserPath, contextPath, i18nContextPath); friendlyURLPublicPath = StringUtil.replaceFirst(friendlyURLPublicPath, contextPath, i18nContextPath); mainPath = StringUtil.replaceFirst(mainPath, contextPath, i18nContextPath); } else { friendlyURLPrivateGroupPath = i18nPath.concat(friendlyURLPrivateGroupPath); friendlyURLPrivateUserPath = i18nPath.concat(friendlyURLPrivateUserPath); friendlyURLPublicPath = i18nPath.concat(friendlyURLPublicPath); mainPath = i18nPath.concat(mainPath); } } // Company logo StringBundler sb = new StringBundler(5); sb.append(imagePath); sb.append("/company_logo?img_id="); sb.append(company.getLogoId()); sb.append("&t="); sb.append(ImageServletTokenUtil.getToken(company.getLogoId())); String companyLogo = sb.toString(); Image companyLogoImage = ImageLocalServiceUtil.getCompanyLogo(company.getLogoId()); int companyLogoHeight = companyLogoImage.getHeight(); int companyLogoWidth = companyLogoImage.getWidth(); String realCompanyLogo = companyLogo; int realCompanyLogoHeight = companyLogoHeight; int realCompanyLogoWidth = companyLogoWidth; // User User user = null; try { user = PortalUtil.getUser(request); } catch (NoSuchUserException nsue) { if (_log.isWarnEnabled()) { _log.warn(nsue.getMessage()); } long userId = PortalUtil.getUserId(request); if (userId > 0) { session.invalidate(); } return; } boolean signedIn = false; if (user == null) { user = company.getDefaultUser(); } else if (!user.isDefaultUser()) { signedIn = true; } User realUser = user; Long realUserId = (Long) session.getAttribute(WebKeys.USER_ID); if (realUserId != null) { if (user.getUserId() != realUserId.longValue()) { realUser = UserLocalServiceUtil.getUserById(realUserId.longValue()); } } String doAsUserId = ParamUtil.getString(request, "doAsUserId"); String doAsUserLanguageId = ParamUtil.getString(request, "doAsUserLanguageId"); long doAsGroupId = ParamUtil.getLong(request, "doAsGroupId"); long refererPlid = ParamUtil.getLong(request, "refererPlid"); // Permission checker PermissionChecker permissionChecker = PermissionCheckerFactoryUtil.create(user, true); PermissionThreadLocal.setPermissionChecker(permissionChecker); // Locale Locale locale = (Locale) session.getAttribute(Globals.LOCALE_KEY); if (Validator.isNotNull(doAsUserLanguageId)) { locale = LocaleUtil.fromLanguageId(doAsUserLanguageId); } String i18nLanguageId = (String) request.getAttribute(WebKeys.I18N_LANGUAGE_ID); if (Validator.isNotNull(i18nLanguageId)) { locale = LocaleUtil.fromLanguageId(i18nLanguageId); } else if (locale == null) { if (signedIn) { locale = user.getLocale(); } else { // User previously set their preferred language String languageId = CookieKeys.getCookie(request, CookieKeys.GUEST_LANGUAGE_ID); if (Validator.isNotNull(languageId)) { locale = LocaleUtil.fromLanguageId(languageId); } // Get locale from the request if ((locale == null) && PropsValues.LOCALE_DEFAULT_REQUEST) { locale = request.getLocale(); } // Get locale from the default user if (locale == null) { locale = user.getLocale(); } if (Validator.isNull(locale.getCountry())) { // Locales must contain a country code locale = LanguageUtil.getLocale(locale.getLanguage()); } if (!LanguageUtil.isAvailableLocale(locale)) { locale = user.getLocale(); } } session.setAttribute(Globals.LOCALE_KEY, locale); LanguageUtil.updateCookie(request, response, locale); } // Cookie support try { // LEP-4069 CookieKeys.validateSupportCookie(request); } catch (Exception e) { CookieKeys.addSupportCookie(request, response); } // Time zone TimeZone timeZone = user.getTimeZone(); if (timeZone == null) { timeZone = company.getTimeZone(); } // Layouts if (signedIn) { updateUserLayouts(user); } Layout layout = null; List<Layout> layouts = null; long plid = ParamUtil.getLong(request, "p_l_id"); if (plid > 0) { layout = LayoutLocalServiceUtil.getLayout(plid); } else { long groupId = ParamUtil.getLong(request, "groupId"); boolean privateLayout = ParamUtil.getBoolean(request, "privateLayout"); long layoutId = ParamUtil.getLong(request, "layoutId"); if ((groupId > 0) && layoutId > 0) { layout = LayoutLocalServiceUtil.getLayout(groupId, privateLayout, layoutId); } } if (layout != null) { try { Group group = layout.getGroup(); if (!signedIn && PropsValues.AUTH_FORWARD_BY_REDIRECT) { request.setAttribute(WebKeys.REQUESTED_LAYOUT, layout); } boolean isViewableCommunity = isViewableGroup(user, layout.getGroupId(), layout.isPrivateLayout(), layout.getLayoutId(), permissionChecker); if (!isViewableCommunity && group.isStagingGroup()) { layout = null; } else if (!isViewableCommunity) { sb = new StringBundler(6); sb.append("User "); sb.append(user.getUserId()); sb.append(" is not allowed to access the "); sb.append(layout.isPrivateLayout() ? "private" : "public"); sb.append(" pages of group "); sb.append(layout.getGroupId()); if (_log.isWarnEnabled()) { _log.warn(sb.toString()); } throw new PrincipalException(sb.toString()); } else if (isViewableCommunity && !LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.VIEW)) { layout = null; } else if (group.isLayoutPrototype()) { layouts = new ArrayList<Layout>(); } else { layouts = LayoutLocalServiceUtil.getLayouts(layout.getGroupId(), layout.isPrivateLayout(), LayoutConstants.DEFAULT_PARENT_LAYOUT_ID); if (!group.isControlPanel()) { doAsGroupId = 0; } } } catch (NoSuchLayoutException nsle) { } } if (layout == null) { Object[] defaultLayout = getDefaultLayout(request, user, signedIn); layout = (Layout) defaultLayout[0]; layouts = (List<Layout>) defaultLayout[1]; request.setAttribute(WebKeys.LAYOUT_DEFAULT, Boolean.TRUE); } Object[] viewableLayouts = getViewableLayouts(request, user, permissionChecker, layout, layouts); String layoutSetLogo = null; layout = (Layout) viewableLayouts[0]; layouts = (List<Layout>) viewableLayouts[1]; Group group = null; if (layout != null) { group = layout.getGroup(); if (!group.isControlPanel()) { rememberVisitedGroupIds(request, group.getGroupId()); } } LayoutTypePortlet layoutTypePortlet = null; layouts = mergeAdditionalLayouts(request, user, permissionChecker, layout, layouts); if (layout != null) { if (company.isCommunityLogo()) { long logoId = 0; LayoutSet layoutSet = layout.getLayoutSet(); if (layoutSet.isLogo()) { logoId = layoutSet.getLogoId(); } else { LayoutSet siblingLayoutSet = LayoutSetLocalServiceUtil.getLayoutSet(layout.getGroupId(), !layout.isPrivateLayout()); if (siblingLayoutSet.isLogo()) { logoId = siblingLayoutSet.getLogoId(); } } if (logoId > 0) { sb = new StringBundler(5); sb.append(imagePath); sb.append("/layout_set_logo?img_id="); sb.append(logoId); sb.append("&t="); sb.append(ImageServletTokenUtil.getToken(logoId)); layoutSetLogo = sb.toString(); Image layoutSetLogoImage = ImageLocalServiceUtil.getCompanyLogo(logoId); companyLogo = layoutSetLogo; companyLogoHeight = layoutSetLogoImage.getHeight(); companyLogoWidth = layoutSetLogoImage.getWidth(); } } plid = layout.getPlid(); // Updates to shared layouts are not reflected until the next time // the user logs in because group layouts are cached in the session layout = (Layout) ((LayoutImpl) layout).clone(); layoutTypePortlet = (LayoutTypePortlet) layout.getLayoutType(); LayoutClone layoutClone = LayoutCloneFactory.getInstance(); if (layoutClone != null) { String typeSettings = layoutClone.get(request, plid); if (typeSettings != null) { UnicodeProperties props = new UnicodeProperties(true); props.load(typeSettings); String stateMax = props.getProperty(LayoutTypePortletConstants.STATE_MAX); String stateMin = props.getProperty(LayoutTypePortletConstants.STATE_MIN); String modeAbout = props.getProperty(LayoutTypePortletConstants.MODE_ABOUT); String modeConfig = props.getProperty(LayoutTypePortletConstants.MODE_CONFIG); String modeEdit = props.getProperty(LayoutTypePortletConstants.MODE_EDIT); String modeEditDefaults = props.getProperty(LayoutTypePortletConstants.MODE_EDIT_DEFAULTS); String modeEditGuest = props.getProperty(LayoutTypePortletConstants.MODE_EDIT_GUEST); String modeHelp = props.getProperty(LayoutTypePortletConstants.MODE_HELP); String modePreview = props.getProperty(LayoutTypePortletConstants.MODE_PREVIEW); String modePrint = props.getProperty(LayoutTypePortletConstants.MODE_PRINT); layoutTypePortlet.setStateMax(stateMax); layoutTypePortlet.setStateMin(stateMin); layoutTypePortlet.setModeAbout(modeAbout); layoutTypePortlet.setModeConfig(modeConfig); layoutTypePortlet.setModeEdit(modeEdit); layoutTypePortlet.setModeEditDefaults(modeEditDefaults); layoutTypePortlet.setModeEditGuest(modeEditGuest); layoutTypePortlet.setModeHelp(modeHelp); layoutTypePortlet.setModePreview(modePreview); layoutTypePortlet.setModePrint(modePrint); } } request.setAttribute(WebKeys.LAYOUT, layout); request.setAttribute(WebKeys.LAYOUTS, layouts); if (layout.isPrivateLayout()) { permissionChecker.setCheckGuest(false); } } // Scope long scopeGroupId = PortalUtil.getScopeGroupId(request); long parentGroupId = PortalUtil.getParentGroupId(scopeGroupId); // Device Device device = DevicesUtil.getDeviceFromRequest(request); _log.debug(" Device is: " + device); // Theme and color scheme Theme theme = null; ColorScheme colorScheme = null; boolean wapTheme = BrowserSnifferUtil.isWap(request); if ((layout != null) && group.isControlPanel()) { String themeId = PrefsPropsUtil.getString(companyId, PropsKeys.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID); String colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId(); theme = ThemeLocalServiceUtil.getTheme(companyId, themeId, wapTheme); colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId, wapTheme); if (!wapTheme && theme.isWapTheme()) { theme = ThemeLocalServiceUtil.getTheme(companyId, PropsValues.CONTROL_PANEL_LAYOUT_REGULAR_THEME_ID, false); colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId, false); } } else { DeviceAction deviceAction = DeviceRulesUtil.getAction(device, companyId, group.getGroupId(), layout.getPlid()); if (deviceAction != null && !(deviceAction instanceof NoAction)) { if (deviceAction instanceof ChangeThemeAction) { ChangeThemeAction changeThemeAction = (ChangeThemeAction) deviceAction; ThemeAndColorScheme themeAndColorScheme = changeThemeAction.getThemeAndColorScheme(); if (themeAndColorScheme != null && themeAndColorScheme.getThemeId() != null) { theme = themeAndColorScheme.getTheme(companyId); _log.debug("Changing theme to " + theme.getThemeId()); if (themeAndColorScheme.getColorSchemeId() != null) { colorScheme = themeAndColorScheme.getColorScheme(companyId); _log.debug("Changing color scheme to " + colorScheme.getColorSchemeId()); } } } if (deviceAction instanceof RedirectAction) { RedirectAction redirectAction = (RedirectAction) deviceAction; String url = redirectAction.getUrl(); if (url != null && !url.trim().isEmpty()) { _log.debug("Redirecting to " + url); response.sendRedirect(url); return; } } } else if (layout != null) { if (wapTheme) { theme = layout.getWapTheme(); colorScheme = layout.getWapColorScheme(); } else { theme = layout.getTheme(); colorScheme = layout.getColorScheme(); } } else { String themeId = null; String colorSchemeId = null; if (wapTheme) { themeId = ThemeImpl.getDefaultWapThemeId(companyId); colorSchemeId = ColorSchemeImpl.getDefaultWapColorSchemeId(); } else { themeId = ThemeImpl.getDefaultRegularThemeId(companyId); colorSchemeId = ColorSchemeImpl.getDefaultRegularColorSchemeId(); } theme = ThemeLocalServiceUtil.getTheme(companyId, themeId, wapTheme); colorScheme = ThemeLocalServiceUtil.getColorScheme(companyId, theme.getThemeId(), colorSchemeId, wapTheme); } } request.setAttribute(WebKeys.THEME, theme); request.setAttribute(WebKeys.COLOR_SCHEME, colorScheme); boolean themeCssFastLoad = SessionParamUtil.getBoolean(request, "css_fast_load", PropsValues.THEME_CSS_FAST_LOAD); boolean themeImagesFastLoad = SessionParamUtil.getBoolean(request, "images_fast_load", PropsValues.THEME_IMAGES_FAST_LOAD); boolean themeJsBarebone = PropsValues.JAVASCRIPT_BAREBONE_ENABLED; if (themeJsBarebone) { if (signedIn) { themeJsBarebone = false; } } boolean themeJsFastLoad = SessionParamUtil.getBoolean(request, "js_fast_load", PropsValues.JAVASCRIPT_FAST_LOAD); String lifecycle = ParamUtil.getString(request, "p_p_lifecycle", "0"); boolean isolated = ParamUtil.getBoolean(request, "p_p_isolated"); String facebookCanvasPageURL = (String) request.getAttribute(WebKeys.FACEBOOK_CANVAS_PAGE_URL); boolean widget = false; Boolean widgetObj = (Boolean) request.getAttribute(WebKeys.WIDGET); if (widgetObj != null) { widget = widgetObj.booleanValue(); } // Theme display ThemeDisplay themeDisplay = ThemeDisplayFactory.create(); // Set the CDN host, portal URL, and Facebook application ID first // because other methods (setLookAndFeel) depend on them being set themeDisplay.setCDNHost(cdnHost); themeDisplay.setPortalURL(portalURL); themeDisplay.setFacebookCanvasPageURL(facebookCanvasPageURL); themeDisplay.setWidget(widget); themeDisplay.setCompany(company); themeDisplay.setCompanyLogo(companyLogo); themeDisplay.setCompanyLogoHeight(companyLogoHeight); themeDisplay.setCompanyLogoWidth(companyLogoWidth); themeDisplay.setRealCompanyLogo(realCompanyLogo); themeDisplay.setRealCompanyLogoHeight(realCompanyLogoHeight); themeDisplay.setRealCompanyLogoWidth(realCompanyLogoWidth); themeDisplay.setUser(user); themeDisplay.setRealUser(realUser); themeDisplay.setDoAsUserId(doAsUserId); themeDisplay.setDoAsUserLanguageId(doAsUserLanguageId); themeDisplay.setDoAsGroupId(doAsGroupId); themeDisplay.setRefererPlid(refererPlid); themeDisplay.setLayoutSetLogo(layoutSetLogo); themeDisplay.setLayout(layout); themeDisplay.setLayouts(layouts); themeDisplay.setPlid(plid); themeDisplay.setLayoutTypePortlet(layoutTypePortlet); themeDisplay.setScopeGroupId(scopeGroupId); themeDisplay.setParentGroupId(parentGroupId); themeDisplay.setSignedIn(signedIn); themeDisplay.setPermissionChecker(permissionChecker); themeDisplay.setLocale(locale); themeDisplay.setLanguageId(LocaleUtil.toLanguageId(locale)); themeDisplay.setI18nLanguageId(i18nLanguageId); themeDisplay.setI18nPath(i18nPath); themeDisplay.setTimeZone(timeZone); themeDisplay.setLookAndFeel(contextPath, theme, colorScheme); themeDisplay.setThemeCssFastLoad(themeCssFastLoad); themeDisplay.setThemeImagesFastLoad(themeImagesFastLoad); themeDisplay.setThemeJsBarebone(themeJsBarebone); themeDisplay.setThemeJsFastLoad(themeJsFastLoad); themeDisplay.setServerName(request.getServerName()); themeDisplay.setServerPort(request.getServerPort()); themeDisplay.setSecure(request.isSecure()); themeDisplay.setLifecycle(lifecycle); themeDisplay.setLifecycleAction(lifecycle.equals("1")); themeDisplay.setLifecycleRender(lifecycle.equals("0")); themeDisplay.setLifecycleResource(lifecycle.equals("2")); themeDisplay.setStateExclusive(LiferayWindowState.isExclusive(request)); themeDisplay.setStateMaximized(LiferayWindowState.isMaximized(request)); themeDisplay.setStatePopUp(LiferayWindowState.isPopUp(request)); themeDisplay.setIsolated(isolated); themeDisplay.setPathApplet(contextPath.concat("/applets")); themeDisplay.setPathCms(contextPath.concat("/cms")); themeDisplay.setPathContext(contextPath); themeDisplay.setPathFlash(contextPath.concat("/flash")); themeDisplay.setPathFriendlyURLPrivateGroup(friendlyURLPrivateGroupPath); themeDisplay.setPathFriendlyURLPrivateUser(friendlyURLPrivateUserPath); themeDisplay.setPathFriendlyURLPublic(friendlyURLPublicPath); themeDisplay.setPathImage(imagePath); themeDisplay.setPathJavaScript(cdnHost.concat(contextPath).concat("/html/js")); themeDisplay.setPathMain(mainPath); themeDisplay.setPathSound(contextPath.concat("/html/sound")); // URLs themeDisplay.setShowAddContentIcon(false); themeDisplay.setShowControlPanelIcon(signedIn); themeDisplay.setShowHomeIcon(true); themeDisplay.setShowMyAccountIcon(signedIn); themeDisplay.setShowPageSettingsIcon(false); themeDisplay.setShowPortalIcon(true); themeDisplay.setShowSignInIcon(!signedIn); themeDisplay.setShowSignOutIcon(signedIn); themeDisplay.setShowStagingIcon(false); String urlControlPanel = friendlyURLPrivateGroupPath.concat(GroupConstants.CONTROL_PANEL_FRIENDLY_URL); if (Validator.isNotNull(doAsUserId)) { urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsUserId", doAsUserId); } if (scopeGroupId > 0) { urlControlPanel = HttpUtil.addParameter(urlControlPanel, "doAsGroupId", scopeGroupId); } if (refererPlid > 0) { urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", refererPlid); } else if (plid > 0) { urlControlPanel = HttpUtil.addParameter(urlControlPanel, "refererPlid", plid); } themeDisplay.setURLControlPanel(urlControlPanel); PortletURL createAccountURL = new PortletURLImpl(request, PortletKeys.LOGIN, plid, PortletRequest.ACTION_PHASE); createAccountURL.setWindowState(WindowState.MAXIMIZED); createAccountURL.setPortletMode(PortletMode.VIEW); createAccountURL.setParameter("saveLastPath", "0"); createAccountURL.setParameter("struts_action", "/login/create_account"); themeDisplay.setURLCreateAccount(createAccountURL); String currentURL = PortalUtil.getCurrentURL(request); themeDisplay.setURLCurrent(currentURL); String urlHome = PortalUtil.getHomeURL(request); themeDisplay.setURLHome(urlHome); if (layout != null) { if (layout.isTypePortlet()) { boolean freeformLayout = layoutTypePortlet.getLayoutTemplateId().equals("freeform"); themeDisplay.setFreeformLayout(freeformLayout); boolean hasUpdateLayoutPermission = LayoutPermissionUtil.contains(permissionChecker, layout, ActionKeys.UPDATE); if (hasUpdateLayoutPermission) { themeDisplay.setShowAddContentIconPermission(true); if (!LiferayWindowState.isMaximized(request)) { themeDisplay.setShowAddContentIcon(true); } themeDisplay.setShowLayoutTemplatesIcon(true); themeDisplay.setURLAddContent("Liferay.LayoutConfiguration.toggle('" .concat(PortletKeys.LAYOUT_CONFIGURATION).concat("');")); themeDisplay.setURLLayoutTemplates("Liferay.LayoutConfiguration.showTemplates();"); } } boolean hasManageLayoutsPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.MANAGE_LAYOUTS); if (group.isUser()) { if ((layout.isPrivateLayout() && !PropsValues.LAYOUT_USER_PRIVATE_LAYOUTS_MODIFIABLE) || (layout.isPublicLayout() && !PropsValues.LAYOUT_USER_PUBLIC_LAYOUTS_MODIFIABLE)) { hasManageLayoutsPermission = false; } } if (hasManageLayoutsPermission) { themeDisplay.setShowPageSettingsIcon(true); PortletURL pageSettingsURL = new PortletURLImpl(request, PortletKeys.LAYOUT_MANAGEMENT, plid, PortletRequest.RENDER_PHASE); pageSettingsURL.setWindowState(WindowState.MAXIMIZED); pageSettingsURL.setPortletMode(PortletMode.VIEW); pageSettingsURL.setParameter("struts_action", "/layout_management/edit_pages"); if (layout.isPrivateLayout()) { pageSettingsURL.setParameter("tabs1", "private-pages"); } else { pageSettingsURL.setParameter("tabs1", "public-pages"); } pageSettingsURL.setParameter("redirect", currentURL); pageSettingsURL.setParameter("groupId", String.valueOf(scopeGroupId)); pageSettingsURL.setParameter("selPlid", String.valueOf(plid)); themeDisplay.setURLPageSettings(pageSettingsURL); } if (group.hasStagingGroup() && !group.isStagingGroup()) { themeDisplay.setShowAddContentIcon(false); themeDisplay.setShowLayoutTemplatesIcon(false); themeDisplay.setShowPageSettingsIcon(false); themeDisplay.setURLPublishToLive(null); } if (group.isControlPanel()) { themeDisplay.setShowPageSettingsIcon(false); themeDisplay.setURLPublishToLive(null); } // LEP-4987 if (group.isStaged() || group.isStagingGroup()) { boolean hasApproveProposalPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.APPROVE_PROPOSAL); boolean hasPublishStagingPermission = GroupPermissionUtil.contains(permissionChecker, scopeGroupId, ActionKeys.PUBLISH_STAGING); if (hasApproveProposalPermission || hasManageLayoutsPermission || hasPublishStagingPermission) { themeDisplay.setShowStagingIcon(true); } if (hasPublishStagingPermission) { PortletURL publishToLiveURL = new PortletURLImpl(request, PortletKeys.LAYOUT_MANAGEMENT, plid, PortletRequest.RENDER_PHASE); publishToLiveURL.setWindowState(LiferayWindowState.EXCLUSIVE); publishToLiveURL.setPortletMode(PortletMode.VIEW); publishToLiveURL.setParameter("struts_action", "/layout_management/export_pages"); if (layout.isPrivateLayout()) { publishToLiveURL.setParameter("tabs1", "private-pages"); } else { publishToLiveURL.setParameter("tabs1", "public-pages"); } publishToLiveURL.setParameter("pagesRedirect", currentURL); publishToLiveURL.setParameter("groupId", String.valueOf(scopeGroupId)); publishToLiveURL.setParameter("selPlid", String.valueOf(plid)); themeDisplay.setURLPublishToLive(publishToLiveURL); } } String myAccountNamespace = PortalUtil.getPortletNamespace(PortletKeys.MY_ACCOUNT); String myAccountRedirect = ParamUtil.getString(request, myAccountNamespace.concat("backURL"), currentURL); Group controlPanelGroup = GroupLocalServiceUtil.getGroup(companyId, GroupConstants.CONTROL_PANEL); long controlPanelPlid = LayoutLocalServiceUtil.getDefaultPlid(controlPanelGroup.getGroupId(), true); PortletURLImpl myAccountURL = new PortletURLImpl(request, PortletKeys.MY_ACCOUNT, controlPanelPlid, PortletRequest.RENDER_PHASE); myAccountURL.setWindowState(WindowState.MAXIMIZED); myAccountURL.setPortletMode(PortletMode.VIEW); myAccountURL.setRefererPlid(plid); myAccountURL.setParameter("struts_action", "/my_account/edit_user"); myAccountURL.setParameter("backURL", myAccountRedirect); themeDisplay.setURLMyAccount(myAccountURL); } if ((!user.isActive()) || (PrefsPropsUtil.getBoolean(companyId, PropsKeys.TERMS_OF_USE_REQUIRED) && !user.isAgreedToTermsOfUse())) { themeDisplay.setShowAddContentIcon(false); themeDisplay.setShowMyAccountIcon(false); themeDisplay.setShowPageSettingsIcon(false); } if (group.isLayoutPrototype()) { themeDisplay.setShowControlPanelIcon(false); themeDisplay.setShowHomeIcon(false); themeDisplay.setShowMyAccountIcon(false); themeDisplay.setShowPageSettingsIcon(true); themeDisplay.setShowPortalIcon(false); themeDisplay.setShowSignInIcon(false); themeDisplay.setShowSignOutIcon(false); themeDisplay.setShowStagingIcon(false); } themeDisplay.setURLPortal(portalURL.concat(contextPath)); String urlSignIn = mainPath.concat("/portal/login"); if (layout != null) { urlSignIn = HttpUtil.addParameter(urlSignIn, "p_l_id", layout.getPlid()); } themeDisplay.setURLSignIn(urlSignIn); themeDisplay.setURLSignOut(mainPath.concat("/portal/logout")); PortletURL updateManagerURL = new PortletURLImpl(request, PortletKeys.UPDATE_MANAGER, plid, PortletRequest.RENDER_PHASE); updateManagerURL.setWindowState(WindowState.MAXIMIZED); updateManagerURL.setPortletMode(PortletMode.VIEW); updateManagerURL.setParameter("struts_action", "/update_manager/view"); themeDisplay.setURLUpdateManager(updateManagerURL); request.setAttribute(WebKeys.THEME_DISPLAY, themeDisplay); // Parallel render boolean parallelRenderEnable = true; if (layout != null) { List<String> portletIds = layoutTypePortlet.getPortletIds(); if (portletIds.size() == 1) { String portletId = portletIds.get(0); Portlet portlet = PortletLocalServiceUtil.getPortletById(portletId); if ((portlet != null) && !portlet.isAjaxable()) { parallelRenderEnable = false; } } } Boolean parallelRenderEnableObj = Boolean .valueOf(ParamUtil.getBoolean(request, "p_p_parallel", parallelRenderEnable)); request.setAttribute(WebKeys.PORTLET_PARALLEL_RENDER, parallelRenderEnableObj); }
From source file:com.vangent.hieos.logbrowser.servlets.AuthenticationServlet.java
/** * //from w w w .ja v a 2 s. c o m * Entry point of the servlet */ public void doPost(HttpServletRequest req, HttpServletResponse res) { res.setContentType("text/xml"); HttpSession session = req.getSession(true); String passwordInput = req.getParameter("password"); String newPassword = req.getParameter("chgPassword"); String getIsAdmin = req.getParameter("isAdmin"); String logout = req.getParameter("logout"); String ipFrom = req.getRemoteAddr(); String company = null; try { InetAddress address = InetAddress.getByName(ipFrom); if (address instanceof Inet6Address) { if (address.isLoopbackAddress()) { ipFrom = "127.0.0.1"; } else { ipFrom = "null"; } } } catch (UnknownHostException e) { } if (ipFrom != null && !ipFrom.equals("null")) { Log log = new Log(); try { PreparedStatement selectCompanyName = null; Connection con = log.getConnection(); selectCompanyName = con.prepareStatement("SELECT company_name,email FROM ip where ip = ? ; "); selectCompanyName.setString(1, ipFrom); ResultSet result = selectCompanyName.executeQuery(); if (result.next()) { company = result.getString(1).replaceAll("'", """); } } catch (SQLException e) { e.printStackTrace(); } catch (LoggerException e) { e.printStackTrace(); } finally { try { log.closeConnection(); } catch (LoggerException ex) { Logger.getLogger(AuthenticationServlet.class.getName()).log(Level.SEVERE, null, ex); } } } String pageNumber = (String) session.getAttribute("page"); String numberResultsByPage = (String) session.getAttribute("numberResultsByPage"); session.setAttribute("isAdmin", true); // BHT (HACK). // DISABLED (BHT) // readFile(); if (passwordInput != null) { try { if (passwordRead.equals(passwordInput)) { session.setAttribute("isAdmin", true); if (newPassword != null) { FileWriter fstream; try { fstream = new FileWriter(passwordFile); BufferedWriter out = new BufferedWriter(fstream); out.write(newPassword); out.close(); res.getWriter() .write("<response isChanged='true' isAuthenticated='true' page ='" + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>"); } catch (IOException e) { try { res.getWriter().write("<response isChanged='false' page ='" + pageNumber + "' numberResultByPage='" + numberResultsByPage + "' ip='" + ipFrom + "' +" + " company='" + company + "' > " + e.getMessage() + "</response>"); } catch (IOException e1) { } } } else { res.getWriter().write("<response isAuthenticated='true' page ='" + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>"); } } else { res.getWriter().write("<response isAuthenticated='false' ip='" + ipFrom + "' page ='" + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>"); } } catch (Exception e) { } } else if (getIsAdmin != null && getIsAdmin.equals("get")) { try { Boolean isAuthenticated = (Boolean) session.getAttribute("isAdmin"); String sysType = (String) session.getAttribute("systemType"); if (sysType == null) { sysType = "new"; } if (isAuthenticated != null && isAuthenticated.booleanValue()) { res.getWriter().write("<response isAuthenticated='true' systemType='" + sysType + "' page ='" + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>"); /*} else if (authorizedIPs.contains(ipFrom)) { res.getWriter().write( "<response isAuthenticated='true'" + " page ='" + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>"); session.setAttribute("isAdmin", true); }*/ } else { res.getWriter() .write("<response isAuthenticated='false' ip='" + ipFrom + "' systemType ='" + sysType + "' company ='" + company + "' page ='" + pageNumber + "' numberResultByPage='" + numberResultsByPage + "'></response>"); } } catch (IOException e) { } } else if (logout != null && logout.equals("yes")) { session.invalidate(); try { res.getWriter().write("<response/>"); } catch (IOException e) { } } }
From source file:be.fedict.eid.idp.webapp.ProtocolExitServlet.java
@Override protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { LOG.debug("doGet"); HttpSession httpSession = request.getSession(); IdentityProviderProtocolService protocolService; try {//from w w w . j a va 2 s.c o m protocolService = ProtocolEntryServlet.getProtocolService(request); } catch (ServletException e) { httpSession.setAttribute(this.protocolErrorMessageSessionAttributeInitParam, e.getMessage()); response.sendRedirect(request.getContextPath() + this.protocolErrorPageInitParam); return; } String protocolId = protocolService.getId(); this.statistics.countAuthentication(protocolId); // get optional RP from Http Session RPEntity rp = (RPEntity) request.getSession().getAttribute(Constants.RP_SESSION_ATTRIBUTE); // get eID data from Http Session Identity identity = (Identity) httpSession .getAttribute(IdentityDataMessageHandler.IDENTITY_SESSION_ATTRIBUTE); Address address = (Address) httpSession.getAttribute(IdentityDataMessageHandler.ADDRESS_SESSION_ATTRIBUTE); String authenticatedIdentifier = (String) httpSession .getAttribute(AuthenticationDataMessageHandler.AUTHENTICATED_USER_IDENTIFIER_SESSION_ATTRIBUTE); X509Certificate authnCertificate = (X509Certificate) httpSession .getAttribute(IdentityDataMessageHandler.AUTHN_CERT_SESSION_ATTRIBUTE); byte[] photo = (byte[]) httpSession.getAttribute(IdentityDataMessageHandler.PHOTO_SESSION_ATTRIBUTE); // get userID + attributes String userId; if (null != identity) { userId = getUniqueId(identity.getNationalNumber(), rp); } else { userId = getUniqueId(authenticatedIdentifier, rp); } Map<String, Attribute> attributes = getAttributes(userId, identity, address, authnCertificate, photo); // add derived attributes for (IdentityProviderAttributeService attributeService : this.attributeServiceManager .getAttributeServices()) { attributeService.addAttribute(attributes); } // filter out attributes if RP was authenticated if (null != rp) { attributes = filterAttributes(rp, attributes); } // get RP SecretKey and/or PublicKey SecretKey secretKey = null; PublicKey publicKey = null; if (null != rp) { try { if (null != rp.getAttributeSecretKey()) { secretKey = CryptoUtil.getSecretKey(rp.getAttributeSecretAlgorithm(), rp.getAttributeSecretKey()); } if (null != rp.getAttributePublicKey()) { publicKey = CryptoUtil.getPublicKey(rp.getAttributePublicKey()); } } catch (Exception e) { LOG.error("protocol error: " + e.getMessage(), e); httpSession.setAttribute(this.protocolErrorMessageSessionAttributeInitParam, e.getMessage()); response.sendRedirect(request.getContextPath() + this.protocolErrorPageInitParam); return; } } // set encryption info if needed if (null != rp) { setEncryptionInfo(rp, attributes); } // set protocol specific URIs if possible for (Attribute attribute : attributes.values()) { attribute.setUri(getUri(protocolService.getId(), attribute.getUri())); } String targetURL = null; if (null != rp) { targetURL = rp.getTargetURL(); } // return protocol specific response ReturnResponse returnResponse; try { returnResponse = protocolService.handleReturnResponse(httpSession, userId, attributes, secretKey, publicKey, targetURL, request, response); } catch (Exception e) { LOG.error("protocol error: " + e.getMessage(), e); httpSession.setAttribute(this.protocolErrorMessageSessionAttributeInitParam, e.getMessage()); response.sendRedirect(request.getContextPath() + this.protocolErrorPageInitParam); return; } if (null != returnResponse) { /* * This means that the protocol service wants us to construct some * Browser POST response towards the Service Provider landing site. */ if (null == returnResponse.getActionUrl()) { LOG.error("No action URL specified"); httpSession.setAttribute(this.protocolErrorMessageSessionAttributeInitParam, "No action URL specified"); response.sendRedirect(request.getContextPath() + this.protocolErrorPageInitParam); return; } LOG.debug("constructing generic Browser POST response..."); httpSession.setAttribute(this.responseActionSessionAttributeInitParam, returnResponse.getActionUrl()); httpSession.setAttribute(this.responseAttributesSessionAttributeInitParam, returnResponse.getAttributes()); response.sendRedirect(request.getContextPath() + this.protocolResponsePostPageInitParam); return; } /* * Clean-up the session here as it is no longer used after this point. */ httpSession.invalidate(); }
From source file:org.joget.apps.app.controller.ConsoleWebController.java
@SuppressWarnings({ "unused", "unchecked", "rawtypes" }) @RequestMapping(value = "/console/profile/submit", method = RequestMethod.POST) public String profileSubmit(ModelMap model, HttpServletRequest request, HttpServletResponse response, @ModelAttribute("user") User user, BindingResult result) throws IOException, NoSuchAlgorithmException, InvalidKeySpecException { User currentUser = userDao.getUser(workflowUserManager.getCurrentUsername()); if (currentUser == null) { response.sendError(HttpServletResponse.SC_NOT_FOUND); return null; }//from w w w .j ava 2 s .co m Collection<String> errors = new ArrayList<String>(); Collection<String> passwordErrors = new ArrayList<String>(); boolean authenticated = false; if (!currentUser.getUsername().equals(user.getUsername())) { HttpSession session = request.getSession(false); if (session != null) { session.invalidate(); } } else { try { if (directoryManager.authenticate(currentUser.getUsername(), user.getOldPassword())) { authenticated = true; } } catch (Exception e) { } } UserSecurity us = DirectoryUtil.getUserSecurity(); if (!authenticated) { if (errors == null) { errors = new ArrayList<String>(); } errors.add(ResourceBundleUtil.getMessage("console.directory.user.error.label.authenticationFailed")); } else { if (us != null) { errors = us.validateUserOnProfileUpdate(user); } if (user.getPassword() != null && !user.getPassword().isEmpty() && us != null) { passwordErrors = us.validatePassword(user.getUsername(), user.getOldPassword(), user.getPassword(), user.getConfirmPassword()); } } if (!authenticated || (passwordErrors != null && !passwordErrors.isEmpty()) || (errors != null && !errors.isEmpty())) { model.addAttribute("passwordErrors", passwordErrors); model.addAttribute("errors", errors); model.addAttribute("user", user); model.addAttribute("timezones", TimeZoneUtil.getList()); String enableUserLocale = SetupManager.getSettingValue("enableUserLocale"); Map<String, String> localeStringList = new TreeMap<String, String>(); if (enableUserLocale != null && enableUserLocale.equalsIgnoreCase("true")) { String userLocale = SetupManager.getSettingValue("userLocale"); Collection<String> locales = new HashSet(); locales.addAll(Arrays.asList(userLocale.split(","))); Locale[] localeList = Locale.getAvailableLocales(); for (int x = 0; x < localeList.length; x++) { String code = localeList[x].toString(); if (locales.contains(code)) { localeStringList.put(code, code + " - " + localeList[x].getDisplayName(LocaleContextHolder.getLocale())); } } } model.addAttribute("enableUserLocale", enableUserLocale); model.addAttribute("localeStringList", localeStringList); if (us != null) { model.addAttribute("policies", us.passwordPolicies()); model.addAttribute("userProfileFooter", us.getUserProfileFooter(currentUser)); } else { model.addAttribute("policies", ""); model.addAttribute("userProfileFooter", ""); } return "console/profile"; } else if (currentUser.getUsername().equals(user.getUsername())) { currentUser.setFirstName(user.getFirstName()); currentUser.setLastName(user.getLastName()); currentUser.setEmail(user.getEmail()); currentUser.setTimeZone(user.getTimeZone()); currentUser.setLocale(user.getLocale()); UserSalt userSalt = userSaltDao.getUserSaltByUserId(currentUser.getUsername()); if (user.getPassword() != null && user.getConfirmPassword() != null && user.getPassword().length() > 0 && user.getPassword().equals(user.getConfirmPassword())) { if (us != null) { currentUser.setPassword(us.encryptPassword(user.getUsername(), user.getPassword())); } else { //currentUser.setPassword(StringUtil.md5Base16(user.getPassword())); HashSalt hashSalt = PasswordGeneratorUtil.createNewHashWithSalt(user.getPassword()); userSalt.setRandomSalt(hashSalt.getSalt()); currentUser.setPassword(hashSalt.getHash()); } currentUser.setConfirmPassword(user.getPassword()); } userDao.updateUser(currentUser); userSaltDao.updateUserSalt(userSalt); if (us != null) { us.updateUserProfilePostProcessing(currentUser); } } return "console/dialogClose"; }
From source file:com.mimp.controllers.main.java
@RequestMapping("/Contacto") public ModelAndView Contacto(ModelMap map, HttpSession session) { session.invalidate(); String pagina = "contacto"; return new ModelAndView(pagina, map); }
From source file:com.mimp.controllers.main.java
@RequestMapping("/salir") public ModelAndView Salir(ModelMap map, HttpSession session) { session.invalidate(); String pagina = "login"; return new ModelAndView(pagina, map); }
From source file:net.groupbuy.controller.shop.RegisterController.java
/** * ??/*from w w w . j a v a 2 s. com*/ */ @RequestMapping(value = "/submit", method = RequestMethod.POST) public @ResponseBody Message submit(String captchaId, String captcha, String username, String email, HttpServletRequest request, HttpServletResponse response, HttpSession session) { String password = rsaService.decryptParameter("enPassword", request); rsaService.removePrivateKey(request); if (!captchaService.isValid(CaptchaType.memberRegister, captchaId, captcha)) { return Message.error("shop.captcha.invalid"); } Setting setting = SettingUtils.get(); if (!setting.getIsRegisterEnabled()) { return Message.error("shop.register.disabled"); } if (!isValid(Member.class, "username", username, Save.class) || !isValid(Member.class, "password", password, Save.class) || !isValid(Member.class, "email", email, Save.class)) { return Message.error("shop.common.invalid"); } if (username.length() < setting.getUsernameMinLength() || username.length() > setting.getUsernameMaxLength()) { return Message.error("shop.common.invalid"); } if (password.length() < setting.getPasswordMinLength() || password.length() > setting.getPasswordMaxLength()) { return Message.error("shop.common.invalid"); } if (memberService.usernameDisabled(username) || memberService.usernameExists(username)) { return Message.error("shop.register.disabledExist"); } if (!setting.getIsDuplicateEmail() && memberService.emailExists(email)) { return Message.error("shop.register.emailExist"); } Member member = new Member(); List<MemberAttribute> memberAttributes = memberAttributeService.findList(); for (MemberAttribute memberAttribute : memberAttributes) { String parameter = request.getParameter("memberAttribute_" + memberAttribute.getId()); if (memberAttribute.getType() == Type.name || memberAttribute.getType() == Type.address || memberAttribute.getType() == Type.zipCode || memberAttribute.getType() == Type.phone || memberAttribute.getType() == Type.mobile || memberAttribute.getType() == Type.text || memberAttribute.getType() == Type.select) { if (memberAttribute.getIsRequired() && StringUtils.isEmpty(parameter)) { return Message.error("shop.common.invalid"); } member.setAttributeValue(memberAttribute, parameter); } else if (memberAttribute.getType() == Type.gender) { Gender gender = StringUtils.isNotEmpty(parameter) ? Gender.valueOf(parameter) : null; if (memberAttribute.getIsRequired() && gender == null) { return Message.error("shop.common.invalid"); } member.setGender(gender); } else if (memberAttribute.getType() == Type.birth) { try { Date birth = StringUtils.isNotEmpty(parameter) ? DateUtils.parseDate(parameter, CommonAttributes.DATE_PATTERNS) : null; if (memberAttribute.getIsRequired() && birth == null) { return Message.error("shop.common.invalid"); } member.setBirth(birth); } catch (ParseException e) { return Message.error("shop.common.invalid"); } } else if (memberAttribute.getType() == Type.area) { Area area = StringUtils.isNotEmpty(parameter) ? areaService.find(Long.valueOf(parameter)) : null; if (area != null) { member.setArea(area); } else if (memberAttribute.getIsRequired()) { return Message.error("shop.common.invalid"); } } else if (memberAttribute.getType() == Type.checkbox) { String[] parameterValues = request.getParameterValues("memberAttribute_" + memberAttribute.getId()); List<String> options = parameterValues != null ? Arrays.asList(parameterValues) : null; if (memberAttribute.getIsRequired() && (options == null || options.isEmpty())) { return Message.error("shop.common.invalid"); } member.setAttributeValue(memberAttribute, options); } } member.setUsername(username.toLowerCase()); member.setPassword(DigestUtils.md5Hex(password)); member.setEmail(email); member.setPoint(setting.getRegisterPoint()); member.setAmount(new BigDecimal(0)); member.setBalance(new BigDecimal(0)); member.setIsEnabled(true); member.setIsLocked(false); member.setLoginFailureCount(0); member.setLockedDate(null); member.setRegisterIp(request.getRemoteAddr()); member.setLoginIp(request.getRemoteAddr()); member.setLoginDate(new Date()); member.setSafeKey(null); member.setMemberRank(memberRankService.findDefault()); member.setFavoriteProducts(null); memberService.save(member); Cart cart = cartService.getCurrent(); if (cart != null && cart.getMember() == null) { cartService.merge(member, cart); WebUtils.removeCookie(request, response, Cart.ID_COOKIE_NAME); WebUtils.removeCookie(request, response, Cart.KEY_COOKIE_NAME); } Map<String, Object> attributes = new HashMap<String, Object>(); Enumeration<?> keys = session.getAttributeNames(); while (keys.hasMoreElements()) { String key = (String) keys.nextElement(); attributes.put(key, session.getAttribute(key)); } session.invalidate(); session = request.getSession(); for (Entry<String, Object> entry : attributes.entrySet()) { session.setAttribute(entry.getKey(), entry.getValue()); } session.setAttribute(Member.PRINCIPAL_ATTRIBUTE_NAME, new Principal(member.getId(), member.getUsername())); WebUtils.addCookie(request, response, Member.USERNAME_COOKIE_NAME, member.getUsername()); return Message.success("shop.register.success"); }