博客tuan-group
来源:互联网 发布:java字符串转date类型 编辑:程序博客网 时间:2024/05/16 14:01
package m.actions;
import groupon.commons.Constants;
import groupon.commons.SessionInCookie;
import groupon.commons.utils.CookieUtils;
import groupon.commons.utils.ServletUtils;
import groupon.modules.manager.models.Manager;
import groupon.modules.manager.service.ManagerService;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringUtils;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import com.opensymphony.xwork2.ActionSupport;
@Results( { @Result(name = ActionSupport.SUCCESS, type = "redirect", location = "/index.do") })
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 1264022987406584371L;
private HttpServletRequest request = ServletActionContext.getRequest();
private HttpServletResponse response = ServletActionContext.getResponse();
private String loginName;
private String loginPassword;
private ManagerService managerService;
@Override
public String execute() throws Exception {
if (ServletUtils.isGet(request)) {
return doGet();
} else if (ServletUtils.isPost(request)) {
validate();
if (hasActionErrors()) {
return INPUT;
}
return doPost();
}
return SUCCESS;
}
private String doPost() throws InterruptedException {
final Manager manager = managerService.selectManager(loginName);
if (manager == null
|| loginPassword.equals(manager.getPassword()) == false) {
addActionError("登录名或密码错误。");
Thread.sleep(5000);// 延迟5秒
}
if (hasActionErrors()) {
return INPUT;
}
login(manager, request, response, managerService);
return SUCCESS;
}
public void validate() {
if (StringUtils.isEmpty(loginName)) {
addActionError("请输入用户名");
} else if (StringUtils.isEmpty(loginPassword)) {
addActionError("请输入密码");
}
}
public static void login(Manager manager, HttpServletRequest request,
HttpServletResponse response, ManagerService managerService) {
// 设置session
int age = -1;// 默认关浏览器失效
SessionInCookie session = new SessionInCookie();
session.put(Constants.MANAGER_ID, manager.getManagerId());
session.put(Constants.MANAGER_LOGIN_IP, request.getRemoteAddr());
// 设置cookie
CookieUtils.addCookie(response, Constants.MANAGER_IN_COOKIE_KEY,
session.toString(), age);
CookieUtils.addCookie(response, Constants.COOKIE_PREVIOUS_MANAGER,
manager.getName());
// 记录日志
managerService.insertLoginLog(manager.getManagerId(), request
.getRemoteAddr(), ServletUtils.getRealIp(request));
}
private String doGet() {
String loginName = CookieUtils.getCookie(request,
Constants.COOKIE_PREVIOUS_MANAGER);
if (StringUtils.isEmpty(this.loginName)
&& StringUtils.isNotEmpty(loginName)) {
this.loginName = loginName;
}
return INPUT;
}
public String getLoginName() {
return loginName;
}
public void setLoginName(String loginName) {
this.loginName = loginName;
}
public String getLoginPassword() {
return loginPassword;
}
public void setLoginPassword(String loginPassword) {
this.loginPassword = loginPassword;
}
public void setManagerService(ManagerService managerService) {
this.managerService = managerService;
}
}
logout
@Results( { @Result(name = ActionSupport.SUCCESS, type = "redirect", location = "/login.do") })
public class LoginOutAction extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = -4971481210126205812L;
private HttpServletResponse response = ServletActionContext.getResponse();
@Override
public String execute() throws Exception {
CookieUtils.removeCookie(response, Constants.MANAGER_IN_COOKIE_KEY);
return SUCCESS;
}
package grouponmanage.commons.interceptors;
import groupon.commons.Constants;
import groupon.commons.SessionInCookie;
import groupon.commons.annontations.RequireLogin;
import groupon.commons.interceptors.CurrentManagerAware;
import groupon.commons.utils.AnnontationUtils;
import groupon.commons.utils.CookieUtils;
import groupon.modules.manager.models.Manager;
import groupon.modules.manager.service.ManagerService;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;
import org.springframework.dao.EmptyResultDataAccessException;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
* @author Jonney
*/
public class ManagerLoginInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = 5215120501853966014L;
protected static final Log log = LogFactory
.getLog(ManagerLoginInterceptor.class);
private ManagerService managerService;
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
*/
public void destroy() {
}
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#init()
*/
public void init() {
}
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext();
final HttpServletRequest request = (HttpServletRequest) context
.get(StrutsStatics.HTTP_REQUEST);
final SessionInCookie session = new SessionInCookie(CookieUtils
.getCookie(request, Constants.MANAGER_IN_COOKIE_KEY));
final ActionProxy proxy = invocation.getProxy();
final Object action = invocation.getAction();
Integer currentManagerId = null;
if (session.get(Constants.MANAGER_ID) != null) {
String loginIp = session.get(Constants.MANAGER_LOGIN_IP);
String ip = request.getRemoteAddr();
if (StringUtils.equals(loginIp, ip)) {
currentManagerId = NumberUtils.toInt(session
.get(Constants.MANAGER_ID));
}
}
final RequireLogin require = AnnontationUtils.getFromMethedOrType(
RequireLogin.class, action, proxy.getMethod());
if (require != null && currentManagerId == null) {
if (request.getMethod().equalsIgnoreCase("post")) {
String refer = request.getHeader("refer");// 得到的是http://127.0.0.1/login.do
request.setAttribute("forward", refer);
} else {
String forward = request.getRequestURI();// 得到的是/index.do
if (StringUtils.isNotEmpty(request.getQueryString())) {// 当参数不为空的时候
forward += "?" + request.getQueryString();
}
request.setAttribute("forward", forward);
}
if (action instanceof ActionSupport) {
((ActionSupport) action)
.addActionError("您还没有登录,或登录已经超时,请登录后继续操作。");
}
return "login";
} else if (currentManagerId != null) {
if (request.getAttribute(Constants.REQUEST_CURRENT_MANAGER_ID) == null) {
request.setAttribute(Constants.REQUEST_CURRENT_MANAGER_ID,
currentManagerId);
}
// 获取并注入当前Manager
Manager currentManager = null;
try {
currentManager = (Manager) request
.getAttribute(Constants.REQUEST_CURRENT_MANAGER);
if (currentManager == null) {
currentManager = managerService
.selectManager(currentManagerId);
request.setAttribute(Constants.REQUEST_CURRENT_MANAGER,
currentManager);
}
} catch (EmptyResultDataAccessException e) {
return ActionSupport.LOGIN;
}
if (action instanceof CurrentManagerAware) {
CurrentManagerAware aware = (CurrentManagerAware) action;
aware.setCurrentManager(currentManager);
}
}
return invocation.invoke();
}
public void setManagerService(ManagerService managerService) {
this.managerService = managerService;
}
}
package grouponmanage.commons.interceptors;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author Jonney
*/
@Target( { ElementType.METHOD, ElementType.TYPE })
@Retention(RetentionPolicy.RUNTIME)
public @interface Secure {
int value();
}
package groupon.commons;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import java.util.Set;
import org.apache.commons.lang.StringUtils;
public class SessionInCookie implements Map<String, String> {
private Map<String, String> session;
private static final String PASSWORD = "i1swgovpn9wh";
public SessionInCookie() {
session = new HashMap<String, String>();
}
public SessionInCookie(String cookie) {
this();
if (StringUtils.isEmpty(cookie)) {
return;
}
cookie = DesCrypto.decrypt(cookie, PASSWORD);
if (StringUtils.isEmpty(cookie)) {
return;
}
String[] lines = StringUtils.split(cookie, '\n');
for (String line : lines) {
String key = StringUtils.substringBefore(line, "=");
String value = StringUtils.substringAfter(line, "=");
session.put(key, value);
}
}
public String toString() {
StringBuilder sb = new StringBuilder();
for (String key : session.keySet()) {
sb.append(key).append("=");
String value = session.get(key);
if (value != null) {
sb.append(value);
}
sb.append('\n');
}
return DesCrypto.encrypt(sb.toString(), PASSWORD);
}
@Override
public void clear() {
session.clear();
}
@Override
public boolean containsKey(Object key) {
return session.containsKey(key);
}
@Override
public boolean containsValue(Object value) {
return session.containsValue(value);
}
@Override
public Set<java.util.Map.Entry<String, String>> entrySet() {
return session.entrySet();
}
@Override
public String get(Object key) {
return session.get(key);
}
@Override
public boolean isEmpty() {
return session.isEmpty();
}
@Override
public Set<String> keySet() {
return session.keySet();
}
@Override
public String put(String key, String value) {
return session.put(key, value);
}
public String put(String key, Object value) {
if (value != null) {
return put(key, value.toString());
} else {
return session.put(key, "");
}
}
@Override
public void putAll(Map<? extends String, ? extends String> m) {
session.putAll(m);
}
@Override
public String remove(Object key) {
return session.remove(key);
}
@Override
public int size() {
return session.size();
}
@Override
public Collection<String> values() {
return session.values();
}
public static void main(String[] args) {
SessionInCookie session = new SessionInCookie();
session.put("111", "11111");
session.put("222", "22222");
System.out.println(session.toString());
session = new SessionInCookie("fb6c8148eb5e0b9d27cbbe0d5381060a1ea3276f8d73f73a");
for (String key : session.keySet()) {
System.out.print(key);
System.out.print("=");
System.out.println(session.get(key));
}
}
}
package groupon.commons.interceptors;
import groupon.commons.Constants;
import groupon.commons.SessionInCookie;
import groupon.commons.annontations.RequireLogin;
import groupon.commons.utils.AnnontationUtils;
import groupon.commons.utils.CookieUtils;
import groupon.modules.seller.models.Seller;
import groupon.modules.seller.service.SellerService;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
* @author Jonney
*/
public class SellerLoginInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = -3197902679898874068L;
protected static final Log log = LogFactory.getLog(SellerLoginInterceptor.class);
private SellerService sellerService;
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
*/
public void destroy() {
}
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#init()
*/
public void init() {
}
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext();
final ActionProxy proxy = invocation.getProxy();
final Object action = invocation.getAction();
final HttpServletRequest request = (HttpServletRequest) context
.get(StrutsStatics.HTTP_REQUEST);
final SessionInCookie session = new SessionInCookie(CookieUtils.getCookie(request,
Constants.SELLER_IN_COOKIE_KEY));
Integer currentSellerId = null;
if (session.get(Constants.SELLER_ID) != null) {
String loginIp = session.get(Constants.SELLER_LOGIN_IP);
String ip = request.getRemoteAddr();
if (StringUtils.equals(loginIp, ip) == false) {
// ip不一致,不能继续访问
} else {
currentSellerId = NumberUtils.toInt(session.get(Constants.SELLER_ID));
}
}
final RequireLogin require = AnnontationUtils.getFromMethedOrType(RequireLogin.class,
action, proxy.getMethod());
if (require != null && currentSellerId == null) {
if (request.getMethod().equalsIgnoreCase("post")) {
String referer = request.getHeader("referer");
request.setAttribute("forward", referer);
} else {
String forward = request.getRequestURI();
if (StringUtils.isNotEmpty(request.getQueryString())) {
forward += "?" + request.getQueryString();
}
request.setAttribute("forward", forward);
}
if (action instanceof ActionSupport) {
((ActionSupport) action).addActionError("您还没有登录,或是已经登录超时,请登录后继续操作。");
}
return Action.LOGIN;
} else if (currentSellerId != null) {
if (request.getAttribute(Constants.REQUEST_CURRENT_SELLER_ID) == null) {
request.setAttribute(Constants.REQUEST_CURRENT_SELLER_ID, currentSellerId);
}
Seller currentSeller = (Seller) request.getAttribute(Constants.REQUEST_CURRENT_SELLER);
if (currentSeller == null) {
currentSeller = sellerService.selectSeller(currentSellerId);
request.setAttribute(Constants.REQUEST_CURRENT_SELLER, currentSeller);
}
// 获取并注入当前Seller
if (action instanceof CurrentSellerAware) {
((CurrentSellerAware) action).setCurrentSeller(currentSeller);
}
}
return invocation.invoke();
}
public void setSellerService(SellerService sellerService) {
this.sellerService = sellerService;
}
}
package groupon.commons.interceptors;
import groupon.commons.Constants;
import groupon.commons.SessionInCookie;
import groupon.commons.annontations.RequireLogin;
import groupon.commons.utils.AnnontationUtils;
import groupon.commons.utils.CookieUtils;
import groupon.modules.seller.models.Seller;
import groupon.modules.seller.service.SellerService;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
* @author Jonney
*/
public class SellerLoginInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = -3197902679898874068L;
protected static final Log log = LogFactory.getLog(SellerLoginInterceptor.class);
private SellerService sellerService;
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
*/
public void destroy() {
}
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#init()
*/
public void init() {
}
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext();
final ActionProxy proxy = invocation.getProxy();
final Object action = invocation.getAction();
final HttpServletRequest request = (HttpServletRequest) context
.get(StrutsStatics.HTTP_REQUEST);
final SessionInCookie session = new SessionInCookie(CookieUtils.getCookie(request,
Constants.SELLER_IN_COOKIE_KEY));
Integer currentSellerId = null;
if (session.get(Constants.SELLER_ID) != null) {
String loginIp = session.get(Constants.SELLER_LOGIN_IP);
String ip = request.getRemoteAddr();
if (StringUtils.equals(loginIp, ip) == false) {
// ip不一致,不能继续访问
} else {
currentSellerId = NumberUtils.toInt(session.get(Constants.SELLER_ID));
}
}
final RequireLogin require = AnnontationUtils.getFromMethedOrType(RequireLogin.class,
action, proxy.getMethod());
if (require != null && currentSellerId == null) {
if (request.getMethod().equalsIgnoreCase("post")) {
String referer = request.getHeader("referer");
request.setAttribute("forward", referer);
} else {
String forward = request.getRequestURI();
if (StringUtils.isNotEmpty(request.getQueryString())) {
forward += "?" + request.getQueryString();
}
request.setAttribute("forward", forward);
}
if (action instanceof ActionSupport) {
((ActionSupport) action).addActionError("您还没有登录,或是已经登录超时,请登录后继续操作。");
}
return Action.LOGIN;
} else if (currentSellerId != null) {
if (request.getAttribute(Constants.REQUEST_CURRENT_SELLER_ID) == null) {
request.setAttribute(Constants.REQUEST_CURRENT_SELLER_ID, currentSellerId);
}
Seller currentSeller = (Seller) request.getAttribute(Constants.REQUEST_CURRENT_SELLER);
if (currentSeller == null) {
currentSeller = sellerService.selectSeller(currentSellerId);
request.setAttribute(Constants.REQUEST_CURRENT_SELLER, currentSeller);
}
// 获取并注入当前Seller
if (action instanceof CurrentSellerAware) {
((CurrentSellerAware) action).setCurrentSeller(currentSeller);
}
}
return invocation.invoke();
}
public void setSellerService(SellerService sellerService) {
this.sellerService = sellerService;
}
}
package groupon.commons;
import java.util.Arrays;
import java.util.List;
public class Constants {
private Constants() {
// 外部不可以实例化此类
}
/**
* SessionInCookie在cookie里的键名
*/
public static final String SESSION_IN_COOKIE_KEY = "session";
/**
* 当前登录userId在session的键名
*/
public static final String SESSION_CURRENT_USER = "currentUserId";
/**
* 当前登录时间在session的键名
*/
public static final String SESSION_LOGIN_TIME = "loginTime";
/**
* 当前登录IP在session的键名
*/
public static final String SESSION_LOGIN_IP = "loginIp";
/**
* 当前session的创建时间
*/
public static final String SESSION_CREATE_TIME = "createTime";
/**
* 是否记住我
*/
public static final String SESSION_REMEMBER_ME = "rememberMe";
/**
* 上一次登陆的邮箱地址保存在cookie的键名
*/
public static final String COOKIE_PREVIOUS_EMAIL = "previousEmail";
/**
* 当前用户的userId
*/
public static final String COOKIE_USER_ID = "userId";
public static final String COOKIE_SID = "sid";
public static final String REQUEST_CURRENT_USER_ID = "currentUserId";
public static final String REQUEST_CURRENT_USER_CORE = "currentUserCore";
/**
* 购物车在cookie里的键名
*/
public static final String CART_IN_COOKIE_KEY = "cart";
public static final String CART_DEAL_ID = "dealId";
public static final String CART_QUANTITY = "quantity";
public static final String CART_MOBILE = "mobile";
public static final String CART_GIFT_CARD_CODE = "giftCardCode";
/**
* 商家的登录信息
*/
public static final String SELLER_IN_COOKIE_KEY = "seller";
public static final String SELLER_ID = "sellerId";
public static final String SELLER_LOGIN_IP = "sellerLoginIp";
public static final String REQUEST_CURRENT_SELLER_ID = "currentSellerId";
public static final String REQUEST_CURRENT_SELLER = "currentSeller";
public static final String COOKIE_PREVIOUS_SELLER = "previousSeller";
/**
* 珍惜大厅登录信息
*/
public static final String MANAGER_IN_COOKIE_KEY="manager";
public static final String MANAGER_ID="managerId";
public static final String MANAGER_LOGIN_IP="managerLoginIp";
public static final String REQUEST_CURRENT_MANAGER_ID="currentManagerId";
public static final String REQUEST_CURRENT_MANAGER="currentManager";
public static final String COOKIE_PREVIOUS_MANAGER="previousManager";
/**
* 邀请信息
*/
public static final String REFER_IN_COOKIE_KEY = "r";
public static final String REFER_SOURCE = "registerFrom";
public static final String REFER_USER_ID = "referUserId";
public static final String REFER_TIME = "referTime";
public static final String REFER_ZHENAI_ID = "zhenaiId";
/** 答疑板块(答疑) */
public static final int CONSULTATIONS_TYPE = 1;
/** 答疑板块(转让求购) */
public static final int EXCHANGES_TYPE = 2;
/** 答疑板块(显示在前台) */
public static final int CONSULTATIONS_IS_SHOW = 1;
/** 答疑板块(不显示在前台) */
public static final int CONSULTATIONS_NOT_SHOW = 0;
public static final String EXCHANGES_TYPE_STR = "exchanges";
public static final List<String> hostList = Arrays.asList("139", "163", "gmail", "live", "qq",
"right", "sina", "sohu", "yahoo");
public static final String ENCRYPT_KEY = "&^45$%@#(57hj)U*";
public static final int SMS_SUBCRIBE_INIT = 0;
public static final int SMS_SUBCRIBE_SUCCESS = 1;
public static final int SMS_SUBCRIBE_CANCEL = 2;
public static final String SMS_TYPE_SUBSCRIBE = "DY";
public static final String SMS_TYPE_CANCEL = "QX";
/** 重发验证的次数限制 */
public static final int CAPTCHA_RESEND_MAX = 3;
}
package groupon.commons.interceptors;
import groupon.commons.Constants;
import groupon.commons.SessionInCookie;
import groupon.commons.annontations.RequireLogin;
import groupon.commons.utils.AnnontationUtils;
import groupon.commons.utils.CookieUtils;
import groupon.modules.seller.models.Seller;
import groupon.modules.seller.service.SellerService;
import javax.servlet.http.HttpServletRequest;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
* @author Jonney
*/
public class SellerLoginInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = -3197902679898874068L;
protected static final Log log = LogFactory.getLog(SellerLoginInterceptor.class);
private SellerService sellerService;
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
*/
public void destroy() {
}
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#init()
*/
public void init() {
}
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext();
final ActionProxy proxy = invocation.getProxy();
final Object action = invocation.getAction();
final HttpServletRequest request = (HttpServletRequest) context
.get(StrutsStatics.HTTP_REQUEST);
final SessionInCookie session = new SessionInCookie(CookieUtils.getCookie(request,
Constants.SELLER_IN_COOKIE_KEY));
Integer currentSellerId = null;
if (session.get(Constants.SELLER_ID) != null) {
String loginIp = session.get(Constants.SELLER_LOGIN_IP);
String ip = request.getRemoteAddr();
if (StringUtils.equals(loginIp, ip) == false) {
// ip不一致,不能继续访问
} else {
currentSellerId = NumberUtils.toInt(session.get(Constants.SELLER_ID));
}
}
final RequireLogin require = AnnontationUtils.getFromMethedOrType(RequireLogin.class,
action, proxy.getMethod());
if (require != null && currentSellerId == null) {
if (request.getMethod().equalsIgnoreCase("post")) {
String referer = request.getHeader("referer");
request.setAttribute("forward", referer);
} else {
String forward = request.getRequestURI();
if (StringUtils.isNotEmpty(request.getQueryString())) {
forward += "?" + request.getQueryString();
}
request.setAttribute("forward", forward);
}
if (action instanceof ActionSupport) {
((ActionSupport) action).addActionError("您还没有登录,或是已经登录超时,请登录后继续操作。");
}
return Action.LOGIN;
} else if (currentSellerId != null) {
if (request.getAttribute(Constants.REQUEST_CURRENT_SELLER_ID) == null) {
request.setAttribute(Constants.REQUEST_CURRENT_SELLER_ID, currentSellerId);
}
Seller currentSeller = (Seller) request.getAttribute(Constants.REQUEST_CURRENT_SELLER);
if (currentSeller == null) {
currentSeller = sellerService.selectSeller(currentSellerId);
request.setAttribute(Constants.REQUEST_CURRENT_SELLER, currentSeller);
}
// 获取并注入当前Seller
if (action instanceof CurrentSellerAware) {
((CurrentSellerAware) action).setCurrentSeller(currentSeller);
}
}
return invocation.invoke();
}
public void setSellerService(SellerService sellerService) {
this.sellerService = sellerService;
}
}
package groupon.commons.interceptors;
import groupon.commons.Constants;
import groupon.commons.SessionInCookie;
import groupon.commons.annontations.RequireLogin;
import groupon.commons.utils.AnnontationUtils;
import groupon.commons.utils.CookieUtils;
import groupon.commons.utils.ServletUtils;
import groupon.modules.account.models.UserCore;
import groupon.modules.account.service.UserService;
import java.util.Calendar;
import java.util.Date;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.BooleanUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.apache.commons.lang.time.DateUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.struts2.StrutsStatics;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionInvocation;
import com.opensymphony.xwork2.ActionProxy;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.interceptor.AbstractInterceptor;
/**
* @author Jonney
*/
public class UserLoginInterceptor extends AbstractInterceptor {
private static final long serialVersionUID = -3197902679898874068L;
protected static final Log log = LogFactory.getLog(UserLoginInterceptor.class);
private UserService userService;
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#destroy()
*/
public void destroy() {
}
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#init()
*/
public void init() {
}
/**
* @see com.opensymphony.xwork2.interceptor.Interceptor#intercept(com.opensymphony.xwork2.ActionInvocation)
*/
public String intercept(ActionInvocation invocation) throws Exception {
final ActionContext context = invocation.getInvocationContext();
final ActionProxy proxy = invocation.getProxy();
final Object action = invocation.getAction();
final HttpServletRequest request = (HttpServletRequest) context
.get(StrutsStatics.HTTP_REQUEST);
final HttpServletResponse response = (HttpServletResponse) context
.get(StrutsStatics.HTTP_RESPONSE);
final SessionInCookie session = new SessionInCookie(CookieUtils.getCookie(request,
Constants.SESSION_IN_COOKIE_KEY));
Long currentUserId = null;
if (session.get(Constants.SESSION_CURRENT_USER) != null) {
// String loginIp = session.get(Constants.SESSION_LOGIN_IP);
String ip = request.getRemoteAddr();
currentUserId = NumberUtils.toLong(session.get(Constants.SESSION_CURRENT_USER));
long loginTime = NumberUtils.toLong(session.get(Constants.SESSION_LOGIN_TIME));
boolean rememberMe = BooleanUtils.toBoolean(session.get(Constants.SESSION_REMEMBER_ME));
Date now = new Date();
Boolean updatedLoginTime = (Boolean) request
.getAttribute("UserLoginInterceptor.updatedLoginTime");
if (updatedLoginTime != null && updatedLoginTime == true) {
// 如果已经更新过了,不用再次更新
} else if (rememberMe && loginTime < DateUtils.truncate(now, Calendar.DATE).getTime()) {
// 如果用户选择了“记住我”,每天算一次登录
long createTime = NumberUtils.toLong(session.get(Constants.SESSION_CREATE_TIME));
session.put(Constants.SESSION_LOGIN_TIME, now.getTime());
long age = createTime + (30 * 24 * 60 * 60 * 1000L) - now.getTime();// 记住我的有效期是30天
CookieUtils.addCookie(response, Constants.SESSION_IN_COOKIE_KEY,
session.toString(), (int) (age / 1000));
userService.insertLoginLog(currentUserId, ip, ServletUtils.getRealIp(request));
request.setAttribute("UserLoginInterceptor.updatedLoginTime", true);
}
}
final RequireLogin require = AnnontationUtils.getFromMethedOrType(RequireLogin.class,
action, proxy.getMethod());
if (require != null && currentUserId == null) {
if (request.getMethod().equalsIgnoreCase("post")) {
String referer = request.getHeader("referer");
request.setAttribute("forward", referer);
} else {
String forward = request.getRequestURI();
if (StringUtils.isNotEmpty(request.getQueryString())) {
forward += "?" + request.getQueryString();
}
request.setAttribute("forward", forward);
}
if (action instanceof ActionSupport) {
((ActionSupport) action).addActionError("您还没有登录,或是已经登录超时,请登录后继续操作。");
}
return Action.LOGIN;
} else if (currentUserId != null) {
if (request.getAttribute(Constants.REQUEST_CURRENT_USER_ID) == null) {
request.setAttribute(Constants.REQUEST_CURRENT_USER_ID, currentUserId);
}
UserCore currentUserCore = (UserCore) request
.getAttribute(Constants.REQUEST_CURRENT_USER_CORE);
if (currentUserCore == null) {
currentUserCore = userService.selectUserCoreById(currentUserId);
request.setAttribute(Constants.REQUEST_CURRENT_USER_CORE, currentUserCore);
}
// 获取并注入当前UserCore
if (action instanceof CurrentUserCoreAware) {
((CurrentUserCoreAware) action).setCurrentUserCore(currentUserCore);
}
}
return invocation.invoke();
}
public void setUserService(UserService userService) {
this.userService = userService;
}
}
package groupon.commons;
import java.io.UnsupportedEncodingException;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
import java.security.spec.KeySpec;
import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.PBEKeySpec;
import javax.crypto.spec.PBEParameterSpec;
import org.apache.commons.codec.DecoderException;
import org.apache.commons.codec.binary.Hex;
public class DesCrypto {
// 8-byte Salt
private static final byte[] salt = { (byte) 0xa9, (byte) 0x9a, (byte) 0xb8, (byte) 0x32,
(byte) 0x59, (byte) 0x45, (byte) 0xc3, (byte) 0x13 };
// Iteration count
private static final int iterationCount = 15;
private static Cipher getCipher(int mod, String password) throws InvalidKeySpecException,
NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException,
InvalidAlgorithmParameterException {
KeySpec keySpec = new PBEKeySpec(password.toCharArray(), salt, iterationCount);
SecretKey key = SecretKeyFactory.getInstance("PBEWithMD5AndDES").generateSecret(keySpec);
// Prepare the parameter to the ciphers
AlgorithmParameterSpec paramSpec = new PBEParameterSpec(salt, iterationCount);
Cipher cipher = Cipher.getInstance(key.getAlgorithm());
cipher.init(mod, key, paramSpec);
return cipher;
}
public static String encrypt(String str, String password) {
try {
// Encode the string into bytes using utf-8
byte[] utf8 = str.getBytes("utf-8");
// Encrypt
byte[] enc = getCipher(Cipher.ENCRYPT_MODE, password).doFinal(utf8);
// Encode bytes to base64 to get a string
return new String(Hex.encodeHex(enc));
} catch (BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException(e);
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
throw new RuntimeException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new RuntimeException(e);
}
return null;
}
public static String decrypt(String str, String password) {
try {
// Decode base64 to get bytes
byte[] dec = Hex.decodeHex(str.toCharArray());
// Decrypt
byte[] utf8 = getCipher(Cipher.DECRYPT_MODE, password).doFinal(dec);
// Decode using utf-8
return new String(utf8, "utf-8");
} catch (BadPaddingException e) {
} catch (IllegalBlockSizeException e) {
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
} catch (NoSuchPaddingException e) {
throw new RuntimeException(e);
} catch (InvalidKeyException e) {
throw new RuntimeException(e);
} catch (InvalidKeySpecException e) {
throw new RuntimeException(e);
} catch (InvalidAlgorithmParameterException e) {
throw new RuntimeException(e);
} catch (DecoderException e) {
}
return null;
}
public static void main(String[] args) throws NoSuchAlgorithmException {
String result = encrypt("12345678", "000000");
System.out.println(result);
System.out.println(decrypt(result, "000000"));
}
}
package groupon.actions.account;
import groupon.commons.Constants;
import groupon.commons.SessionInCookie;
import groupon.commons.actionmapper.ParamNames;
import groupon.commons.interceptors.CurrentUserCoreAware;
import groupon.commons.utils.CookieUtils;
import groupon.commons.utils.ServletUtils;
import groupon.commons.validation.MobileValidator;
import groupon.modules.account.events.UserLoginEvent;
import groupon.modules.account.models.UserCore;
import groupon.modules.account.models.UserRegister;
import groupon.modules.account.models.UserUnactived;
import groupon.modules.account.service.MobileCaptchaService;
import groupon.modules.account.service.UserService;
import groupon.modules.account.utils.VerifyCodeUtils;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.lang.StringEscapeUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.validator.EmailValidator;
import org.apache.struts2.ServletActionContext;
import org.apache.struts2.convention.annotation.Result;
import org.apache.struts2.convention.annotation.Results;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionSupport;
@ParamNames("email")
@Results( {
@Result(name = ActionSupport.SUCCESS, type = "redirect", location = "${forward}"),
@Result(name = "signuped", type = "redirect", location = "/account/signuped?email=${encodedEmail}"),
@Result(name = "mobileCaptcha", type = "redirect", location = "/account/mobile-captcha/${mobileCode}"),
@Result(name = "home", type = "redirect", location = "/") })
public class LoginAction extends ActionSupport implements ApplicationContextAware,
CurrentUserCoreAware {
private static final long serialVersionUID = -4152827392535666154L;
private HttpServletRequest request = ServletActionContext.getRequest();
private HttpServletResponse response = ServletActionContext.getResponse();
private ApplicationContext spring;
private UserService userService;
private UserCore currentUserCore;
private MobileCaptchaService mobileCaptchaService;
private String forward;
private String email;
private String password;
private boolean rememberMe;
private String mobileCode;
@Override
public String execute() throws Exception {
if (currentUserCore != null) {
return "home";
}
if (ServletUtils.isGet(request)) {
return doGet();
} else if (ServletUtils.isPost(request)) {
validate();
if (hasActionErrors()) {
return INPUT;
}
return doPost();
}
return NONE;
}
private String doGet() {
if (EmailValidator.getInstance().isValid(this.email) == false) {
this.email = null;
}
String email = CookieUtils.getCookie(request, Constants.COOKIE_PREVIOUS_EMAIL);
if (StringUtils.isEmpty(this.email) && StringUtils.isNotEmpty(email)) {
this.email = email;
}
return INPUT;
}
@Override
public void validate() {
if (StringUtils.isEmpty(email)) {
addActionError("请填写Email或手机");
} else if ((StringUtils.contains(email, '@') && EmailValidator.getInstance().isValid(email) == false)
|| (StringUtils.contains(email, '@') == false && StringUtils.isNumeric(email) == false)) {
addActionError("请填写正确格式的Email或手机");
} else if (StringUtils.isEmpty(password)) {
addActionError("请填写密码");
}
}
private String doPost() {
UserRegister userRegister = userService.selectUserRegisterByEmail(email);
if (userRegister == null) {
UserUnactived userUnactived = userService.selectUserUnactivedByEmail(email);
if (userUnactived != null && StringUtils.equals(userUnactived.getPassword(), password)) {
if (MobileValidator.isValid(email)) {
mobileCaptchaService.sendCaptcha(email);
mobileCode = VerifyCodeUtils.mergeVerifyCode(email, "");
return "mobileCaptcha";
} else {
return "signuped";
}
} else if (userUnactived != null) {
addActionError("密码错误");
} else {
if (StringUtils.contains(email, '@')) {
addActionError("邮箱地址 " + StringEscapeUtils.escapeHtml(email) + " 不存在。");
} else {
addActionError("手机 " + StringEscapeUtils.escapeHtml(email) + " 不存在。");
}
}
} else if (StringUtils.equals(userRegister.getPassword(), password) == false) {
addActionError("密码错误");
try {
Thread.sleep(2000);// 如果密码错误,等待2秒钟
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
} else if (userRegister.getLocked() > 0) {
addActionError("此账号处于冻结状态,不能登录。");
}
if (hasActionErrors()) {
return INPUT;
}
login(userRegister, rememberMe, request, response, userService, spring, this);
return SUCCESS;
}
public static void login(UserRegister userRegister, boolean rememberMe,
HttpServletRequest request, HttpServletResponse response, UserService userService,
ApplicationContext spring, Action source) {
// 设置session
int age = -1;// 默认关浏览器失效
SessionInCookie session = new SessionInCookie();
session.put(Constants.SESSION_CURRENT_USER, userRegister.getUserId());
// 不管登录时是否选择了“记住我”,登录时间每天更新一次
long nowTime = System.currentTimeMillis();
session.put(Constants.SESSION_LOGIN_TIME, nowTime);
session.put(Constants.SESSION_LOGIN_IP, request.getRemoteAddr());
session.put(Constants.SESSION_CREATE_TIME, nowTime);
if (rememberMe) {
session.put(Constants.SESSION_REMEMBER_ME, rememberMe);
age = 30 * 24 * 60 * 60;// 记住30天
}
// 设置cookie
CookieUtils.addCookie(response, Constants.SESSION_IN_COOKIE_KEY, session.toString(), age);
CookieUtils.addCookie(response, Constants.COOKIE_USER_ID, String.valueOf(userRegister
.getUserId()), age);
CookieUtils.addCookie(response, Constants.COOKIE_PREVIOUS_EMAIL, userRegister.getEmail());
CookieUtils.removeCookie(response, Constants.REFER_IN_COOKIE_KEY);
// 记录日志
userService.insertLoginLog(userRegister.getUserId(), request.getRemoteAddr(), ServletUtils
.getRealIp(request));
// 发布登录事件,有什么新代码可以写到监听器里面
spring.publishEvent(new UserLoginEvent(source, userRegister));
}
public String getEmail() {
return email;
}
public String getEncodedEmail() {
if (email == null) {
return null;
}
try {
return URLEncoder.encode(email, "utf-8");
} catch (UnsupportedEncodingException e) {
throw new RuntimeException(e);
}
}
public void setEmail(String email) {
this.email = StringUtils.trim(email);
}
public void setPassword(String password) {
this.password = password;
}
public boolean isRememberMe() {
return rememberMe;
}
public void setRememberMe(boolean rememberMe) {
this.rememberMe = rememberMe;
}
public void setUserService(UserService userService) {
this.userService = userService;
}
@Override
public void setApplicationContext(ApplicationContext spring) throws BeansException {
this.spring = spring;
}
public String getForward() {
// TODO 检查目的地址是否安全
// TODO 跳到用户所在的城市
if (StringUtils.isEmpty(forward)) {
return "/";
}
return forward;
}
public void setForward(String forward) {
this.forward = forward;
}
@Override
public void setCurrentUserCore(UserCore currentUserCore) {
this.currentUserCore = currentUserCore;
}
public String getMobileCode() {
return mobileCode;
}
public void setMobileCaptchaService(MobileCaptchaService mobileCaptchaService) {
this.mobileCaptchaService = mobileCaptchaService;
}
}
- 博客tuan-group
- 博客的第一天 (no such group)
- group
- group
- Group
- Group
- $group
- 给博客搬家工具在google group上弄了个讨论区 http://groups.google.com/group/blog-remover
- WINRAER: Yhis Stie Cangains Abult Comtents, Nt Etrgy Yor Lass Tuan 18-Ydars33bbb-Olb !333bbb-
- SCSA-中文认证教材:http://yuhuohu.cublog.cn SUN-Solaris博客圈http://blog.chinaunix.net/group/group_982.html
- 关于group()、group(int group)、groupCount()
- group by
- Expand Group
- Function Group
- qq group
- group by
- group by
- One Group
- Oracle的入门命令
- 厚积薄发,丰富的公用类库积累,助你高效进行系统开发(4)----CSV、Excel、INI文件、独立存储等文件相关
- 轻量级HTTP服务器Nginx(常用配置实例)
- CentOS-6.2安装Nvidia显卡驱动
- php 变量判断
- 博客tuan-group
- jquery导航
- c程序设计语言笔记2
- Oracle常用服务简介
- 专注于操作系统19之走进分页
- C#中StringReader和StringWriter的使用
- ubuntu11.10 搭建 SMB (samba)服务
- Oracle语句及查询结果
- day04基础