Просмотр исходного кода

feat: 添加门户登录功能,支持通过门户id进行用户注册和信息更新

201250038 1 год назад
Родитель
Сommit
40e9acec84

+ 2 - 2
src/main/java/com/njuzr/eaibackend/config/JWTAuthenticationFilter.java

@@ -1,7 +1,6 @@
 package com.njuzr.eaibackend.config;
 
 import com.njuzr.eaibackend.exception.MyAuthenticationEntryPoint;
-import com.njuzr.eaibackend.exception.MyException;
 import com.njuzr.eaibackend.service.MyUserDetailService;
 import com.njuzr.eaibackend.utils.JWTTokenUtil;
 import jakarta.servlet.FilterChain;
@@ -11,9 +10,9 @@ import jakarta.servlet.http.HttpServletResponse;
 import lombok.extern.slf4j.Slf4j;
 import org.springframework.security.authentication.CredentialsExpiredException;
 import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
-import org.springframework.security.core.AuthenticationException;
 import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.core.userdetails.UserDetails;
+import org.springframework.stereotype.Component;
 import org.springframework.web.filter.OncePerRequestFilter;
 
 import java.io.IOException;
@@ -25,6 +24,7 @@ import java.io.IOException;
  */
 
 @Slf4j
+@Component
 public class JWTAuthenticationFilter extends OncePerRequestFilter {
 
     private final JWTTokenUtil jwtTokenUtil;

+ 8 - 9
src/main/java/com/njuzr/eaibackend/config/SecurityConfig.java

@@ -3,6 +3,7 @@ package com.njuzr.eaibackend.config;
 import com.njuzr.eaibackend.exception.MyAccessDeniedHandler;
 import com.njuzr.eaibackend.exception.MyAuthenticationEntryPoint;
 import com.njuzr.eaibackend.service.MyUserDetailService;
+import com.njuzr.eaibackend.service.UserService;
 import com.njuzr.eaibackend.utils.JWTTokenUtil;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.context.annotation.Bean;
@@ -34,16 +35,15 @@ public class SecurityConfig {
 
     private final MyAccessDeniedHandler accessDeniedHandler;
 
-    private final MyUserDetailService userDetailsService;
-
-    private final JWTTokenUtil jwtTokenUtil;
+    private final JWTAuthenticationFilter jwtAuthenticationFilter;
 
     @Autowired
-    public SecurityConfig(MyAuthenticationEntryPoint unauthorizedHandler, MyAccessDeniedHandler accessDeniedHandler, MyUserDetailService userDetailsService, JWTTokenUtil jwtTokenUtil) {
+    public SecurityConfig(MyAuthenticationEntryPoint unauthorizedHandler,
+                          MyAccessDeniedHandler accessDeniedHandler,
+                          JWTAuthenticationFilter jwtAuthenticationFilter) {
         this.unauthorizedHandler = unauthorizedHandler;
         this.accessDeniedHandler = accessDeniedHandler;
-        this.userDetailsService = userDetailsService;
-        this.jwtTokenUtil = jwtTokenUtil;
+        this.jwtAuthenticationFilter = jwtAuthenticationFilter;
     }
 
     @Bean
@@ -56,7 +56,8 @@ public class SecurityConfig {
                                 "/api/user/updatePassword",
                                 "/api/user/verifyCode",
                                 "/api/onlyoffice/**",
-                                "/api/assignment/**").permitAll() // 允许公开访问的路径
+                                "/api/assignment/**",
+                                "api/auth/loginByPortal").permitAll() // 允许公开访问的路径
                         .anyRequest().authenticated() // 其他所有请求需要认证
                 )
                 .exceptionHandling(exception -> exception
@@ -79,8 +80,6 @@ public class SecurityConfig {
         authenticationFilter.setAuthenticationFailureHandler(new MyAuthenticationFailureHandler());
 
         // JWT过滤器(在过滤器中已经实现了Token解析,不通过Provider解析)
-        JWTAuthenticationFilter jwtAuthenticationFilter = new JWTAuthenticationFilter(jwtTokenUtil, userDetailsService);
-
         // 将自定义的Filter添加到Spring Security过滤器链中
         http.addFilterBefore(jwtAuthenticationFilter, UsernamePasswordAuthenticationFilter.class);
         http.addFilter(authenticationFilter);

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

@@ -18,6 +18,7 @@ public class AuthenticationController {
 
     /**
      * 用户登陆学号(officialNumber)和密码(password)进行登陆
+     *
      * @param userLoginDTO officialNumber、password
      * @return 如果成功登陆,则返回登陆用户的身份信息和Token;如果失败,则返回具体原因。
      */
@@ -28,6 +29,7 @@ public class AuthenticationController {
 
     /**
      * 邮箱验证登录
+     *
      * @param emailLoginDTO officialEmail、verifyCode
      * @return 如果成功登陆,则返回登陆用户的身份信息和Token;如果失败,则返回具体原因。
      */
@@ -36,5 +38,16 @@ public class AuthenticationController {
         return authenticationService.loginByEmail(emailLoginDTO);
     }
 
+    /**
+     * 通门户登录
+     *
+     * @param token id_token
+     * @return 如果成功登陆,则返回登陆用户的身份信息和Token;如果失败,则返回具体原因。
+     */
+    @GetMapping("/loginByPortal")
+    public MyResponse loginByPortal(@RequestParam(value = "id_token") String token) {
+        return authenticationService.loginByPortal(token);
+    }
+
 
 }

+ 2 - 0
src/main/java/com/njuzr/eaibackend/dto/user/UserRegisterDTO.java

@@ -33,4 +33,6 @@ public class UserRegisterDTO { // 用户注册,前传后
 
     @NotNull(message = "role不能为空")
     private Role role; // 用户角色:学生、教师、管理员(必填)
+
+    private Integer pid; // 用户门户id
 }

+ 2 - 0
src/main/java/com/njuzr/eaibackend/po/base/BaseUser.java

@@ -38,4 +38,6 @@ public class BaseUser {
     private String phone; // 联系方式(选填)
 
     private String contentEmail; // 联系邮箱(选填)
+
+    private String pid; // 门户id
 }

+ 1 - 0
src/main/java/com/njuzr/eaibackend/service/AuthenticationService.java

@@ -10,4 +10,5 @@ public interface AuthenticationService {
 
     MyResponse loginByEmail(EmailLoginDTO emailLoginDTO);
 
+    MyResponse loginByPortal(String token);
 }

+ 13 - 0
src/main/java/com/njuzr/eaibackend/service/UserService.java

@@ -6,6 +6,7 @@ import com.njuzr.eaibackend.dto.user.PasswordChangeDTO;
 import com.njuzr.eaibackend.dto.user.UserRegisterDTO;
 import com.njuzr.eaibackend.dto.user.UserUpdateDTO;
 import com.njuzr.eaibackend.enums.Role;
+import com.njuzr.eaibackend.exception.MyException;
 import com.njuzr.eaibackend.po.User;
 import com.njuzr.eaibackend.vo.UserVO;
 
@@ -41,9 +42,21 @@ public interface UserService {
     UserVO updateUser(Long id, UserUpdateDTO userDTO);
 
 
+    /**
+     * 根据用户门户id更新用户
+     * @param pid
+     */
+    UserVO updateUserByPid(Integer pid, UserUpdateDTO userDTO);
+
     /**
      * 用户更新密码
      */
     void updatePassword(PasswordChangeDTO passwordChangeDTO);
 
+    /**
+     * 根据用户pid判断用户是否存在
+     * @param pid
+     * @return
+     */
+    boolean userExists(Integer pid);
 }

+ 49 - 5
src/main/java/com/njuzr/eaibackend/service/impl/AuthenticationServiceImpl.java

@@ -3,11 +3,15 @@ package com.njuzr.eaibackend.service.impl;
 import com.njuzr.eaibackend.controller.MyResponse;
 import com.njuzr.eaibackend.dto.auth.EmailLoginDTO;
 import com.njuzr.eaibackend.dto.auth.UserLoginDTO;
+import com.njuzr.eaibackend.dto.user.UserRegisterDTO;
+import com.njuzr.eaibackend.dto.user.UserUpdateDTO;
+import com.njuzr.eaibackend.enums.Role;
 import com.njuzr.eaibackend.exception.MyException;
 import com.njuzr.eaibackend.mapper.UserMapper;
 import com.njuzr.eaibackend.po.MyUserDetails;
 import com.njuzr.eaibackend.po.User;
 import com.njuzr.eaibackend.service.AuthenticationService;
+import com.njuzr.eaibackend.service.UserService;
 import com.njuzr.eaibackend.utils.JWTTokenUtil;
 import com.njuzr.eaibackend.utils.ModelMapperUtil;
 import com.njuzr.eaibackend.vo.auth.UserLoginVO;
@@ -23,6 +27,8 @@ import org.springframework.security.core.context.SecurityContextHolder;
 import org.springframework.security.core.userdetails.UsernameNotFoundException;
 import org.springframework.stereotype.Service;
 
+import java.util.Map;
+
 
 @Slf4j
 @Service
@@ -36,6 +42,8 @@ public class AuthenticationServiceImpl implements AuthenticationService {
     private UserMapper userMapper;
     @Autowired
     private RedisTemplate<String, Object> redisTemplate;
+    @Autowired
+    private UserService userService;
 
 
     @Override
@@ -62,10 +70,10 @@ public class AuthenticationServiceImpl implements AuthenticationService {
 
         } catch (BadCredentialsException e) {
             log.error("登陆失败,密码错误");
-            return MyResponse.error(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase()+":"+"用户名或密码错误");
+            return MyResponse.error(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase() + ":" + "用户名或密码错误");
         } catch (UsernameNotFoundException e) {
             log.error("登陆失败,找不到该用户");
-            return MyResponse.error(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase()+":"+"用户名或密码错误");
+            return MyResponse.error(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase() + ":" + "用户名或密码错误");
         }
     }
 
@@ -78,14 +86,14 @@ public class AuthenticationServiceImpl implements AuthenticationService {
             throw new MyException(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase() + ":" + "验证码已过期");
         }
         // 验证码校验
-        if(!storedCode.equals(emailLoginDTO.getVerifyCode())) {
+        if (!storedCode.equals(emailLoginDTO.getVerifyCode())) {
             throw new MyException(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase() + ":" + "验证码错误");
         }
 
         User user = userMapper.selectByOfficialEmail(emailLoginDTO.getOfficialEmail());
-        if(user == null) {
+        if (user == null) {
             log.error("登陆失败,找不到该用户");
-            return MyResponse.error(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase()+":"+"邮箱未注册");
+            return MyResponse.error(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase() + ":" + "邮箱未注册");
         }
         String jwt = jwtTokenUtil.generateToken(user.getOfficialNumber());
         log.info("生成jwt成功,token信息:" + jwt);
@@ -94,4 +102,40 @@ public class AuthenticationServiceImpl implements AuthenticationService {
         return MyResponse.success(userLoginVO);
     }
 
+    @Override
+    public MyResponse loginByPortal(String token) {
+        // 从门户返回的jwt中解析用户信息
+        Map<String, Object> userInfoMap = jwtTokenUtil.parseClaim(token).getBody().get("user_info", Map.class);
+        log.info("解析出的用户信息:{}", userInfoMap.toString());
+        //pid:门户用户id
+        Integer pid = Integer.valueOf(userInfoMap.get("id").toString());
+        String username = userInfoMap.get("username").toString();
+        String name = userInfoMap.get("name").toString();
+        String email = userInfoMap.get("email").toString();
+        String phone = userInfoMap.get("phone").toString();
+        Role role = Role.valueOf(userInfoMap.get("role").toString());
+        // 如果EAI数据库中没有该用户,则添加该用户
+        if (!userService.userExists(pid)) {
+            log.info("用户不存在,添加用户{}", phone);
+            UserRegisterDTO reg = new UserRegisterDTO();
+            reg.setPid(pid);
+            reg.setOfficialEmail(email);
+            reg.setOfficialNumber(phone);
+            reg.setRole(role);
+            reg.setName(name);
+            reg.setPassword("no_password");
+            userService.createUser(reg);
+        } else {
+            // 否则更新用户信息
+            UserUpdateDTO update = new UserUpdateDTO();
+            update.setContentEmail(email);
+            update.setPhone(phone);
+            userService.updateUserByPid(pid, update);
+        }
+        UserLoginVO userLoginVO = ModelMapperUtil.map(userMapper.selectByOfficialNumber(phone), UserLoginVO.class);
+        userLoginVO.setToken(token);
+        return MyResponse.success(userLoginVO);
+    }
+
+
 }

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

@@ -58,19 +58,19 @@ public class UserServiceImpl implements UserService {
 
 
     @Override
-    public UserVO createUser(UserRegisterDTO userDTO) throws MyException {
-        // 从Redis中获取验证码
-        final String key = "registerVerifyCode:" + userDTO.getOfficialEmail();
-        String storedCode = (String) redisTemplate.opsForValue().get(key);
-
-        if (storedCode == null) {
-            throw new MyException(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase() + ":" + "验证码已过期");
-        }
-        // 验证码校验
-        if (storedCode.equals(userDTO.getVerifyCode())) {
+    public UserVO createUser(UserRegisterDTO userDTO) {
+//        // 从Redis中获取验证码
+//        final String key = "registerVerifyCode:" + userDTO.getOfficialEmail();
+//        String storedCode = (String) redisTemplate.opsForValue().get(key);
+//
+//        if (storedCode == null) {
+//            throw new MyException(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase() + ":" + "验证码已过期");
+//        }
+//        // 验证码校验
+//        if (storedCode.equals(userDTO.getVerifyCode())) {
             User targetUser = ModelMapperUtil.map(userDTO, User.class);
 
-            targetUser.setPassword(new BCryptPasswordEncoder().encode(targetUser.getPassword())); // 密码加密存储
+//            targetUser.setPassword(new BCryptPasswordEncoder().encode(targetUser.getPassword())); // 密码加密存储
             targetUser.setCreateTime(new Date()); // 设置创建时间
 
             // 同一个邮箱、学号只能注册一次
@@ -85,18 +85,20 @@ public class UserServiceImpl implements UserService {
 
             log.info("User创建完毕,User对象如下:" + targetUser);
 
-            redisTemplate.delete(key); //注册成功后删除验证码
+//            redisTemplate.delete(key); //注册成功后删除验证码
 
             return ModelMapperUtil.map(targetUser, UserVO.class);
 
-        } else {
-            throw new MyException(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase() + ":" + "验证码错误");
         }
-    }
+//        else {
+//            throw new MyException(HttpStatus.BAD_REQUEST.value(), HttpStatus.BAD_REQUEST.getReasonPhrase() + ":" + "验证码错误");
+//        }
+//    }
 
 
     /**
      * 更新用户信息
+     *
      * @param userDTO
      * @return
      */
@@ -117,6 +119,14 @@ public class UserServiceImpl implements UserService {
         return null;
     }
 
+    @Override
+    public UserVO updateUserByPid(Integer pid, UserUpdateDTO userDTO) {
+        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
+        queryWrapper.eq("pid", pid);
+        User user = userMapper.selectOne(queryWrapper);
+        return this.updateUser(user.getId(), userDTO);
+    }
+
 
     /**
      * 更新密码
@@ -149,6 +159,13 @@ public class UserServiceImpl implements UserService {
         }
     }
 
+    @Override
+    public boolean userExists(Integer pid) {
+        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
+        queryWrapper.eq("pid", pid);
+        return userMapper.exists(queryWrapper);
+    }
+
     /**
      * 查看学号是否不存在
      *