AuthServiceImpl.java
8.69 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
package com.youjia.system.service.impl;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.youjia.common.constant.CommonConstants;
import com.youjia.common.core.ResultCode;
import com.youjia.common.enums.DataScopeEnum;
import com.youjia.common.exception.BusinessException;
import com.youjia.framework.security.AuthProperties;
import com.youjia.framework.security.AuthTokenService;
import com.youjia.framework.security.CurrentUserHolder;
import com.youjia.framework.security.LoginUser;
import com.youjia.system.dto.LoginDTO;
import com.youjia.system.entity.SysUser;
import com.youjia.system.mapper.SysUserMapper;
import com.youjia.system.remote.DjSilentLoginClient;
import com.youjia.system.remote.ScrmSilentLoginClient;
import com.youjia.system.service.AuthService;
import com.youjia.system.service.SysUserService;
import com.youjia.system.support.PermissionSupport;
import com.youjia.system.vo.LoginVO;
import com.youjia.system.vo.UserInfoVO;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;
import java.time.LocalDateTime;
import java.util.List;
import java.util.Objects;
/**
* 统一登录实现:BCrypt 校验密码 → 装配角色与数据域 → 建立 Redis 会话 → 预热权限缓存。
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class AuthServiceImpl implements AuthService {
private final SysUserMapper sysUserMapper;
private final AuthTokenService authTokenService;
private final PasswordEncoder passwordEncoder;
private final PermissionSupport permissionSupport;
private final AuthProperties authProperties;
private final SysUserService sysUserService;
private final DjSilentLoginClient djSilentLoginClient;
private final ScrmSilentLoginClient scrmSilentLoginClient;
@Override
public LoginVO login(LoginDTO dto) {
String account = dto.getAccount() == null ? "" : dto.getAccount().trim();
if (authTokenService.isLocked(account)) {
throw new BusinessException(ResultCode.USER_ACCOUNT_LOCKED,
"密码连续错误次数过多,账号已锁定,请 " + authTokenService.lockRemainSeconds(account) + " 秒后重试");
}
SysUser user = sysUserMapper.selectOne(new LambdaQueryWrapper<SysUser>()
.eq(SysUser::getAccount, account));
if (user == null) {
authTokenService.incrementFail(account);
throw new BusinessException(ResultCode.USER_PASSWORD_ERROR);
}
if (!Objects.equals(CommonConstants.STATUS_ENABLED, user.getStatus())) {
throw new BusinessException(ResultCode.USER_DISABLED);
}
if (user.getPassword() == null || !passwordEncoder.matches(dto.getPassword(), user.getPassword())) {
long fails = authTokenService.incrementFail(account);
int remain = (int) Math.max(0, authProperties.getMaxFailCount() - fails);
throw new BusinessException(ResultCode.USER_PASSWORD_ERROR,
remain > 0 ? "账号或密码错误,还可尝试 " + remain + " 次" : "账号或密码错误,账号已锁定");
}
authTokenService.clearFail(account);
Long userId = user.getUserId();
List<Long> roleIds = permissionSupport.listRoleIds(userId);
List<String> roleCodes = permissionSupport.listRoleCodes(userId);
Integer dataScope = permissionSupport.resolveDataScope(user);
LoginUser loginUser = LoginUser.builder()
.userId(userId)
.account(user.getAccount())
.name(user.getName())
.orgId(user.getOrgId())
.dataScope(dataScope)
.roleIds(roleIds)
.roleCodes(roleCodes)
.build();
String token = authTokenService.createSession(loginUser);
// 预热权限缓存,避免首个业务请求才回源
List<String> permCodes = authTokenService.getPermCodes(userId,
() -> permissionSupport.listPermCodes(userId));
SysUser lastLogin = new SysUser();
lastLogin.setUserId(userId);
lastLogin.setLastLoginAt(LocalDateTime.now());
sysUserMapper.updateById(lastLogin);
log.info("账号 {} 登录成功,角色 {} 个,权限码 {} 个", account, roleIds.size(), permCodes.size());
// 静默登录 D+(嘀加):用 Nacos 配置的默认账号调 dj.api.user.login 换取 sessionId 随登录结果返回。
// 属于附加动作,失败只记日志不阻断本次优加登录(sessionId 置空,前端自行判空降级)。
String djSessionId = null;
try {
djSessionId = djSilentLoginClient.silentLogin();
} catch (BusinessException e) {
log.error("账号 {} 登录成功但 D+ 静默登录失败:{}", account, e.getMessage());
}
// 静默登录 SCRM:用独立的默认账号调 scrm.api.sso.user.login 换取 sessionId(单账号,直接返回)。
// 与 D+ 静默登录同样是附加动作,失败只记日志不阻断登录。
String scrmSessionId = null;
try {
scrmSessionId = scrmSilentLoginClient.silentLogin();
} catch (BusinessException e) {
log.error("账号 {} 登录成功但 SCRM 静默登录失败:{}", account, e.getMessage());
}
LoginUser session = authTokenService.getSession(token);
return LoginVO.builder()
.token(token)
.tokenType(StringUtils.hasText(authProperties.getTokenPrefix())
? authProperties.getTokenPrefix().trim() : "Bearer")
.expireAt(session == null ? null : session.getExpireAt())
.userId(userId)
.account(user.getAccount())
.name(user.getName())
.orgId(user.getOrgId())
.dataScope(dataScope)
.roleCodes(roleCodes)
.permCodes(permCodes)
.sessionId(djSessionId)
.loginToken(scrmSessionId)
.needChangePassword(user.getNeedChangePwd() != null && user.getNeedChangePwd() == 1)
.build();
}
@Override
public void logout() {
LoginUser loginUser = CurrentUserHolder.get();
if (loginUser != null && StringUtils.hasText(loginUser.getToken())) {
authTokenService.removeSession(loginUser.getToken());
log.info("账号 {} 退出登录", loginUser.getAccount());
}
}
@Override
public void changePassword(String oldPassword, String newPassword) {
Long userId = CurrentUserHolder.getUserId();
if (userId == null) {
throw new BusinessException(ResultCode.UNAUTHORIZED, "请先登录");
}
sysUserService.changePassword(userId, oldPassword, newPassword);
}
@Override
public UserInfoVO currentUserInfo() {
LoginUser loginUser = CurrentUserHolder.get();
if (loginUser == null || loginUser.getUserId() == null) {
throw new BusinessException(ResultCode.UNAUTHORIZED, "请先登录");
}
SysUser user = sysUserMapper.selectById(loginUser.getUserId());
if (user == null) {
throw new BusinessException(ResultCode.USER_NOT_FOUND);
}
List<String> permCodes = authTokenService.getPermCodes(loginUser.getUserId(),
() -> permissionSupport.listPermCodes(loginUser.getUserId()));
return UserInfoVO.builder()
.userId(user.getUserId())
.account(user.getAccount())
.name(user.getName())
.mobile(user.getMobile())
.orgId(user.getOrgId())
.dataScope(loginUser.getDataScope())
.dataScopeLabel(DataScopeEnum.of(loginUser.getDataScope())
.map(DataScopeEnum::getLabel).orElse(null))
.roleIds(loginUser.getRoleIds())
.roleCodes(loginUser.getRoleCodes())
.permCodes(permCodes)
.loginAt(loginUser.getLoginAt())
.expireAt(loginUser.getExpireAt())
.build();
}
@Override
public int refreshPermCache() {
LoginUser loginUser = CurrentUserHolder.get();
if (loginUser == null || loginUser.getUserId() == null) {
throw new BusinessException(ResultCode.UNAUTHORIZED, "请先登录");
}
authTokenService.evictPermCache(loginUser.getUserId());
List<String> codes = authTokenService.getPermCodes(loginUser.getUserId(),
() -> permissionSupport.listPermCodes(loginUser.getUserId()));
return codes.size();
}
}