Commit e746f5203547c774cb374b4eaa4ebb702b078bde

Authored by 黄 x
1 parent 0c6d927d

fix: 修改租户管理员的分页查询 修改密码需调用TB【除开平台管理员意外的用户】

... ... @@ -50,7 +50,7 @@ public class YtRoleController extends BaseController {
50 50 if (orderType != null) {
51 51 queryMap.put(ORDER_TYPE, orderType.name());
52 52 }
53   - return roleService.page(getCurrentUser().isPtSysadmin(), getCurrentUser().isPtmAdmin(), getCurrentUser().getCurrentTenantId(),queryMap);
  53 + return roleService.page(getCurrentUser().isPtSysadmin(), getCurrentUser().isPtAdmin(), getCurrentUser().getCurrentTenantId(),queryMap);
54 54 }
55 55
56 56 @DeleteMapping
... ... @@ -75,7 +75,7 @@ public class YtRoleController extends BaseController {
75 75 return roleService.saveOrUpdateRoleInfoWithMenu(
76 76 roleReqDTO,
77 77 getCurrentUser().isPtSysadmin(),
78   - getCurrentUser().isPtmAdmin(),
  78 + getCurrentUser().isPtAdmin(),
79 79 getCurrentUser().getCurrentTenantId());
80 80 }
81 81
... ...
... ... @@ -6,6 +6,7 @@ import io.swagger.annotations.ApiResponse;
6 6 import io.swagger.annotations.ApiResponses;
7 7 import lombok.RequiredArgsConstructor;
8 8 import org.apache.commons.lang3.StringUtils;
  9 +import org.springframework.context.ApplicationEventPublisher;
9 10 import org.springframework.http.ResponseEntity;
10 11 import org.springframework.security.access.prepost.PreAuthorize;
11 12 import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
... ... @@ -20,6 +21,7 @@ import org.thingsboard.server.common.data.id.TenantId;
20 21 import org.thingsboard.server.common.data.id.UserId;
21 22 import org.thingsboard.server.common.data.security.Authority;
22 23 import org.thingsboard.server.common.data.security.UserCredentials;
  24 +import org.thingsboard.server.common.data.security.event.UserAuthDataChangedEvent;
23 25 import org.thingsboard.server.common.data.yunteng.common.AddGroup;
24 26 import org.thingsboard.server.common.data.yunteng.common.DeleteGroup;
25 27 import org.thingsboard.server.common.data.yunteng.constant.FastIotConstants;
... ... @@ -41,6 +43,7 @@ import org.thingsboard.server.dao.user.UserService;
41 43 import org.thingsboard.server.dao.yunteng.service.YtUserService;
42 44 import org.thingsboard.server.service.security.model.SecurityUser;
43 45 import org.thingsboard.server.service.security.permission.Operation;
  46 +import org.thingsboard.server.service.security.system.SystemSecurityService;
44 47
45 48 import javax.servlet.http.HttpServletRequest;
46 49 import javax.servlet.http.HttpServletResponse;
... ... @@ -60,6 +63,9 @@ public class YtUserController extends BaseController {
60 63 private final BCryptPasswordEncoder passwordEncoder;
61 64 private final YtUserService userService;
62 65 private final UserService tbUserService;
  66 + private final ApplicationEventPublisher eventPublisher;
  67 + private final SystemSecurityService systemSecurityService;
  68 +
63 69 @GetMapping("{userId}")
64 70 public ResponseEntity<UserDTO> getUser(@PathVariable("userId") String userId)
65 71 throws ThingsboardException {
... ... @@ -97,24 +103,20 @@ public class YtUserController extends BaseController {
97 103 queryMap.put(ORDER_FILED, orderBy);
98 104 queryMap.put("realName", realName);
99 105 queryMap.put("username", username);
100   - if (getCurrentUser().isPtSysadmin()) {
101   - if (StringUtils.isEmpty(tenantId)) {
102   - tenantId = getCurrentUser().getCurrentTenantId();
103   - }
104   - queryMap.put("tenantId", tenantId);
105   - }
106   - if (null != roleType) {
  106 + if (null != roleType && roleType.equals(RoleEnum.TENANT_ADMIN)) {
107 107 queryMap.put("roleType", roleType.name());
  108 + }else{
  109 + tenantId = getCurrentUser().getCurrentTenantId();
108 110 }
109 111 if (orderType != null) {
110 112 queryMap.put(ORDER_TYPE, orderType.name());
111 113 }
  114 + queryMap.put("tenantId", tenantId);
112 115 return userService.page(
113 116 queryMap,
114 117 getCurrentUser().isPtSysadmin(),
115   - getCurrentUser().isPtmAdmin(),
116   - getCurrentUser().isPtTenantAdmin(),
117   - getCurrentUser().getCurrentTenantId());
  118 + getCurrentUser().isPtAdmin(),
  119 + getCurrentUser().isPtTenantAdmin(),tenantId);
118 120 }
119 121
120 122 @PutMapping
... ... @@ -147,38 +149,48 @@ public class YtUserController extends BaseController {
147 149
148 150 @PreAuthorize("hasAnyAuthority('SYS_ADMIN','PLATFORM_ADMIN')")
149 151 @PostMapping("saveTenantAdmin")
150   - public UserDTO saveTenantAdmin(@Validated(AddGroup.class)@RequestBody UserDTO userDTO) throws ThingsboardException {
151   - if(StringUtils.isAllBlank(userDTO.getTenantId())){
  152 + public UserDTO saveTenantAdmin(@Validated(AddGroup.class) @RequestBody UserDTO userDTO)
  153 + throws ThingsboardException {
  154 + if (StringUtils.isAllBlank(userDTO.getTenantId())) {
152 155 throw new YtDataValidationException(ErrorMessage.INVALID_PARAMETER.getMessage());
153 156 }
154 157 userService.validateUserNameAndPhoneNumberAndEmail(userDTO);
155 158 TenantId tenantId = new TenantId(UUID.fromString(userDTO.getTenantId()));
156   - try{
157   - //创建TB的租户管理员
  159 + try {
  160 + // 创建TB的租户管理员
158 161 User tbUser = new User();
159 162 tbUser.setAuthority(Authority.TENANT_ADMIN);
160 163 tbUser.setTenantId(tenantId);
161   - tbUser.setEmail(userDTO.getUsername()+ FastIotConstants.DEFAULT_EMAIL_SUFFIX_FOR_TB);
  164 + tbUser.setEmail(userDTO.getUsername() + FastIotConstants.DEFAULT_EMAIL_SUFFIX_FOR_TB);
162 165 tbUser = tbUserService.saveUser(tbUser);
163 166 userDTO.setTbUser(tbUser.getId().getId().toString());
164   - logEntityAction(tbUser.getId(), tbUser,
165   - tbUser.getCustomerId(),
166   - userDTO.getId() == null ? ActionType.ADDED : ActionType.UPDATED, null);
167   - sendEntityNotificationMsg(tenantId, tbUser.getId(),
168   - userDTO.getId() == null ? EdgeEventActionType.ADDED : EdgeEventActionType.UPDATED);
169   -
170   - //激活租户管理员
171   - //1、获取UserCredentials 并获取activateToken
  167 + logEntityAction(
  168 + tbUser.getId(),
  169 + tbUser,
  170 + tbUser.getCustomerId(),
  171 + userDTO.getId() == null ? ActionType.ADDED : ActionType.UPDATED,
  172 + null);
  173 + sendEntityNotificationMsg(
  174 + tenantId,
  175 + tbUser.getId(),
  176 + userDTO.getId() == null ? EdgeEventActionType.ADDED : EdgeEventActionType.UPDATED);
  177 +
  178 + // 激活租户管理员
  179 + // 1、获取UserCredentials 并获取activateToken
172 180 UserId userId = tbUser.getId();
173 181 User user = checkUserId(userId, Operation.READ);
174 182 SecurityUser authUser = getCurrentUser();
175   - UserCredentials userCredentials = tbUserService.findUserCredentialsByUserId(authUser.getTenantId(), user.getId());
176   - //2、进行激活
  183 + UserCredentials userCredentials =
  184 + tbUserService.findUserCredentialsByUserId(authUser.getTenantId(), user.getId());
  185 + // 2、进行激活
177 186 String encodedPassword = passwordEncoder.encode(FastIotConstants.DEFAULT_PWD);
178   - UserCredentials credentials = tbUserService.activateUserCredentials(TenantId.SYS_TENANT_ID, userCredentials.getActivateToken(), encodedPassword);
179   - User currentUser = tbUserService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
  187 + UserCredentials credentials =
  188 + tbUserService.activateUserCredentials(
  189 + TenantId.SYS_TENANT_ID, userCredentials.getActivateToken(), encodedPassword);
  190 + User currentUser =
  191 + tbUserService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
180 192 tbUserService.setUserCredentialsEnabled(currentUser.getTenantId(), currentUser.getId(), true);
181   - }catch (Exception e){
  193 + } catch (Exception e) {
182 194 throw handleException(e);
183 195 }
184 196 return userService.saveTenantAdmin(
... ... @@ -236,7 +248,27 @@ public class YtUserController extends BaseController {
236 248
237 249 @PostMapping("/reset")
238 250 @ApiOperation(value = "修改密码")
239   - public ResponseResult<Boolean> changePassword(@RequestBody AccountReqDTO accountReqDTO) {
240   - return ResponseResult.success(userService.changePassword(accountReqDTO));
  251 + public ResponseResult<Boolean> changePassword(@RequestBody AccountReqDTO accountReqDTO)
  252 + throws ThingsboardException {
  253 + org.thingsboard.server.dao.yunteng.entities.User user =
  254 + userService.validateChangePasswordAccount(accountReqDTO);
  255 + String resetPassword = accountReqDTO.getResetPassword();
  256 + if(!getCurrentUser().isPtAdmin()){
  257 + try{
  258 + // 除开平台管理员,都要调用TB密码修改
  259 + SecurityUser securityUser = getCurrentUser();
  260 + UserCredentials userCredentials =
  261 + tbUserService.findUserCredentialsByUserId(TenantId.SYS_TENANT_ID, securityUser.getId());
  262 + systemSecurityService.validatePassword(securityUser.getTenantId(), resetPassword, userCredentials);
  263 + userCredentials.setPassword(passwordEncoder.encode(resetPassword));
  264 + tbUserService.replaceUserCredentials(securityUser.getTenantId(), userCredentials);
  265 + sendEntityNotificationMsg(
  266 + getTenantId(), userCredentials.getUserId(), EdgeEventActionType.CREDENTIALS_UPDATED);
  267 + eventPublisher.publishEvent(new UserAuthDataChangedEvent(securityUser.getId()));
  268 + }catch (Exception e){
  269 + throw handleException(e);
  270 + }
  271 + }
  272 + return ResponseResult.success(userService.changePassword(user));
241 273 }
242 274 }
... ...
... ... @@ -281,8 +281,10 @@ public class YtUserServiceImpl extends AbstractBaseService<UserMapper, User>
281 281 String roleType = (String) queryMap.get("roleType");
282 282 if (StringUtils.isEmpty(roleType)) {
283 283 roleType = RoleEnum.PLATFORM_ADMIN.name();
  284 + userPage = baseMapper.getAdminUserPage(userIPage, tenantId, roleType);
  285 + }else{
  286 + userPage = baseMapper.getTenantAdminPage(userIPage, tenantId);
284 287 }
285   - userPage = baseMapper.getAdminUserPage(userIPage, tenantId, roleType);
286 288 } else if (isPlatformAdmin) {
287 289 // 平台管理员只能管理租户
288 290 userPage = baseMapper.selectAllTenantUser(userIPage);
... ... @@ -359,6 +361,7 @@ public class YtUserServiceImpl extends AbstractBaseService<UserMapper, User>
359 361 User user = new User();
360 362 userDTO.copyToEntity(user, ID, PASSWORD, CREATE_TIME, UPDATE_TIME, ACTIVATE_TOKEN);
361 363 user.setPassword(passwordEncoder.encode(FastIotConstants.DEFAULT_PWD));
  364 + user.setLevel(FastIotConstants.LevelValue.IS_TENANT_ADMIN);
362 365 List<User> users =
363 366 baseMapper.selectList(
364 367 new QueryWrapper<User>().lambda().eq(User::getUsername, userDTO.getUsername()));
... ... @@ -487,22 +490,9 @@ public class YtUserServiceImpl extends AbstractBaseService<UserMapper, User>
487 490
488 491 @Override
489 492 @Transactional
490   - public boolean changePassword(AccountReqDTO accountReqDTO) {
491   - User user = baseMapper.selectById(accountReqDTO.getUserId());
492   - if (null == user
493   - || StringUtils.isEmpty(accountReqDTO.getPassword())
494   - || StringUtils.isEmpty(accountReqDTO.getResetPassword())) {
495   - throw new YtDataValidationException(ErrorMessage.INVALID_PARAMETER.getMessage());
496   - }
497   - if (!StringUtils.isEmpty(user.getPassword())) {
498   - // 判断用户密码是否正确
499   - boolean isMatch = passwordEncoder.matches(accountReqDTO.getPassword(), user.getPassword());
500   - if (!isMatch) {
501   - throw new YtDataValidationException(ErrorMessage.INVALID_PARAMETER.getMessage());
502   - }
503   - }
  493 + public boolean changePassword(User user) {
504 494 // 修改密码
505   - user.setPassword(passwordEncoder.encode(accountReqDTO.getResetPassword()));
  495 + user.setPassword(passwordEncoder.encode(user.getPassword()));
506 496 user.setActivateToken(RandomStringUtils.randomAlphabetic(10));
507 497 return baseMapper.updateById(user) > 0;
508 498 }
... ... @@ -518,6 +508,23 @@ public class YtUserServiceImpl extends AbstractBaseService<UserMapper, User>
518 508 return baseMapper.findUserInfo(userDTO);
519 509 }
520 510
  511 + @Override
  512 + public User validateChangePasswordAccount(AccountReqDTO accountReqDTO) {
  513 + User user = baseMapper.selectById(accountReqDTO.getUserId());
  514 + if (null == user
  515 + || StringUtils.isEmpty(accountReqDTO.getPassword())
  516 + || StringUtils.isEmpty(accountReqDTO.getResetPassword())) {
  517 + throw new YtDataValidationException(ErrorMessage.INVALID_PARAMETER.getMessage());
  518 + }
  519 + // 判断用户密码是否正确
  520 + boolean isMatch = passwordEncoder.matches(accountReqDTO.getPassword(), user.getPassword());
  521 + if (!isMatch) {
  522 + throw new YtDataValidationException(ErrorMessage.INVALID_PARAMETER.getMessage());
  523 + }
  524 + user.setPassword(accountReqDTO.getResetPassword());
  525 + return user;
  526 + }
  527 +
521 528 /**
522 529 * 先删除用户与角色的关系,再添加新的关系
523 530 * @param userId 用户ID
... ...
... ... @@ -25,6 +25,8 @@ public interface UserMapper extends BaseMapper<User> {
25 25 IPage<UserDTO> getAdminUserPage(
26 26 IPage<?> page, @Param("tenantId") String tenantId, @Param("roleType") String roleType);
27 27
  28 + IPage<UserDTO> getTenantAdminPage(IPage<?> page, @Param("tenantId") String tenantId);
  29 +
28 30 IPage<UserDTO> selectAllTenantUser(IPage<?> page);
29 31
30 32 Set<String> getAllIdsByTenantId(@Param("tenantIds") Collection<String> tenantIds);
... ...
... ... @@ -7,6 +7,7 @@ import org.thingsboard.server.common.data.yunteng.dto.request.AccountReqDTO;
7 7 import org.thingsboard.server.common.data.yunteng.dto.request.RoleOrOrganizationReqDTO;
8 8 import org.thingsboard.server.common.data.yunteng.dto.request.SendResetPasswordEmailMsg;
9 9 import org.thingsboard.server.common.data.yunteng.utils.tools.YtPageData;
  10 +import org.thingsboard.server.dao.yunteng.entities.User;
10 11
11 12 import java.util.List;
12 13 import java.util.Map;
... ... @@ -54,6 +55,8 @@ public interface YtUserService {
54 55 */
55 56 UserDTO accountExist(String username,String tenantId);
56 57
  58 + User validateChangePasswordAccount(AccountReqDTO accountReqDTO);
  59 +
57 60 Optional<List<UserDTO>> getOrganizationUserByOrganizationId(String organizationId,String tenantId);
58 61
59 62 /**
... ... @@ -67,8 +70,8 @@ public interface YtUserService {
67 70 /**
68 71 * 修改密码
69 72 *
70   - * @param accountReqDTO 账号信息
  73 + * @param user 账号信息
71 74 * @return 修改成功、失败
72 75 */
73   - boolean changePassword(AccountReqDTO accountReqDTO);
  76 + boolean changePassword(User user);
74 77 }
... ...
... ... @@ -108,11 +108,19 @@
108 108 WHERE role_id IN (SELECT ID
109 109 FROM sys_role
110 110 WHERE role_type = #{roleType}
111   - <if test="roleType == 'ROLE_PLATFORM_ADMIN'">
112   - OR role_type = 'ROLE_SYS_ADMIN'
  111 + <if test="roleType == 'PLATFORM_ADMIN'">
  112 + OR role_type = 'SYS_ADMIN'
113 113 </if>
114 114 AND tenant_id = #{tenantId}))
115 115 </select>
  116 + <select id="getTenantAdminPage" resultMap="userDTOMap">
  117 + SELECT
  118 + <include refid="columns"/>,
  119 + st.name AS tenant_name
  120 + FROM sys_user su
  121 + LEFT JOIN sys_tenant st ON su.tenant_id = st.tenant_id
  122 + WHERE su.level = 2 AND su.tenant_id = #{tenantId}
  123 + </select>
116 124 <select id="selectAllTenantUser" resultMap="userDTOMap">
117 125 SELECT
118 126 <include refid="columns"/>,
... ...