Commit 956bb1ede1c1c4a3a813114ecb986c6ea233fefe

Authored by 黄 x
1 parent 39427775

fix: 已完成租户管理员增加的用户为客户,同时创建客户管理员并激活客户管理员

@@ -12,11 +12,14 @@ import org.springframework.security.access.prepost.PreAuthorize; @@ -12,11 +12,14 @@ import org.springframework.security.access.prepost.PreAuthorize;
12 import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder; 12 import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
13 import org.springframework.validation.annotation.Validated; 13 import org.springframework.validation.annotation.Validated;
14 import org.springframework.web.bind.annotation.*; 14 import org.springframework.web.bind.annotation.*;
15 -import org.springframework.web.servlet.support.ServletUriComponentsBuilder; 15 +import org.thingsboard.server.common.data.Customer;
  16 +import org.thingsboard.server.common.data.EntityType;
16 import org.thingsboard.server.common.data.User; 17 import org.thingsboard.server.common.data.User;
17 import org.thingsboard.server.common.data.audit.ActionType; 18 import org.thingsboard.server.common.data.audit.ActionType;
18 import org.thingsboard.server.common.data.edge.EdgeEventActionType; 19 import org.thingsboard.server.common.data.edge.EdgeEventActionType;
19 import org.thingsboard.server.common.data.exception.ThingsboardException; 20 import org.thingsboard.server.common.data.exception.ThingsboardException;
  21 +import org.thingsboard.server.common.data.id.CustomerId;
  22 +import org.thingsboard.server.common.data.id.EntityId;
20 import org.thingsboard.server.common.data.id.TenantId; 23 import org.thingsboard.server.common.data.id.TenantId;
21 import org.thingsboard.server.common.data.id.UserId; 24 import org.thingsboard.server.common.data.id.UserId;
22 import org.thingsboard.server.common.data.security.Authority; 25 import org.thingsboard.server.common.data.security.Authority;
@@ -43,12 +46,10 @@ import org.thingsboard.server.dao.user.UserService; @@ -43,12 +46,10 @@ import org.thingsboard.server.dao.user.UserService;
43 import org.thingsboard.server.dao.yunteng.service.YtUserService; 46 import org.thingsboard.server.dao.yunteng.service.YtUserService;
44 import org.thingsboard.server.service.security.model.SecurityUser; 47 import org.thingsboard.server.service.security.model.SecurityUser;
45 import org.thingsboard.server.service.security.permission.Operation; 48 import org.thingsboard.server.service.security.permission.Operation;
  49 +import org.thingsboard.server.service.security.permission.Resource;
46 import org.thingsboard.server.service.security.system.SystemSecurityService; 50 import org.thingsboard.server.service.security.system.SystemSecurityService;
47 -  
48 -import javax.servlet.http.HttpServletRequest;  
49 import javax.servlet.http.HttpServletResponse; 51 import javax.servlet.http.HttpServletResponse;
50 import java.io.IOException; 52 import java.io.IOException;
51 -import java.net.URI;  
52 import java.util.HashMap; 53 import java.util.HashMap;
53 import java.util.List; 54 import java.util.List;
54 import java.util.UUID; 55 import java.util.UUID;
@@ -105,7 +106,7 @@ public class YtUserController extends BaseController { @@ -105,7 +106,7 @@ public class YtUserController extends BaseController {
105 queryMap.put("username", username); 106 queryMap.put("username", username);
106 if (null != roleType && roleType.equals(RoleEnum.TENANT_ADMIN)) { 107 if (null != roleType && roleType.equals(RoleEnum.TENANT_ADMIN)) {
107 queryMap.put("roleType", roleType.name()); 108 queryMap.put("roleType", roleType.name());
108 - }else{ 109 + } else {
109 tenantId = getCurrentUser().getCurrentTenantId(); 110 tenantId = getCurrentUser().getCurrentTenantId();
110 } 111 }
111 if (orderType != null) { 112 if (orderType != null) {
@@ -116,7 +117,8 @@ public class YtUserController extends BaseController { @@ -116,7 +117,8 @@ public class YtUserController extends BaseController {
116 queryMap, 117 queryMap,
117 getCurrentUser().isPtSysadmin(), 118 getCurrentUser().isPtSysadmin(),
118 getCurrentUser().isPtAdmin(), 119 getCurrentUser().isPtAdmin(),
119 - getCurrentUser().isPtTenantAdmin(),tenantId); 120 + getCurrentUser().isPtTenantAdmin(),
  121 + tenantId);
120 } 122 }
121 123
122 @PutMapping 124 @PutMapping
@@ -126,19 +128,25 @@ public class YtUserController extends BaseController { @@ -126,19 +128,25 @@ public class YtUserController extends BaseController {
126 } 128 }
127 129
128 @PostMapping 130 @PostMapping
129 - @PreAuthorize("hasAnyAuthority('SYS_ADMIN','PLATFORM_ADMIN','TENANT_ADMIN')") 131 + @PreAuthorize("hasAnyAuthority('SYS_ADMIN','TENANT_ADMIN')")
130 public ResponseEntity<UserDTO> addUser( 132 public ResponseEntity<UserDTO> addUser(
131 @RequestParam(value = "sendEmail", required = false, defaultValue = "false") 133 @RequestParam(value = "sendEmail", required = false, defaultValue = "false")
132 boolean sendEmail, 134 boolean sendEmail,
133 @RequestParam(value = "sendMsg", required = false, defaultValue = "false") boolean sendMsg, 135 @RequestParam(value = "sendMsg", required = false, defaultValue = "false") boolean sendMsg,
134 @Validated({AddGroup.class}) @RequestBody UserDTO userDTO) 136 @Validated({AddGroup.class}) @RequestBody UserDTO userDTO)
135 throws ThingsboardException { 137 throws ThingsboardException {
136 - //如果当前用户是租户管理员,则代表创建的用户为CUSTOMER_USER,则需要调用TB,否则为本平台的管理员不需要调用TB 138 + // 如果当前用户是租户管理员,则代表创建的用户为CUSTOMER_USER,则需要调用TB,否则为本平台的管理员不需要调用TB
137 boolean isTenantAdminOperator = getCurrentUser().isPtTenantAdmin(); 139 boolean isTenantAdminOperator = getCurrentUser().isPtTenantAdmin();
138 - if(isTenantAdminOperator){  
139 - 140 + if (isTenantAdminOperator) {
  141 + // 创建CUSTOMER_USER用户
  142 + Customer customer = createCustomer(userDTO.getUsername());
  143 + // 创建CUSTOMER_USER的管理员
  144 + User tbUser = createTBUser(userDTO,customer.getTenantId(),customer.getId(), Authority.CUSTOMER_USER);
  145 + // 激活CUSTOMER_USER的管理员
  146 + activeTBUser(tbUser.getId());
140 } 147 }
141 - return ResponseEntity.ok(userService.saveAccount( 148 + return ResponseEntity.ok(
  149 + userService.saveAccount(
142 userDTO, 150 userDTO,
143 sendEmail, 151 sendEmail,
144 sendMsg, 152 sendMsg,
@@ -146,7 +154,7 @@ public class YtUserController extends BaseController { @@ -146,7 +154,7 @@ public class YtUserController extends BaseController {
146 getCurrentUser().getCurrentTenantId())); 154 getCurrentUser().getCurrentTenantId()));
147 } 155 }
148 156
149 - @PreAuthorize("hasAnyAuthority('SYS_ADMIN','PLATFORM_ADMIN')") 157 + @PreAuthorize("hasAnyAuthority('SYS_ADMIN')")
150 @PostMapping("saveTenantAdmin") 158 @PostMapping("saveTenantAdmin")
151 public UserDTO saveTenantAdmin(@Validated(AddGroup.class) @RequestBody UserDTO userDTO) 159 public UserDTO saveTenantAdmin(@Validated(AddGroup.class) @RequestBody UserDTO userDTO)
152 throws ThingsboardException { 160 throws ThingsboardException {
@@ -157,38 +165,10 @@ public class YtUserController extends BaseController { @@ -157,38 +165,10 @@ public class YtUserController extends BaseController {
157 TenantId tenantId = new TenantId(UUID.fromString(userDTO.getTenantId())); 165 TenantId tenantId = new TenantId(UUID.fromString(userDTO.getTenantId()));
158 try { 166 try {
159 // 创建TB的租户管理员 167 // 创建TB的租户管理员
160 - User tbUser = new User();  
161 - tbUser.setAuthority(Authority.TENANT_ADMIN);  
162 - tbUser.setTenantId(tenantId);  
163 - tbUser.setEmail(userDTO.getUsername() + FastIotConstants.DEFAULT_EMAIL_SUFFIX_FOR_TB);  
164 - tbUser = tbUserService.saveUser(tbUser);  
165 - userDTO.setTbUser(tbUser.getId().getId().toString());  
166 - logEntityAction(  
167 - tbUser.getId(),  
168 - tbUser,  
169 - tbUser.getCustomerId(),  
170 - userDTO.getId() == null ? ActionType.ADDED : ActionType.UPDATED,  
171 - null);  
172 - sendEntityNotificationMsg(  
173 - tenantId,  
174 - tbUser.getId(),  
175 - userDTO.getId() == null ? EdgeEventActionType.ADDED : EdgeEventActionType.UPDATED);  
176 - 168 + CustomerId customerId = new CustomerId(EntityId.NULL_UUID);
  169 + User tbUser = createTBUser(userDTO, tenantId,customerId, Authority.TENANT_ADMIN);
177 // 激活租户管理员 170 // 激活租户管理员
178 - // 1、获取UserCredentials 并获取activateToken  
179 - UserId userId = tbUser.getId();  
180 - User user = checkUserId(userId, Operation.READ);  
181 - SecurityUser authUser = getCurrentUser();  
182 - UserCredentials userCredentials =  
183 - tbUserService.findUserCredentialsByUserId(authUser.getTenantId(), user.getId());  
184 - // 2、进行激活  
185 - String encodedPassword = passwordEncoder.encode(FastIotConstants.DEFAULT_PWD);  
186 - UserCredentials credentials =  
187 - tbUserService.activateUserCredentials(  
188 - TenantId.SYS_TENANT_ID, userCredentials.getActivateToken(), encodedPassword);  
189 - User currentUser =  
190 - tbUserService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());  
191 - tbUserService.setUserCredentialsEnabled(currentUser.getTenantId(), currentUser.getId(), true); 171 + activeTBUser(tbUser.getId());
192 } catch (Exception e) { 172 } catch (Exception e) {
193 throw handleException(e); 173 throw handleException(e);
194 } 174 }
@@ -199,21 +179,10 @@ public class YtUserController extends BaseController { @@ -199,21 +179,10 @@ public class YtUserController extends BaseController {
199 @DeleteMapping 179 @DeleteMapping
200 public void deleteUser(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO) 180 public void deleteUser(@Validated({DeleteGroup.class}) @RequestBody DeleteDTO deleteDTO)
201 throws ThingsboardException { 181 throws ThingsboardException {
202 - //如果当前用户是租户管理员,则代表创建的用户为CUSTOMER_USER,则需要调用TB,否则为本平台的管理员不需要调用TB 182 + // 如果当前用户是租户管理员,则代表创建的用户为CUSTOMER_USER,则需要调用TB,否则为本平台的管理员不需要调用TB
203 userService.deleteUser( 183 userService.deleteUser(
204 deleteDTO.getIds(), getCurrentUser().isPtSysadmin(), getCurrentUser().getCurrentTenantId()); 184 deleteDTO.getIds(), getCurrentUser().isPtSysadmin(), getCurrentUser().getCurrentTenantId());
205 } 185 }
206 -  
207 - @RequestMapping(  
208 - value = "/{userId}/activationLink",  
209 - method = RequestMethod.GET,  
210 - produces = "text/plain")  
211 - public String getActivationLink(  
212 - @PathVariable("userId") String strUserId, HttpServletRequest request) {  
213 -  
214 - return null;  
215 - }  
216 -  
217 @GetMapping("getGroupUserByGroupId/{groupId}") 186 @GetMapping("getGroupUserByGroupId/{groupId}")
218 public ResponseEntity<List<UserDTO>> getGroupUserByGroupId( 187 public ResponseEntity<List<UserDTO>> getGroupUserByGroupId(
219 @PathVariable("groupId") String groupId) throws ThingsboardException { 188 @PathVariable("groupId") String groupId) throws ThingsboardException {
@@ -253,22 +222,113 @@ public class YtUserController extends BaseController { @@ -253,22 +222,113 @@ public class YtUserController extends BaseController {
253 org.thingsboard.server.dao.yunteng.entities.User user = 222 org.thingsboard.server.dao.yunteng.entities.User user =
254 userService.validateChangePasswordAccount(accountReqDTO); 223 userService.validateChangePasswordAccount(accountReqDTO);
255 String resetPassword = accountReqDTO.getResetPassword(); 224 String resetPassword = accountReqDTO.getResetPassword();
256 - if(!getCurrentUser().isPtAdmin()){  
257 - try{ 225 + if (!getCurrentUser().isPtAdmin()) {
  226 + try {
258 // 除开平台管理员,都要调用TB密码修改 227 // 除开平台管理员,都要调用TB密码修改
259 SecurityUser securityUser = getCurrentUser(); 228 SecurityUser securityUser = getCurrentUser();
260 UserCredentials userCredentials = 229 UserCredentials userCredentials =
261 - tbUserService.findUserCredentialsByUserId(TenantId.SYS_TENANT_ID, securityUser.getId());  
262 - systemSecurityService.validatePassword(securityUser.getTenantId(), resetPassword, userCredentials); 230 + tbUserService.findUserCredentialsByUserId(TenantId.SYS_TENANT_ID, securityUser.getId());
  231 + systemSecurityService.validatePassword(
  232 + securityUser.getTenantId(), resetPassword, userCredentials);
263 userCredentials.setPassword(passwordEncoder.encode(resetPassword)); 233 userCredentials.setPassword(passwordEncoder.encode(resetPassword));
264 tbUserService.replaceUserCredentials(securityUser.getTenantId(), userCredentials); 234 tbUserService.replaceUserCredentials(securityUser.getTenantId(), userCredentials);
265 sendEntityNotificationMsg( 235 sendEntityNotificationMsg(
266 - getTenantId(), userCredentials.getUserId(), EdgeEventActionType.CREDENTIALS_UPDATED); 236 + getTenantId(), userCredentials.getUserId(), EdgeEventActionType.CREDENTIALS_UPDATED);
267 eventPublisher.publishEvent(new UserAuthDataChangedEvent(securityUser.getId())); 237 eventPublisher.publishEvent(new UserAuthDataChangedEvent(securityUser.getId()));
268 - }catch (Exception e){ 238 + } catch (Exception e) {
269 throw handleException(e); 239 throw handleException(e);
270 } 240 }
271 } 241 }
272 return ResponseResult.success(userService.changePassword(user)); 242 return ResponseResult.success(userService.changePassword(user));
273 } 243 }
  244 +
  245 + /**
  246 + * 创建租户用户
  247 + *
  248 + * @param title 标题
  249 + * @throws ThingsboardException tb运行异常
  250 + */
  251 + private Customer createCustomer(String title) throws ThingsboardException {
  252 + Customer customer = new Customer();
  253 + try {
  254 + customer.setTitle(title);
  255 + customer.setTenantId(getCurrentUser().getTenantId());
  256 + checkEntity(customer.getId(), customer, Resource.CUSTOMER);
  257 +
  258 + Customer savedCustomer = checkNotNull(customerService.saveCustomer(customer));
  259 +
  260 + logEntityAction(
  261 + savedCustomer.getId(), savedCustomer, savedCustomer.getId(), ActionType.ADDED, null);
  262 +
  263 + if (customer.getId() != null) {
  264 + sendEntityNotificationMsg(
  265 + savedCustomer.getTenantId(), savedCustomer.getId(), EdgeEventActionType.UPDATED);
  266 + }
  267 + return savedCustomer;
  268 + } catch (Exception e) {
  269 + logEntityAction(emptyId(EntityType.CUSTOMER), customer, null, ActionType.ADDED, e);
  270 + throw handleException(e);
  271 + }
  272 + }
  273 +
  274 + /**
  275 + * 激活用户
  276 + *
  277 + * @param userId 用户ID
  278 + * @throws ThingsboardException tb运行异常
  279 + */
  280 + private void activeTBUser(UserId userId) throws ThingsboardException {
  281 + try {
  282 + // 1、获取UserCredentials 并获取activateToken
  283 + User user = checkUserId(userId, Operation.READ);
  284 + SecurityUser authUser = getCurrentUser();
  285 + UserCredentials userCredentials =
  286 + tbUserService.findUserCredentialsByUserId(authUser.getTenantId(), user.getId());
  287 + // 2、进行激活
  288 + String encodedPassword = passwordEncoder.encode(FastIotConstants.DEFAULT_PWD);
  289 + UserCredentials credentials =
  290 + tbUserService.activateUserCredentials(
  291 + TenantId.SYS_TENANT_ID, userCredentials.getActivateToken(), encodedPassword);
  292 + User currentUser =
  293 + tbUserService.findUserById(TenantId.SYS_TENANT_ID, credentials.getUserId());
  294 + tbUserService.setUserCredentialsEnabled(currentUser.getTenantId(), currentUser.getId(), true);
  295 + } catch (Exception e) {
  296 + throw handleException(e);
  297 + }
  298 + }
  299 +
  300 + /**
  301 + * 创建TB的用户
  302 + * @param userDTO 基础用户信息
  303 + * @param authority 用户角色权限
  304 + * @param tenantId 租户ID
  305 + * @param customerId 客户ID
  306 + * @return 用户
  307 + * @throws ThingsboardException tb运行异常
  308 + */
  309 + private User createTBUser(UserDTO userDTO, TenantId tenantId, CustomerId customerId, Authority authority)
  310 + throws ThingsboardException {
  311 + try {
  312 + User tbUser = new User();
  313 + tbUser.setAuthority(authority);
  314 + tbUser.setTenantId(tenantId);
  315 + tbUser.setCustomerId(customerId);
  316 + tbUser.setEmail(userDTO.getUsername() + FastIotConstants.DEFAULT_EMAIL_SUFFIX_FOR_TB);
  317 + tbUser = tbUserService.saveUser(tbUser);
  318 + userDTO.setTbUser(tbUser.getId().getId().toString());
  319 + logEntityAction(
  320 + tbUser.getId(),
  321 + tbUser,
  322 + tbUser.getCustomerId(),
  323 + userDTO.getId() == null ? ActionType.ADDED : ActionType.UPDATED,
  324 + null);
  325 + sendEntityNotificationMsg(
  326 + tenantId,
  327 + tbUser.getId(),
  328 + userDTO.getId() == null ? EdgeEventActionType.ADDED : EdgeEventActionType.UPDATED);
  329 + return tbUser;
  330 + } catch (Exception e) {
  331 + throw handleException(e);
  332 + }
  333 + }
274 } 334 }