禁止同一账号 同时登录

This commit is contained in:
zhanglipeng 2021-03-08 10:57:41 +08:00
parent 1ed87c6ea9
commit 9239ee606c

View File

@ -32,8 +32,7 @@ import java.util.List;
* @author ruoyi
*/
@Component
public class SysLoginService
{
public class SysLoginService {
@Autowired
private TokenService tokenService;
@ -48,42 +47,33 @@ public class SysLoginService
*
* @param username 用户名
* @param password 密码
* @param captcha 验证码
* @param uuid 唯一标识
* @param captcha 验证码
* @param uuid 唯一标识
* @return 结果
*/
public String login(String username, String password, String code, String uuid)
{
public String login(String username, String password, String code, String uuid) {
String verifyKey = Constants.CAPTCHA_CODE_KEY + uuid;
String captcha = redisCache.getCacheObject(verifyKey);
redisCache.deleteObject(verifyKey);
if (captcha == null)
{
if (captcha == null) {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.expire")));
throw new CaptchaExpireException();
}
if (!code.equalsIgnoreCase(captcha))
{
if (!code.equalsIgnoreCase(captcha)) {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
throw new CaptchaException();
}
// 用户验证
Authentication authentication = null;
try
{
try {
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager
.authenticate(new UsernamePasswordAuthenticationToken(username, password));
}
catch (Exception e)
{
if (e instanceof BadCredentialsException)
{
} catch (Exception e) {
if (e instanceof BadCredentialsException) {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException();
}
else
{
} else {
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
throw new CustomException(e.getMessage());
}
@ -93,14 +83,13 @@ public class SysLoginService
List<SysUserOnline> userOnlineList = new ArrayList<SysUserOnline>();
for (String key : keys) {
LoginUser user = redisCache.getCacheObject(key);
if (StringUtils.isNotEmpty(username) && StringUtils.isNotNull(user.getUser()))
{
if (StringUtils.equals(username, user.getUsername()))
{
if (StringUtils.isNotEmpty(username) && StringUtils.isNotNull(user.getUser())) {
if (StringUtils.equals(username, user.getUsername())) {
//存在已经登录用户抛出异常
CustomException alreadyLoginExcep = new CustomException("该账号已在别处登陆", HttpStatus.ALREADY_LOGIN);
alreadyLoginExcep.setObj(username);
throw alreadyLoginExcep;
// CustomException alreadyLoginExcep = new CustomException("该账号已在别处登陆", HttpStatus.ALREADY_LOGIN);
// alreadyLoginExcep.setObj(username);
// throw alreadyLoginExcep;
redisCache.deleteObject(key);
}
}
}