22301115 | cf6dba2 | 2025-03-25 19:06:21 +0800 | [diff] [blame] | 1 | package com.example.myproject.controller; |
| 2 | |
| 3 | import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper; |
| 4 | import com.example.myproject.mapper.UserMapper; |
| 5 | import com.example.myproject.mapper.VerificationTokenMapper; |
| 6 | import com.example.myproject.entity.User; |
| 7 | import com.example.myproject.entity.VerificationToken; |
| 8 | import com.example.myproject.service.EmailService; |
| 9 | import com.example.myproject.service.UserService; |
| 10 | import com.example.myproject.utils.Result; |
| 11 | import io.swagger.annotations.Api; |
| 12 | import io.swagger.annotations.ApiOperation; |
| 13 | import io.swagger.annotations.ApiParam; |
| 14 | import org.apache.commons.lang3.RandomStringUtils; |
| 15 | import org.slf4j.Logger; |
| 16 | import org.slf4j.LoggerFactory; |
| 17 | import org.springframework.beans.factory.annotation.Autowired; |
| 18 | import org.springframework.http.HttpStatus; |
| 19 | import org.springframework.http.ResponseEntity; |
| 20 | import org.springframework.security.authentication.AuthenticationManager; |
| 21 | import org.springframework.security.authentication.UsernamePasswordAuthenticationToken; |
| 22 | import org.springframework.security.core.Authentication; |
| 23 | import org.springframework.security.core.AuthenticationException; |
| 24 | import org.springframework.security.core.context.SecurityContextHolder; |
| 25 | import org.springframework.web.bind.annotation.*; |
| 26 | |
| 27 | import javax.annotation.Resource; |
| 28 | import java.time.Instant; |
| 29 | import java.time.temporal.ChronoUnit; |
| 30 | |
| 31 | @RestController |
| 32 | @RequestMapping("/user") |
| 33 | @Api(value = "用户管理接口", tags = {"用户管理"}) |
| 34 | public class UserController { |
| 35 | |
| 36 | @Resource |
| 37 | private UserService userService; |
| 38 | |
| 39 | @Autowired |
| 40 | private AuthenticationManager authenticationManager; |
| 41 | |
| 42 | @Autowired |
| 43 | private UserMapper userMapper; // 使用 MyBatis-Plus |
| 44 | |
| 45 | @Autowired |
| 46 | private VerificationTokenMapper verificationTokenMapper; // 替换 JPA |
| 47 | |
| 48 | private static final Logger logger = LoggerFactory.getLogger(UserController.class); |
| 49 | |
| 50 | @PostMapping("/login") |
| 51 | @ApiOperation(value = "用户登录", notes = "使用用户名和密码进行登录") |
| 52 | public Result loginController(@RequestParam @ApiParam(value = "用户名", required = true) String username, |
| 53 | @RequestParam @ApiParam(value = "密码", required = true) String password) { |
| 54 | try { |
| 55 | Authentication authentication = authenticationManager.authenticate( |
| 56 | new UsernamePasswordAuthenticationToken(username, password) |
| 57 | ); |
| 58 | SecurityContextHolder.getContext().setAuthentication(authentication); |
| 59 | |
| 60 | // 使用 MyBatis-Plus 查询 |
| 61 | User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username)); |
| 62 | |
| 63 | System.out.println("Login successful for user: " + username); |
| 64 | return Result.success(user); |
| 65 | } catch (AuthenticationException e) { |
| 66 | return Result.error("401", "登录失败:" + e.getMessage()); |
| 67 | } |
| 68 | } |
| 69 | |
| 70 | @PostMapping("/register") |
| 71 | @ApiOperation(value = "用户注册", notes = "使用用户信息进行注册") |
| 72 | public Result registerController(@RequestBody @ApiParam(value = "新用户信息", required = true) User newUser) { |
| 73 | if (userService.checkEmailExists(newUser.getEmail())) { |
| 74 | return Result.error("邮箱冲突", "邮箱已被使用,请使用其他邮箱注册或找回密码!"); |
| 75 | } |
| 76 | boolean success = userService.preRegisterUser(newUser); |
| 77 | if (success) { |
| 78 | User responseUser = new User(); |
| 79 | responseUser.setEmail(newUser.getEmail()); |
| 80 | return Result.success(responseUser, "验证邮件已发送,请检查您的邮箱。"); |
| 81 | } else { |
| 82 | return Result.error("注册失败", "账号已存在或注册失败!"); |
| 83 | } |
| 84 | } |
| 85 | |
| 86 | public static class VerificationRequest { |
| 87 | private String email; |
| 88 | private String code; |
| 89 | |
| 90 | public String getEmail() { return email; } |
| 91 | public void setEmail(String email) { this.email = email; } |
| 92 | public String getCode() { return code; } |
| 93 | public void setCode(String code) { this.code = code; } |
| 94 | } |
| 95 | |
| 96 | @PostMapping("/verify-code") |
| 97 | @ApiOperation(value = "验证邮箱验证码", notes = "验证用户邮箱的验证码") |
| 98 | public Result verifyEmailCode(@RequestBody @ApiParam(value = "验证请求信息", required = true) VerificationRequest verificationRequest) { |
| 99 | String email = verificationRequest.getEmail(); |
| 100 | String code = verificationRequest.getCode(); |
| 101 | boolean isVerified = userService.verifyEmail(email, code); |
| 102 | if (isVerified) { |
| 103 | return Result.success(null, "邮箱验证成功!"); |
| 104 | } else { |
| 105 | return Result.error("验证失败", "验证码错误或已过期!"); |
| 106 | } |
| 107 | } |
| 108 | |
| 109 | @Autowired |
| 110 | private EmailService emailService; |
| 111 | |
| 112 | public static class EmailRequest { |
| 113 | private String email; |
| 114 | public String getEmail() { return email; } |
| 115 | public void setEmail(String email) { this.email = email; } |
| 116 | } |
| 117 | |
| 118 | @PostMapping("/get-verification-email") |
| 119 | @ApiOperation(value = "发送验证邮件", notes = "通过电子邮件发送验证邮件") |
| 120 | public ResponseEntity<Result> sendVerificationEmail(@RequestBody @ApiParam(value = "发送验证请求", required = true) EmailRequest emailVerificationRequest) { |
| 121 | String email = emailVerificationRequest.getEmail(); |
| 122 | User user = userMapper.selectOne(new QueryWrapper<User>().eq("email", email)); |
| 123 | if (user == null) { |
| 124 | logger.error("未找到与该邮箱地址相关联的用户: {}", email); |
| 125 | return ResponseEntity.status(HttpStatus.BAD_REQUEST) |
| 126 | .body(Result.error("1","未找到与该邮箱地址相关联的用户")); |
| 127 | } |
| 128 | |
| 129 | // 生成验证码 |
| 130 | String token = RandomStringUtils.randomNumeric(6); |
| 131 | Instant expiryDate = Instant.now().plus(1, ChronoUnit.HOURS); |
| 132 | logger.info("生成的验证令牌: {}, 过期时间: {}", token, expiryDate); |
| 133 | |
| 134 | VerificationToken verificationToken = new VerificationToken(token, user.getUsername(), email, user.getPassword(), expiryDate); |
| 135 | |
| 136 | // 保存到 MyBatis-Plus 数据库 |
| 137 | verificationTokenMapper.insert(verificationToken); |
| 138 | |
| 139 | logger.info("验证令牌已保存,用户: {}", user.getUsername()); |
| 140 | emailService.sendVerificationEmail(email, token); |
| 141 | |
| 142 | return ResponseEntity.ok(Result.success(200, "验证邮件已发送!")); |
| 143 | } |
| 144 | @PostMapping("/checkPassword") |
| 145 | public Result<String> checkPassword(@RequestParam Long userId, @RequestParam String password) { |
| 146 | boolean isPasswordCorrect = userService.checkPassword(userId, password); |
| 147 | if (isPasswordCorrect) { |
| 148 | return Result.success("200","原始密码输入正确"); |
| 149 | } else { |
| 150 | return Result.error("305","原始密码输入错误"); |
| 151 | } |
| 152 | } |
| 153 | } |