Skip to content

Commit

Permalink
[Fix-2776] [admin] fix multi user login with the same token value ins…
Browse files Browse the repository at this point in the history
…ert error (#2863)

* fix multi user login with the same token value insert error

* fix multi user login with the same token value insert error

* 代码格式化

* use reentrant lock to instead synchronized

---------

Co-authored-by: tianxy105 <lucas123.COM>
  • Loading branch information
gitfortian authored Jan 1, 2024
1 parent 962fe4f commit b242e0d
Showing 1 changed file with 21 additions and 3 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -60,6 +60,7 @@
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.locks.ReentrantLock;
import java.util.stream.Collectors;

import org.springframework.stereotype.Service;
Expand Down Expand Up @@ -106,6 +107,8 @@ public class UserServiceImpl extends SuperServiceImpl<UserMapper, User> implemen
private final TokenService tokenService;
private final TokenMapper tokenMapper;

private final ReentrantLock lock = new ReentrantLock();

@Override
public Result<Void> registerUser(User user) {
User userByUsername = getUserByUsername(user.getUsername());
Expand Down Expand Up @@ -199,13 +202,13 @@ public Result<UserDTO> loginUser(LoginDTO loginDTO) {
// save login log record
loginLogService.saveLoginLog(user, Status.LOGIN_SUCCESS);

insertToken(userInfo);
upsertToken(userInfo);

// Return the user information along with a success status
return Result.succeed(userInfo, Status.LOGIN_SUCCESS);
}

private void insertToken(UserDTO userInfo) {
private void upsertToken(UserDTO userInfo) {
Integer userId = userInfo.getUser().getId();
SysToken sysToken = new SysToken();
String tokenValue = StpUtil.getTokenValueByLoginId(userId);
Expand All @@ -221,7 +224,22 @@ private void insertToken(UserDTO userInfo) {
sysToken.setCreator(userId);
sysToken.setUpdater(userId);
sysToken.setSource(SysToken.Source.LOGIN);
tokenMapper.insert(sysToken);

try {
lock.lock();
SysToken lastSysToken =
tokenMapper.selectOne(new LambdaQueryWrapper<SysToken>().eq(SysToken::getTokenValue, tokenValue));
if (Asserts.isNull(lastSysToken)) {
tokenMapper.insert(sysToken);
} else {
sysToken.setId(lastSysToken.getId());
tokenMapper.updateById(sysToken);
}
} catch (Exception e) {
log.error("update token info failed", e);
} finally {
lock.unlock();
}
}

private User localLogin(LoginDTO loginDTO) throws AuthException {
Expand Down

0 comments on commit b242e0d

Please sign in to comment.