瀏覽代碼

fix: 同一邮箱或学号禁止重复注册;查询接口采用token中的id而非前端传入的id

201250038 1 年之前
父節點
當前提交
451ce6b760

+ 0 - 2
src/main/java/com/njuzr/eaibackend/controller/AuthenticationController.java

@@ -30,14 +30,12 @@ import org.springframework.web.bind.annotation.*;
 public class AuthenticationController {
 
     private final AuthenticationManager authenticationManager;
-    private final UserService userService;
 
     private final JWTTokenUtil jwtTokenUtil;
 
     @Autowired
     public AuthenticationController(AuthenticationManager authenticationManager, UserService userService, JWTTokenUtil jwtTokenUtil) {
         this.authenticationManager = authenticationManager;
-        this.userService = userService;
         this.jwtTokenUtil = jwtTokenUtil;
     }
 

+ 4 - 5
src/main/java/com/njuzr/eaibackend/controller/CourseController.java

@@ -7,7 +7,6 @@ import com.njuzr.eaibackend.dto.course.CourseQueryDTO;
 import com.njuzr.eaibackend.dto.course.CourseUpdateDTO;
 import com.njuzr.eaibackend.dto.course.EnrollDTO;
 import com.njuzr.eaibackend.po.Course;
-import com.njuzr.eaibackend.po.Enrollment;
 import com.njuzr.eaibackend.po.MyUserDetails;
 import com.njuzr.eaibackend.po.User;
 import com.njuzr.eaibackend.service.CourseService;
@@ -76,9 +75,9 @@ public class CourseController {
      * @param studentId
      * @return
      */
-    @GetMapping("/byStudent/{studentId}")
+    @GetMapping("/byStudent")
     public MyResponse findCourseByStudentId(
-            @PathVariable Long studentId,
+            @AuthenticationPrincipal(expression = "id") Long studentId,
             @RequestParam(value = "page", defaultValue = "1") int currentPage,
             @RequestParam(value = "size", defaultValue = "10") int pageSize
     ) {
@@ -96,9 +95,9 @@ public class CourseController {
      * @return
      */
     @PreAuthorize("hasRole('TEACHER')")
-    @GetMapping("/byTeacher/{teacherId}")
+    @GetMapping("/byTeacher")
     public MyResponse findByTeacherId(
-            @PathVariable Long teacherId,
+            @AuthenticationPrincipal(expression = "id") Long teacherId,
             @RequestParam(value = "page", defaultValue = "1") int currentPage,
             @RequestParam(value = "size", defaultValue = "10") int pageSize
     ) {

+ 38 - 15
src/main/java/com/njuzr/eaibackend/service/impl/UserServiceImpl.java

@@ -86,11 +86,6 @@ public class UserServiceImpl implements UserService {
     //TODO:   注册DEMO:学生老师都可自行注册账号,管理员那套不需要修改/弃用,学生注册这套已经有完整逻辑,直接使用
     @Override
     public UserVO createUser(UserRegisterDTO userDTO) throws MyException{
-        Role role = userDTO.getRole();
-//        if (role != Role.STUDENT) { // 只允许注册学生账号
-//            throw new MyException(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase()+":"+"权限不够");
-//        }
-
         // 从Redis中获取验证码
         final String key = "verifyCode:" + userDTO.getOfficialEmail();
         String storedCode = (String) redisTemplate.opsForValue().get(key);
@@ -105,7 +100,9 @@ public class UserServiceImpl implements UserService {
             targetUser.setPassword(new BCryptPasswordEncoder().encode(targetUser.getPassword())); // 密码加密存储
             targetUser.setCreateTime(new Date()); // 设置创建时间
 
-            if (isUserNotExists(targetUser.getOfficialNumber())) {
+            // 同一个邮箱、学号只能注册一次
+            if (isOfficialNumberNotExists(targetUser.getOfficialNumber())
+                    && isEmailNotExists(targetUser.getOfficialEmail())) {
                 int status = userMapper.insert(targetUser);
                 if (status == 0) {
                     log.error("createUser -- 数据库插入错误:");
@@ -169,8 +166,9 @@ public class UserServiceImpl implements UserService {
 
         targetUser.setCreateTime(new Date());
 
-        // 检查用户是否存在
-        if (isUserNotExists(targetUser.getOfficialNumber())) {
+        // 同一个邮箱、学号只能注册一次
+        if (isOfficialNumberNotExists(targetUser.getOfficialNumber())
+                && isEmailNotExists(targetUser.getOfficialEmail())) {
             int code =  userMapper.insert(targetUser);
             if (code == 0) {
                 log.error("createUser -- 数据库插入错误:");
@@ -294,6 +292,11 @@ public class UserServiceImpl implements UserService {
         processUsers(users);
     }
 
+
+    /**
+     * 批量创建用户,从csv文件中读取数据
+     * @param file csv文件
+     */
     @Override
     public void batchCreateUsersFromCsv(MultipartFile file) throws Exception {
         CSVReader csvReader = new CSVReader(new InputStreamReader(file.getInputStream()));
@@ -309,11 +312,13 @@ public class UserServiceImpl implements UserService {
         String[] nextRecord;
         while ((nextRecord = csvReader.readNext()) != null) {
             String officialNumber = String.valueOf(nextRecord[numberCol]);
-            if (isUserNotExists(officialNumber)) {
+            String email = String.valueOf(nextRecord[emailCol]);
+            if (isOfficialNumberNotExists(officialNumber)
+                    && isEmailNotExists(email)) {
                 User user = new User();
                 user.setName(String.valueOf(nextRecord[nameCol]));
                 user.setOfficialNumber(officialNumber);
-                user.setOfficialEmail(String.valueOf(nextRecord[emailCol]));
+                user.setOfficialEmail(String.valueOf(email));
                 user.setRole(Role.STUDENT); // 批量创建只创建学生账号
                 user.setCreateTime(new Date());
 
@@ -329,11 +334,11 @@ public class UserServiceImpl implements UserService {
 
 
     /**
-     * 查看用户是否不存在,如果用户不存在,则返回true
-     * @param officialNumber
-     * @return
+     * 查看学号是否不存在
+     * @param officialNumber 学号
+     * @return true表示不存在,false表示存在
      */
-    private boolean isUserNotExists(String officialNumber) throws MyException{
+    private boolean isOfficialNumberNotExists(String officialNumber) throws MyException{
         QueryWrapper<User> queryWrapper = new QueryWrapper<>();
         queryWrapper.eq("official_number", officialNumber);
         User existingUser = userMapper.selectOne(queryWrapper);
@@ -344,8 +349,26 @@ public class UserServiceImpl implements UserService {
         return true;
     }
 
+
+    /**
+     * 查看邮箱是否不存在
+     * @param email 邮箱
+     * @return true表示不存在,false表示存在
+     */
+    private boolean isEmailNotExists(String email) throws MyException{
+        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
+        queryWrapper.eq("official_email", email);
+        User existingUser = userMapper.selectOne(queryWrapper);
+        if (existingUser != null) {
+            log.error("用户已存在,邮箱{}重复", email);
+            throw new MyException(400, "用户已存在,请检查邮箱信息");
+        }
+        return true;
+    }
+
+
     /**
-     * 检查用户是否存在,如果存在则返回true;不存在则报错
+     * 检查用户ID是否存在,如果存在则返回true;不存在则报错
      * @param id
      * @return
      * @throws MyException