新增编辑管理员功能代码 #117

Merged
hnu202326010106 merged 1 commits from wanglei_branch into develop 2 weeks ago

@ -8,6 +8,7 @@ import io.swagger.v3.oas.annotations.tags.Tag;
import lombok.RequiredArgsConstructor;
import org.springframework.http.ResponseEntity;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.core.Authentication;
import org.springframework.web.bind.annotation.*;
import java.util.List;
@ -119,4 +120,39 @@ public class AdminController {
return ResponseEntity.ok(ResultVO.error(401, "用户名或密码错误"));
}
}
/**
*
* /
*/
@PostMapping("/profile/update")
@PreAuthorize("isAuthenticated()") // 只要登录即可访问
@Operation(summary = "修改个人信息", description = "当前登录管理员修改自己的基本信息(不含角色)")
public ResponseEntity<ResultVO<Admin>> updateProfile(
@RequestBody Admin profile,
Authentication authentication) {
try {
// 1. 获取当前登录用户名
String currentUsername = authentication.getName();
// 2. 验证身份一致性(当前用户只能修改自己的信息)
Admin currentAdmin = adminService.getAdminByName(currentUsername)
.orElseThrow(() -> new RuntimeException("当前用户信息不存在"));
if (!currentAdmin.getAdminId().equals(profile.getAdminId())) {
throw new RuntimeException("无权修改其他管理员信息");
}
// 3. 过滤敏感字段不允许修改角色和区域ID
profile.setRole(currentAdmin.getRole());
profile.setAreaId(currentAdmin.getAreaId());
// 4. 调用服务层更新
Admin updatedAdmin = adminService.updateProfile(profile);
return ResponseEntity.ok(ResultVO.success(updatedAdmin, "个人信息更新成功"));
} catch (Exception e) {
return ResponseEntity.ok(ResultVO.error(500, "更新失败:" + e.getMessage()));
}
}
}

@ -115,4 +115,33 @@ public class AdminService {
public void setPasswordEncoder(PasswordEncoder passwordEncoder) {
this.passwordEncoder = passwordEncoder;
}
/**
*
*/
public Admin updateProfile(Admin profile) {
// 1. 获取数据库中原始信息
Admin existingAdmin = adminRepository.findByAdminId(profile.getAdminId())
.orElseThrow(() -> new RuntimeException("管理员不存在"));
// 2. 仅更新允许修改的字段(排除角色、区域等敏感信息)
existingAdmin.setAdminName(profile.getAdminName());
existingAdmin.setPhone(profile.getPhone());
existingAdmin.setUpdatedTime(LocalDateTime.now());
// 3. 密码修改单独处理(如果有密码更新需求)
if (profile.getPassword() != null && !profile.getPassword().isEmpty()) {
existingAdmin.setPassword(passwordEncoder.encode(profile.getPassword()));
}
return adminRepository.save(existingAdmin);
}
/**
*
*/
public Optional<Admin> getAdminByName(String username) {
return adminRepository.findByAdminName(username);
}
}
Loading…
Cancel
Save