Revert "用户"

This reverts commit f6824511ca617c9421633c44830c938b862e75df.

Reason for revert: <撤销>

Change-Id: Ie4ee5bc5d3fa26981f61c52408ecf2d0a8e45243
diff --git a/src/main/java/com/example/myproject/controller/UserController.java b/src/main/java/com/example/myproject/controller/UserController.java
index 224c138..acda403 100644
--- a/src/main/java/com/example/myproject/controller/UserController.java
+++ b/src/main/java/com/example/myproject/controller/UserController.java
@@ -1,155 +1,190 @@
 package com.example.myproject.controller;
 
-import com.example.myproject.entity.Users;
-import com.example.myproject.repository.UserRepository;
-import com.example.myproject.service.DynamicService;
-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;
-import java.util.ArrayList;
-
 
 @RestController
-@RequestMapping("/echo/user")
+@RequestMapping("/user")
+@Api(value = "用户管理接口", tags = {"用户管理"})
 public class UserController {
 
-    @Autowired
+    @Resource
     private UserService userService;
 
     @Autowired
-    private UserRepository userRepository;
+    private AuthenticationManager authenticationManager;
 
     @Autowired
-    private DynamicService dynamicService;
+    private UserMapper userMapper; // 使用 MyBatis-Plus
 
-    // 接口:生成邀请码
-    @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 VerificationTokenMapper verificationTokenMapper; // 替换 JPA
 
-    //注册
-    @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");
+    private static final Logger logger = LoggerFactory.getLogger(UserController.class);
 
-        // 调用服务层的注册方法
-        String resultMessage = userService.registerUser(username, email, password, role, inviteCode);
-
-        // 返回注册结果
-        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", "用户信息查询失败");
-            }
+            System.out.println("Login successful for user: " + username);
+            return Result.ok(user);
+        } catch (AuthenticationException e) {
+            return Result.error("登录失败");
+        }
+    }
+
+    @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("msg", resultMessage);
+            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");
+    public static class VerificationRequest {
+        private String email;
+        private String code;
 
-        // 调用服务层的修改密码方法
-        String resultMessage = userService.changePassword(userId, oldPassword, newPassword, confirmPassword);
-
-        // 返回修改结果
-        return Map.of("message", resultMessage, "status", resultMessage.equals("密码修改成功") ? "success" : "error");
+        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; }
     }
 
-    // 获取用户个人资料
-    @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("/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 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);
+    @Autowired
+    private EmailService emailService;
+
+    public static class EmailRequest {
+        private String email;
+        public String getEmail() { return email; }
+        public void setEmail(String email) { this.email = email; }
     }
 
-    // 获取用户所有好友的基本信息
-    @GetMapping("/{userId}/friends")
-    public List<Map<String, Object>> getUserFriends(@PathVariable("userId") Long userId) {
-        List<Long> friendIds = dynamicService.getAllFriendIds(userId);  // 注意这里用的是实例对象
-        List<Map<String, Object>> friends = new ArrayList<>();
-
-        for (Long friendId : friendIds) {
-            Optional<Users> userOpt = userRepository.findById(friendId);
-            if (userOpt.isPresent()) {
-                Users user = userOpt.get();
-                Map<String, Object> friendInfo = Map.of(
-                        "id", user.getUserId(),
-                        "avatar", user.getAvatarUrl() != null ? user.getAvatarUrl() : "https://example.com/default-avatar.jpg",
-                        "nickname", user.getUsername() != null ? user.getUsername() : "未知用户",
-                        "email", user.getEmail() != null ? user.getEmail() : "未填写"
-                );
-                friends.add(friendInfo);
-            }
+    @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("未找到与该邮箱地址相关联的用户"));
         }
 
-        return friends;
+        // 生成验证码
+        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));
+//    }
+//
+
 
 
 }
-
-