完成/changePassword,测试通过

This commit is contained in:
高子兴 2024-07-01 20:02:22 +08:00
parent cbe7ec9a24
commit c03b190aba
3 changed files with 44 additions and 9 deletions

View File

@ -1,9 +1,6 @@
package org.cmh.backend.authentication.controller;
import lombok.AllArgsConstructor;
import lombok.Getter;
import lombok.Setter;
import org.cmh.backend.Utils.JwtUtil;
import org.cmh.backend.authentication.dto.*;
import org.cmh.backend.authentication.model.UserHS;
@ -13,8 +10,6 @@ import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;
@RestController
class AuthenticationController {
@ -86,5 +81,15 @@ class AuthenticationController {
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
@PostMapping("/changePassword")
public ResponseEntity<Object> changePassword(@RequestBody ChangePasswordRequest changePasswordRequest) {
if (JwtUtil.isTokenValid(changePasswordRequest.getToken())) {
if (userService.changePassword(JwtUtil.extractUsername(changePasswordRequest.getToken()), changePasswordRequest)) {
return new ResponseEntity<>(HttpStatus.OK);
}
}
return new ResponseEntity<>(HttpStatus.BAD_REQUEST);
}
}

View File

@ -0,0 +1,11 @@
package org.cmh.backend.authentication.dto;
import lombok.Getter;
import lombok.Setter;
@Getter
@Setter
public class ChangePasswordRequest extends JwtRequest{
private String currentPassword;
private String newPassword;
}

View File

@ -1,5 +1,6 @@
package org.cmh.backend.authentication.service;
import org.cmh.backend.authentication.dto.ChangePasswordRequest;
import org.cmh.backend.authentication.dto.ManageUserProfileRequest;
import org.cmh.backend.authentication.model.UserHS;
import org.cmh.backend.authentication.repository.UserRepository;
@ -67,17 +68,35 @@ public class UserService {
user.setEmail(request.getEmail());
user.setDepartment(request.getDepartment());
user.setRole(request.getRole());
try{
try {
userRepository.save(user);
}
catch (Exception e) {
} catch (Exception e) {
return false;
}
return true;
} else {
return false;
}
}
}
public boolean changePassword(String username, ChangePasswordRequest request) {
UserHS user = userRepository.findByUsername(username);
if (user != null) {
if (passwordEncoder.matches(request.getCurrentPassword(), user.getPassword())) {
if (isValidPassword(request.getNewPassword())) {
String encodedPassword = passwordEncoder.encode(request.getNewPassword());
user.setPassword(encodedPassword);
try {
userRepository.save(user);
} catch (Exception e) {
return false;
}
return true;
}
}
}
return false;
}
// 验证用户名格式