修改是否允许账户多终端同时登录

master
wangxy 4 months ago
parent ddac1ba2b3
commit 237641dd29

@ -106,6 +106,8 @@ token:
secret: abcdefghijklmnopqrstuvwxyz secret: abcdefghijklmnopqrstuvwxyz
# 令牌有效期默认30分钟 # 令牌有效期默认30分钟
expireTime: 30 expireTime: 30
# 是否允许账户多终端同时登录true允许 false不允许
soloLogin: false
# MyBatis Plus配置 # MyBatis Plus配置
mybatis-plus: mybatis-plus:

@ -170,4 +170,10 @@ public class Constants
*/ */
public static final String[] JOB_ERROR_STR = { "java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml", public static final String[] JOB_ERROR_STR = { "java.net.URL", "javax.naming.InitialContext", "org.yaml.snakeyaml",
"org.springframework", "org.apache", "com.ruoyi.common.utils.file", "com.ruoyi.common.config", "com.ruoyi.generator" }; "org.springframework", "org.apache", "com.ruoyi.common.utils.file", "com.ruoyi.common.config", "com.ruoyi.generator" };
/**
* redis key
*/
public static final String LOGIN_USERID_KEY = "login_userid:";
} }

@ -44,7 +44,7 @@ public class LogoutSuccessHandlerImpl implements LogoutSuccessHandler
{ {
String userName = loginUser.getUsername(); String userName = loginUser.getUsername();
// 删除用户缓存记录 // 删除用户缓存记录
tokenService.delLoginUser(loginUser.getToken()); tokenService.delLoginUser(loginUser.getToken(), loginUser.getUser().getUserId());
// 记录用户退出日志 // 记录用户退出日志
AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success"))); AsyncManager.me().execute(AsyncFactory.recordLogininfor(userName, Constants.LOGOUT, MessageUtils.message("user.logout.success")));
} }

@ -7,6 +7,7 @@ import com.anji.captcha.model.vo.CaptchaVO;
import com.anji.captcha.service.CaptchaService; import com.anji.captcha.service.CaptchaService;
import org.hibernate.validator.internal.util.stereotypes.Lazy; import org.hibernate.validator.internal.util.stereotypes.Lazy;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.AuthenticationManager; import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.BadCredentialsException; import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
@ -40,8 +41,7 @@ import com.ruoyi.system.service.ISysUserService;
* @author ruoyi * @author ruoyi
*/ */
@Component @Component
public class SysLoginService public class SysLoginService {
{
@Autowired @Autowired
private TokenService tokenService; private TokenService tokenService;
@ -61,49 +61,53 @@ public class SysLoginService
@Lazy @Lazy
private CaptchaService captchaService; private CaptchaService captchaService;
// 是否允许账户多终端同时登录true允许 false不允许
@Value("${token.soloLogin}")
private boolean soloLogin;
/** /**
* *
* *
* @param username * @param username
* @param password * @param password
* @param code * @param code
* @param uuid
* @return * @return
*/ */
public String login(String username, String password, String code) public String login(String username, String password, String code) {
{
// 验证码校验 // 验证码校验
validateCaptcha(username, code); validateCaptcha(username, code);
// 登录前置校验 // 登录前置校验
loginPreCheck(username, password); loginPreCheck(username, password);
// 用户验证 // 用户验证
Authentication authentication = null; Authentication authentication = null;
try try {
{
UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password); UsernamePasswordAuthenticationToken authenticationToken = new UsernamePasswordAuthenticationToken(username, password);
AuthenticationContextHolder.setContext(authenticationToken); AuthenticationContextHolder.setContext(authenticationToken);
// 该方法会去调用UserDetailsServiceImpl.loadUserByUsername // 该方法会去调用UserDetailsServiceImpl.loadUserByUsername
authentication = authenticationManager.authenticate(authenticationToken); authentication = authenticationManager.authenticate(authenticationToken);
} } catch (Exception e) {
catch (Exception e) if (e instanceof BadCredentialsException) {
{
if (e instanceof BadCredentialsException)
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException(); throw new UserPasswordNotMatchException();
} } else {
else
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage())); AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, e.getMessage()));
throw new ServiceException(e.getMessage()); throw new ServiceException(e.getMessage());
} }
} } finally {
finally
{
AuthenticationContextHolder.clearContext(); AuthenticationContextHolder.clearContext();
} }
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success"))); AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_SUCCESS, MessageUtils.message("user.login.success")));
LoginUser loginUser = (LoginUser) authentication.getPrincipal(); LoginUser loginUser = (LoginUser) authentication.getPrincipal();
if (!soloLogin) {
// 如果用户不允许多终端同时登录,清除缓存信息
String userIdKey = Constants.LOGIN_USERID_KEY + loginUser.getUser().getUserId();
String userKey = redisCache.getCacheObject(userIdKey);
if (StringUtils.isNotEmpty(userKey)) {
redisCache.deleteObject(userIdKey);
redisCache.deleteObject(userKey);
}
}
recordLoginInfo(loginUser.getUserId()); recordLoginInfo(loginUser.getUserId());
// 生成token // 生成token
return tokenService.createToken(loginUser); return tokenService.createToken(loginUser);
@ -116,13 +120,11 @@ public class SysLoginService
* @param code * @param code
* @return * @return
*/ */
public void validateCaptcha(String username, String code) public void validateCaptcha(String username, String code) {
{
CaptchaVO captchaVO = new CaptchaVO(); CaptchaVO captchaVO = new CaptchaVO();
captchaVO.setCaptchaVerification(code); captchaVO.setCaptchaVerification(code);
ResponseModel response = captchaService.verification(captchaVO); ResponseModel response = captchaService.verification(captchaVO);
if (!response.isSuccess()) if (!response.isSuccess()) {
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error"))); AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.jcaptcha.error")));
throw new CaptchaException(); throw new CaptchaException();
} }
@ -130,35 +132,31 @@ public class SysLoginService
/** /**
* *
*
* @param username * @param username
* @param password * @param password
*/ */
public void loginPreCheck(String username, String password) public void loginPreCheck(String username, String password) {
{
// 用户名或密码为空 错误 // 用户名或密码为空 错误
if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) if (StringUtils.isEmpty(username) || StringUtils.isEmpty(password)) {
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null"))); AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("not.null")));
throw new UserNotExistsException(); throw new UserNotExistsException();
} }
// 密码如果不在指定范围内 错误 // 密码如果不在指定范围内 错误
if (password.length() < UserConstants.PASSWORD_MIN_LENGTH if (password.length() < UserConstants.PASSWORD_MIN_LENGTH
|| password.length() > UserConstants.PASSWORD_MAX_LENGTH) || password.length() > UserConstants.PASSWORD_MAX_LENGTH) {
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException(); throw new UserPasswordNotMatchException();
} }
// 用户名不在指定范围内 错误 // 用户名不在指定范围内 错误
if (username.length() < UserConstants.USERNAME_MIN_LENGTH if (username.length() < UserConstants.USERNAME_MIN_LENGTH
|| username.length() > UserConstants.USERNAME_MAX_LENGTH) || username.length() > UserConstants.USERNAME_MAX_LENGTH) {
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match"))); AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("user.password.not.match")));
throw new UserPasswordNotMatchException(); throw new UserPasswordNotMatchException();
} }
// IP黑名单校验 // IP黑名单校验
String blackStr = configService.selectConfigByKey("sys.login.blackIPList"); String blackStr = configService.selectConfigByKey("sys.login.blackIPList");
if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) if (IpUtils.isMatchedIp(blackStr, IpUtils.getIpAddr())) {
{
AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked"))); AsyncManager.me().execute(AsyncFactory.recordLogininfor(username, Constants.LOGIN_FAIL, MessageUtils.message("login.blocked")));
throw new BlackListException(); throw new BlackListException();
} }
@ -169,8 +167,7 @@ public class SysLoginService
* *
* @param userId ID * @param userId ID
*/ */
public void recordLoginInfo(Long userId) public void recordLoginInfo(Long userId) {
{
SysUser sysUser = new SysUser(); SysUser sysUser = new SysUser();
sysUser.setUserId(userId); sysUser.setUserId(userId);
sysUser.setLoginIp(IpUtils.getIpAddr()); sysUser.setLoginIp(IpUtils.getIpAddr());

@ -4,6 +4,7 @@ import java.util.HashMap;
import java.util.Map; import java.util.Map;
import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeUnit;
import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletRequest;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Autowired;
@ -29,8 +30,7 @@ import io.jsonwebtoken.SignatureAlgorithm;
* @author ruoyi * @author ruoyi
*/ */
@Component @Component
public class TokenService public class TokenService {
{
private static final Logger log = LoggerFactory.getLogger(TokenService.class); private static final Logger log = LoggerFactory.getLogger(TokenService.class);
// 令牌自定义标识 // 令牌自定义标识
@ -45,6 +45,10 @@ public class TokenService
@Value("${token.expireTime}") @Value("${token.expireTime}")
private int expireTime; private int expireTime;
// 是否允许账户多终端同时登录true允许 false不允许
@Value("${token.soloLogin}")
private boolean soloLogin;
protected static final long MILLIS_SECOND = 1000; protected static final long MILLIS_SECOND = 1000;
protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND; protected static final long MILLIS_MINUTE = 60 * MILLIS_SECOND;
@ -54,28 +58,24 @@ public class TokenService
@Autowired @Autowired
private RedisCache redisCache; private RedisCache redisCache;
/** /**
* *
* *
* @return * @return
*/ */
public LoginUser getLoginUser(HttpServletRequest request) public LoginUser getLoginUser(HttpServletRequest request) {
{
// 获取请求携带的令牌 // 获取请求携带的令牌
String token = getToken(request); String token = getToken(request);
if (StringUtils.isNotEmpty(token)) if (StringUtils.isNotEmpty(token)) {
{ try {
try
{
Claims claims = parseToken(token); Claims claims = parseToken(token);
// 解析对应的权限以及用户信息 // 解析对应的权限以及用户信息
String uuid = (String) claims.get(Constants.LOGIN_USER_KEY); String uuid = (String) claims.get(Constants.LOGIN_USER_KEY);
String userKey = getTokenKey(uuid); String userKey = getTokenKey(uuid);
LoginUser user = redisCache.getCacheObject(userKey); LoginUser user = redisCache.getCacheObject(userKey);
return user; return user;
} } catch (Exception e) {
catch (Exception e)
{
log.error("获取用户信息异常'{}'", e.getMessage()); log.error("获取用户信息异常'{}'", e.getMessage());
} }
} }
@ -85,10 +85,8 @@ public class TokenService
/** /**
* *
*/ */
public void setLoginUser(LoginUser loginUser) public void setLoginUser(LoginUser loginUser) {
{ if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken())) {
if (StringUtils.isNotNull(loginUser) && StringUtils.isNotEmpty(loginUser.getToken()))
{
refreshToken(loginUser); refreshToken(loginUser);
} }
} }
@ -96,13 +94,15 @@ public class TokenService
/** /**
* *
*/ */
public void delLoginUser(String token) public void delLoginUser(String token, Long userId) {
{ if (StringUtils.isNotEmpty(token)) {
if (StringUtils.isNotEmpty(token))
{
String userKey = getTokenKey(token); String userKey = getTokenKey(token);
redisCache.deleteObject(userKey); redisCache.deleteObject(userKey);
} }
if (!soloLogin && StringUtils.isNotNull(userId)) {
String userIdKey = getUserIdKey(userId);
redisCache.deleteObject(userIdKey);
}
} }
/** /**
@ -111,8 +111,7 @@ public class TokenService
* @param loginUser * @param loginUser
* @return * @return
*/ */
public String createToken(LoginUser loginUser) public String createToken(LoginUser loginUser) {
{
String token = IdUtils.fastUUID(); String token = IdUtils.fastUUID();
loginUser.setToken(token); loginUser.setToken(token);
setUserAgent(loginUser); setUserAgent(loginUser);
@ -129,12 +128,10 @@ public class TokenService
* @param loginUser * @param loginUser
* @return * @return
*/ */
public void verifyToken(LoginUser loginUser) public void verifyToken(LoginUser loginUser) {
{
long expireTime = loginUser.getExpireTime(); long expireTime = loginUser.getExpireTime();
long currentTime = System.currentTimeMillis(); long currentTime = System.currentTimeMillis();
if (expireTime - currentTime <= MILLIS_MINUTE_TEN) if (expireTime - currentTime <= MILLIS_MINUTE_TEN) {
{
refreshToken(loginUser); refreshToken(loginUser);
} }
} }
@ -144,13 +141,17 @@ public class TokenService
* *
* @param loginUser * @param loginUser
*/ */
public void refreshToken(LoginUser loginUser) public void refreshToken(LoginUser loginUser) {
{
loginUser.setLoginTime(System.currentTimeMillis()); loginUser.setLoginTime(System.currentTimeMillis());
loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE); loginUser.setExpireTime(loginUser.getLoginTime() + expireTime * MILLIS_MINUTE);
// 根据uuid将loginUser缓存 // 根据uuid将loginUser缓存
String userKey = getTokenKey(loginUser.getToken()); String userKey = getTokenKey(loginUser.getToken());
redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES); redisCache.setCacheObject(userKey, loginUser, expireTime, TimeUnit.MINUTES);
if (!soloLogin) {
// 缓存用户唯一标识,防止同一帐号,同时登录
String userIdKey = getUserIdKey(loginUser.getUser().getUserId());
redisCache.setCacheObject(userIdKey, userKey, expireTime, TimeUnit.MINUTES);
}
} }
/** /**
@ -158,8 +159,7 @@ public class TokenService
* *
* @param loginUser * @param loginUser
*/ */
public void setUserAgent(LoginUser loginUser) public void setUserAgent(LoginUser loginUser) {
{
UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent")); UserAgent userAgent = UserAgent.parseUserAgentString(ServletUtils.getRequest().getHeader("User-Agent"));
String ip = IpUtils.getIpAddr(); String ip = IpUtils.getIpAddr();
loginUser.setIpaddr(ip); loginUser.setIpaddr(ip);
@ -174,8 +174,7 @@ public class TokenService
* @param claims * @param claims
* @return * @return
*/ */
private String createToken(Map<String, Object> claims) private String createToken(Map<String, Object> claims) {
{
String token = Jwts.builder() String token = Jwts.builder()
.setClaims(claims) .setClaims(claims)
.signWith(SignatureAlgorithm.HS512, secret).compact(); .signWith(SignatureAlgorithm.HS512, secret).compact();
@ -188,8 +187,7 @@ public class TokenService
* @param token * @param token
* @return * @return
*/ */
private Claims parseToken(String token) private Claims parseToken(String token) {
{
return Jwts.parser() return Jwts.parser()
.setSigningKey(secret) .setSigningKey(secret)
.parseClaimsJws(token) .parseClaimsJws(token)
@ -202,8 +200,7 @@ public class TokenService
* @param token * @param token
* @return * @return
*/ */
public String getUsernameFromToken(String token) public String getUsernameFromToken(String token) {
{
Claims claims = parseToken(token); Claims claims = parseToken(token);
return claims.getSubject(); return claims.getSubject();
} }
@ -214,18 +211,19 @@ public class TokenService
* @param request * @param request
* @return token * @return token
*/ */
private String getToken(HttpServletRequest request) private String getToken(HttpServletRequest request) {
{
String token = request.getHeader(header); String token = request.getHeader(header);
if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) if (StringUtils.isNotEmpty(token) && token.startsWith(Constants.TOKEN_PREFIX)) {
{
token = token.replace(Constants.TOKEN_PREFIX, ""); token = token.replace(Constants.TOKEN_PREFIX, "");
} }
return token; return token;
} }
private String getTokenKey(String uuid) private String getTokenKey(String uuid) {
{
return CacheConstants.LOGIN_TOKEN_KEY + uuid; return CacheConstants.LOGIN_TOKEN_KEY + uuid;
} }
private String getUserIdKey(Long userId) {
return Constants.LOGIN_USERID_KEY + userId;
}
} }

@ -1,5 +1,5 @@
# 页面标题 # 页面标题
VUE_APP_TITLE = 若依管理系统 VUE_APP_TITLE = 后台管理系统
# 开发环境配置 # 开发环境配置
ENV = 'development' ENV = 'development'

@ -1,5 +1,5 @@
# 页面标题 # 页面标题
VUE_APP_TITLE = 若依管理系统 VUE_APP_TITLE = 后台管理系统
# 生产环境配置 # 生产环境配置
ENV = 'production' ENV = 'production'

@ -1,5 +1,5 @@
# 页面标题 # 页面标题
VUE_APP_TITLE = 若依管理系统 VUE_APP_TITLE = 后台管理系统
NODE_ENV = production NODE_ENV = production

@ -30,35 +30,15 @@
icon="el-icon-cloudy" icon="el-icon-cloudy"
plain plain
@click="goTarget('https://gitee.com/dromara/warm-flow')" @click="goTarget('https://gitee.com/dromara/warm-flow')"
>访问码云</el-button >访问码云</el-button>
>
<el-button <el-button
size="mini" size="mini"
icon="el-icon-s-home" icon="el-icon-s-home"
plain plain
@click="goTarget('http://www.warm-flow.cn/')" @click="goTarget('http://www.warm-flow.cn/')"
>访问主页</el-button >访问主页</el-button>
>
</p> </p>
</el-col> </el-col>
<el-col :sm="24" :lg="12" style="padding-left: 50px">
<el-card class="update-log">
<div slot="header" class="clearfix">
<span>捐赠支持</span>
</div>
<div class="body">
<img
src="https://foruda.gitee.com/images/1697770422557390406/7efa04d6_2218307.png"
alt="donate"
width="100%"
/>
<span style="display: inline-block; height: 30px; line-height: 30px"
>你可以请作者喝杯咖啡表示鼓励</span
>
</div>
</el-card>
</el-col>
</el-row> </el-row>
<el-divider /> <el-divider />
</div> </div>

@ -1,7 +1,7 @@
<template> <template>
<div class="login"> <div class="login">
<el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form"> <el-form ref="loginForm" :model="loginForm" :rules="loginRules" class="login-form">
<h3 class="title">若依后台管理系统</h3> <h3 class="title">后台管理系统</h3>
<el-form-item prop="username"> <el-form-item prop="username">
<el-input <el-input
v-model="loginForm.username" v-model="loginForm.username"

@ -1,7 +1,7 @@
<template> <template>
<div class="register"> <div class="register">
<el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form"> <el-form ref="registerForm" :model="registerForm" :rules="registerRules" class="register-form">
<h3 class="title">若依后台管理系统</h3> <h3 class="title">后台管理系统</h3>
<el-form-item prop="username"> <el-form-item prop="username">
<el-input v-model="registerForm.username" type="text" auto-complete="off" placeholder="账号"> <el-input v-model="registerForm.username" type="text" auto-complete="off" placeholder="账号">
<svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" /> <svg-icon slot="prefix" icon-class="user" class="el-input__icon input-icon" />

Loading…
Cancel
Save