Revert "注册登录,用户等级,社交,动态,新手任务"
This reverts commit 1c359108ca33d46271920ee0cd57dddcb7012937.
Reason for revert: <冲突>
Change-Id: Ie586267169acac99130b1fadf4a5f433441c4b8c
diff --git a/src/main/java/com/example/myproject/controller/UserController.java b/src/main/java/com/example/myproject/controller/UserController.java
index e96df8f..acda403 100644
--- a/src/main/java/com/example/myproject/controller/UserController.java
+++ b/src/main/java/com/example/myproject/controller/UserController.java
@@ -1,122 +1,190 @@
package com.example.myproject.controller;
-import com.example.myproject.entity.Users;
-import com.example.myproject.repository.UserRepository;
-import com.example.myproject.service.TaskService;
+import cn.dev33.satoken.annotation.SaCheckLogin;
+import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
+import com.example.myproject.common.base.PageUtil;
+import com.example.myproject.dto.param.TorrentParam;
+import com.example.myproject.dto.vo.TorrentVO;
+import com.example.myproject.entity.TorrentEntity;
+import com.example.myproject.mapper.UserMapper;
+import com.example.myproject.mapper.VerificationTokenMapper;
+import com.example.myproject.entity.User;
+import com.example.myproject.entity.VerificationToken;
+import com.example.myproject.service.EmailService;
import com.example.myproject.service.UserService;
+import com.example.myproject.common.base.Result;
+import io.swagger.annotations.Api;
+import io.swagger.annotations.ApiOperation;
+import io.swagger.annotations.ApiParam;
+import io.swagger.v3.oas.annotations.Operation;
+import io.swagger.v3.oas.annotations.media.Content;
+import io.swagger.v3.oas.annotations.media.Schema;
+import io.swagger.v3.oas.annotations.responses.ApiResponse;
+import org.apache.commons.lang3.RandomStringUtils;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+import org.springframework.security.authentication.AuthenticationManager;
+import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
+import org.springframework.security.core.Authentication;
+import org.springframework.security.core.AuthenticationException;
+import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.*;
-import java.util.Map;
-import java.util.Optional;
+import javax.annotation.Resource;
+import java.time.Instant;
+import java.time.temporal.ChronoUnit;
+import java.util.List;
@RestController
-@RequestMapping("/echo/user")
+@RequestMapping("/user")
+@Api(value = "用户管理接口", tags = {"用户管理"})
public class UserController {
- @Autowired
+ @Resource
private UserService userService;
@Autowired
- private UserRepository userRepository;
+ private AuthenticationManager authenticationManager;
- // 接口:生成邀请码
- @PostMapping("/getInviteCode")
- public Map<String, Object> generateInviteCode(@RequestBody Map<String, Object> request) {
- Long userId = Long.parseLong(request.get("user_id").toString());
- return userService.generateInviteCode(userId);
- }
+ @Autowired
+ private UserMapper userMapper; // 使用 MyBatis-Plus
- //注册
- @PostMapping("/register")
- public Map<String, Object> register(@RequestBody Map<String, Object> request) {
- String username = (String) request.get("username");
- String email = (String) request.get("email");
- String password = (String) request.get("password");
- String role = (String) request.get("role");
- String inviteCode = (String) request.get("inviteCode");
+ @Autowired
+ private VerificationTokenMapper verificationTokenMapper; // 替换 JPA
- // 调用服务层的注册方法
- String resultMessage = userService.registerUser(username, email, password, role, inviteCode);
+ private static final Logger logger = LoggerFactory.getLogger(UserController.class);
- // 返回注册结果
- return Map.of("msg", resultMessage);
- }
-
- //登录
@PostMapping("/login")
- public Map<String, Object> login(@RequestBody Map<String, Object> request) {
- String username = (String) request.get("username");
- String password = (String) request.get("password");
+ @ApiOperation(value = "用户登录", notes = "使用用户名和密码进行登录")
+ public Result loginController(@RequestParam @ApiParam(value = "用户名", required = true) String username,
+ @RequestParam @ApiParam(value = "密码", required = true) String password) {
+ try {
+ Authentication authentication = authenticationManager.authenticate(
+ new UsernamePasswordAuthenticationToken(username, password)
+ );
+ SecurityContextHolder.getContext().setAuthentication(authentication);
- // 调用服务层的登录方法
- String resultMessage = userService.loginUser(username, password);
+ // 使用 MyBatis-Plus 查询
+ User user = userMapper.selectOne(new QueryWrapper<User>().eq("username", username));
- // 根据登录结果返回不同的响应
- if (resultMessage.equals("登录成功")) {
- // 查询用户信息
- Optional<Users> user = userRepository.findByUsername(username);
- if (user.isPresent()) {
- // 将用户的所有信息作为返回值
- return Map.of("msg", resultMessage, "user", user.get());
- } else {
- return Map.of("msg", "用户信息查询失败");
- }
- } else {
- return Map.of("msg", resultMessage);
+ System.out.println("Login successful for user: " + username);
+ return Result.ok(user);
+ } catch (AuthenticationException e) {
+ return Result.error("登录失败");
}
}
- //修改密码
- @PostMapping("/password")
- public Map<String, Object> changePassword(@RequestBody Map<String, Object> request) {
- Long userId = Long.parseLong(request.get("user_id").toString());
- String oldPassword = (String) request.get("old_password");
- String newPassword = (String) request.get("new_password");
- String confirmPassword = (String) request.get("confirm_password");
-
- // 调用服务层的修改密码方法
- String resultMessage = userService.changePassword(userId, oldPassword, newPassword, confirmPassword);
-
- // 返回修改结果
- return Map.of("message", resultMessage, "status", resultMessage.equals("密码修改成功") ? "success" : "error");
- }
-
- // 获取用户个人资料
- @GetMapping("/{userId}/getProfile")
- public Map<String, Object> getProfile(@PathVariable("userId") Long userId) {
- return userService.getProfile(userId);
- }
-
- // 修改用户个人资料
- @PutMapping("/{userId}/editProfile")
- public Map<String, String> editProfile(
- @PathVariable("userId") Long userId,
- @RequestBody Map<String, Object> profileData) {
-
- // 获取请求体中的修改数据
- String avatarUrl = (String) profileData.get("avatarUrl");
- String nickname = (String) profileData.get("nickname");
- String gender = (String) profileData.get("gender");
- String description = (String) profileData.get("description");
- String hobbies = (String) profileData.get("hobbies");
-
- // 调用服务层方法进行修改
- boolean updated = userService.editProfile(userId, avatarUrl, nickname, gender, description, hobbies);
-
- // 返回操作结果消息
- if (updated) {
- return Map.of("message", "用户资料更新成功");
+ @PostMapping("/register")
+ @ApiOperation(value = "用户注册", notes = "使用用户信息进行注册")
+ public Result registerController(@RequestBody @ApiParam(value = "新用户信息", required = true) User newUser) {
+ if (userService.checkEmailExists(newUser.getEmail())) {
+ return Result.error( "邮箱已被使用,请使用其他邮箱注册或找回密码!");
+ }
+ boolean success = userService.preRegisterUser(newUser);
+ if (success) {
+ User responseUser = new User();
+ responseUser.setEmail(newUser.getEmail());
+ return Result.ok();
} else {
- return Map.of("message", "用户不存在");
+ return Result.error("账号已存在或注册失败!");
}
}
- // 计算分享率
- @GetMapping("/{user_id}/calculate-share-rate")
- public Map<String, Object> calculateShareRate(@PathVariable("user_id") Long userId) {
- return userService.calculateShareRate(userId);
+ public static class VerificationRequest {
+ private String email;
+ private String code;
+
+ public String getEmail() { return email; }
+ public void setEmail(String email) { this.email = email; }
+ public String getCode() { return code; }
+ public void setCode(String code) { this.code = code; }
}
+ @PostMapping("/verify-code")
+ @ApiOperation(value = "验证邮箱验证码", notes = "验证用户邮箱的验证码")
+ public Result verifyEmailCode(@RequestBody @ApiParam(value = "验证请求信息", required = true) VerificationRequest verificationRequest) {
+ String email = verificationRequest.getEmail();
+ String code = verificationRequest.getCode();
+ boolean isVerified = userService.verifyEmail(email, code);
+ if (isVerified) {
+ return Result.ok();
+ } else {
+ return Result.error( "验证码错误或已过期!");
+ }
+ }
+
+ @Autowired
+ private EmailService emailService;
+
+ public static class EmailRequest {
+ private String email;
+ public String getEmail() { return email; }
+ public void setEmail(String email) { this.email = email; }
+ }
+
+ @PostMapping("/get-verification-email")
+ @ApiOperation(value = "发送验证邮件", notes = "通过电子邮件发送验证邮件")
+ public ResponseEntity<Result> sendVerificationEmail(@RequestBody @ApiParam(value = "发送验证请求", required = true) EmailRequest emailVerificationRequest) {
+ String email = emailVerificationRequest.getEmail();
+ User user = userMapper.selectOne(new QueryWrapper<User>().eq("email", email));
+ if (user == null) {
+ logger.error("未找到与该邮箱地址相关联的用户: {}", email);
+ return ResponseEntity.status(HttpStatus.BAD_REQUEST)
+ .body(Result.error("未找到与该邮箱地址相关联的用户"));
+ }
+
+ // 生成验证码
+ String token = RandomStringUtils.randomNumeric(6);
+ Instant expiryDate = Instant.now().plus(1, ChronoUnit.HOURS);
+ logger.info("生成的验证令牌: {}, 过期时间: {}", token, expiryDate);
+
+ VerificationToken verificationToken = new VerificationToken(token, user.getUsername(), email, user.getPassword(), expiryDate);
+
+ // 保存到 MyBatis-Plus 数据库
+ verificationTokenMapper.insert(verificationToken);
+
+ logger.info("验证令牌已保存,用户: {}", user.getUsername());
+ emailService.sendVerificationEmail(email, token);
+
+ return ResponseEntity.ok(Result.ok());
+ }
+ @PostMapping("/checkPassword")
+ public Result<String> checkPassword(@RequestParam Long userId, @RequestParam String password) {
+ boolean isPasswordCorrect = userService.checkPassword(userId, password);
+ if (isPasswordCorrect) {
+ return Result.ok();
+ } else {
+ return Result.error("原始密码输入错误");
+ }
+ }
+
+
+// @SaCheckLogin
+// @Operation(summary = "用户收藏列表", description = "获取用户收藏的种子列表-分页-排序")
+// @ApiResponse(responseCode = "0", description = "操作成功",
+// content = {@Content(mediaType = "application/json",
+// schema = @Schema(implementation = TorrentVO.class))
+// })
+// @PostMapping("/favorite/list")
+// public Result listFavorites(@RequestBody FavoriteParam param) {
+// if (param.getUserId() == null) {
+// return Result.error("缺少 userId");
+// }
+//
+// // 校验排序字段是否合理(可选)
+// param.validOrder(param.getOrderKey(TorrentEntity.class));
+//
+// PageUtil.startPage(param);
+//
+// List<TorrentEntity> list = favoriteService.getUserFavoritesPaged(param.getUserId());
+//
+// return Result.ok(list, PageUtil.getPage(list));
+// }
+//
+
+
}