Prevent the same account from logging in on multiple computers

1.实现HttpSessionListener  接口对session 进行监听

package com.tms.listener;

import com.tms.bean.UserSession;
import com.tms.constant.SystemConst;
import com.tms.service.system.RedisCacheService;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import javax.annotation.Resource;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
* Created by gjp on 2017/10/19.
* 防止同一账号在多台机器上登录
*/
@Component
public class SessionListener implements HttpSessionListener {
    static final Logger logSession = LoggerFactory.getLogger(SessionListener.class);

    @Resource
    private RedisCacheService<String> redisCacheService;


    @Override
    public void sessionCreated(HttpSessionEvent httpSessionEvent) {
       HttpSession start = httpSessionEvent.getSession();

       logSession.info("createId={}",start.getId());
    }

    @Override
    public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
        String id =httpSessionEvent.getSession().getId();
        deleteById(id);

        logSession.info("destroyed session id:"+id);
    }

    public boolean isCheckRepeatUser(UserSession newSession,HttpSession session){
        boolean flag =false;
        Set<String> keys = redisCacheService.keys(SystemConst.REPEAT_USER_LOGIN+"*");
        if(null != keys){
            for(String item:keys){
                   if(!flag) {
                       String userId = redisCacheService.getRedisCache(item);
                       if (!StringUtils.isEmpty(userId)) {
                           if (newSession.getUserId().equals(userId) &&
                                   !(SystemConst.REPEAT_USER_LOGIN+session.getId()).equals(item)) {
                               int len ​​= item.length();
                               String key = item.substring(SystemConst.REPEAT_USER_LOGIN.length(), len);
                               //User repeats
                               addRepeatUserId(userId, key, TimeUnit.HOURS);
                               flag = true;
                               break;
                           }
                       }
                   }
            }
        }

        addUserSession(session.getId(),newSession);

        return flag;
    }

    /**
     * Add a duplicated Session
     * @param item value
     * @param key
     * @param hours 小时
     */
    private void addRepeatUserId(String item, String key, TimeUnit hours) {
                redisCacheService.setRedisCache( SystemConst.REPEAT_USER_LOGIN_TRUE +key,
                item, 24, hours);
    }

    /**
     * 删除已经重复Session
     * @param sessionId
     */
     public void deleteRepeatUserId(String sessionId) {
        redisCacheService.deleteById(sessionId,SystemConst.REPEAT_USER_LOGIN_TRUE);
    }

    public String getRepeatUserId(final String sessionId){
         return  redisCacheService.getRedisCache(SystemConst.REPEAT_USER_LOGIN_TRUE+sessionId);
    }


    /**
     * Delete expired session
     * @param sessionId
     */
    public void deleteById(final String sessionId){
        redisCacheService.deleteById(sessionId,SystemConst.REPEAT_USER_LOGIN);
        redisCacheService.deleteById(sessionId,SystemConst.REPEAT_USER_LOGIN_TRUE);


    }

    private void addUserSession(final String sessionId, final UserSession session){
        redisCacheService.setRedisCache(SystemConst.REPEAT_USER_LOGIN+sessionId,session.getUserId(),
                24, TimeUnit.HOURS);
    }


}


2. After the user logs in successfully, execute the isCheckRepeatUser() method in the SessionListener object to
check, And mark whether the same account is logged in on different machines.

3. If the user logs out, delete the corresponding sessionid record.

@Resurce
private SessionListener sessionListener;

@CheckSession(method = "LoginController.fgLogout")
    @RequestMapping("/logout")
    public ModelAndView fgLogout(){
        ModelAndView mav = new ModelAndView("/front/login");
        HttpSession session = getSession();
        Enumeration<String> enumeration = session.getAttributeNames();
        if(null != enumeration ) {
            while (enumeration.hasMoreElements()) {
                session.removeAttribute(enumeration.nextElement());
            }
        }


       sessionListener.deleteById(session.getId());
        return mav;
    }

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326647438&siteId=291194637