Эх сурвалжийг харах

新增教研分析单点登录

wangliang 3 жил өмнө
parent
commit
cc1582a471

+ 1 - 1
teachcloud-common/src/main/java/com/qmth/teachcloud/common/contant/SystemConstant.java

@@ -158,7 +158,7 @@ public class SystemConstant {
     public static final int DEFAULT_SESSION_EXPIRE = 1;//过期时间1天
     public static final long REDIS_DEFAULT_EXPIRE_TIME = 24 * 60L * 60L;//过期时间24小时
     public static final long REDIS_CREATE_PDF_EXPIRE_TIME = 1 * 60L * 60L;//过期时间1小时
-    public static final long REDIS_WHU_USER_AUTH_EXPIRE_TIME = 2 * 60L;//过期时间2分钟
+    public static final long REDIS_THIRD_USER_AUTH_EXPIRE_TIME = 2 * 60L;//过期时间2分钟
 
     /**
      * redis mq

+ 1 - 2
teachcloud-common/src/main/java/com/qmth/teachcloud/common/entity/SysUser.java

@@ -128,7 +128,7 @@ public class SysUser extends BaseEntity implements Serializable {
 
     }
 
-    public SysUser(Long schoolId, String loginName, String realName, String mobileNumber, Long orgId) {
+    public SysUser(Long schoolId, String loginName, String realName, String mobileNumber) {
         setId(SystemConstant.getDbUuid());
         this.schoolId = schoolId;
         this.loginName = loginName;
@@ -136,7 +136,6 @@ public class SysUser extends BaseEntity implements Serializable {
         this.mobileNumber = mobileNumber;
         this.pwdCount = 1;
         this.password = SystemConstant.DEFAULT_PASSWORD;
-        this.orgId = orgId;
     }
 
     @Override

+ 8 - 3
teachcloud-report-business/src/main/java/com/qmth/teachcloud/report/business/cache/RedisKeyHelper.java

@@ -9,9 +9,14 @@ package com.qmth.teachcloud.report.business.cache;
  */
 public class RedisKeyHelper {
 
-    private static String whuUserAuthFix = "whu_user_auth:";
+    private static String thirdUserAuthFix = "third_user_auth:";
+    private static String thirdUserAuthReturnUrlFix = "third_user_auth_return_url:";
 
-    public static String whuUserAuth(String key) {
-        return whuUserAuthFix + key;
+    public static String thirdUserAuth(String key) {
+        return thirdUserAuthFix + key;
+    }
+
+    public static String thirdUserAuthReturnUrl(String key) {
+        return thirdUserAuthReturnUrlFix + key;
     }
 }

+ 43 - 0
teachcloud-report-business/src/main/java/com/qmth/teachcloud/report/business/cache/ThirdUserAuthCacheUtil.java

@@ -0,0 +1,43 @@
+package com.qmth.teachcloud.report.business.cache;
+
+import com.qmth.teachcloud.common.bean.dto.UserAuthenticationDto;
+import com.qmth.teachcloud.common.contant.SpringContextHolder;
+import com.qmth.teachcloud.common.contant.SystemConstant;
+import com.qmth.teachcloud.common.util.RedisUtil;
+
+import java.util.concurrent.TimeUnit;
+
+/**
+ * @Description: 武大开发鉴权用户临时授权cache
+ * @Param:
+ * @return:
+ * @Author: wangliang
+ * @Date: 2021/6/29
+ */
+public class ThirdUserAuthCacheUtil {
+    private static RedisUtil redisUtil = SpringContextHolder.getBean(RedisUtil.class);
+
+    public static void setAuthCode(UserAuthenticationDto userAuthenticationDto) {
+        redisUtil.set(RedisKeyHelper.thirdUserAuth(userAuthenticationDto.getUid()), userAuthenticationDto.getCode(), SystemConstant.REDIS_THIRD_USER_AUTH_EXPIRE_TIME, TimeUnit.SECONDS);
+    }
+
+    public static String getAuthCode(String key) {
+        return (String) redisUtil.get(RedisKeyHelper.thirdUserAuth(key));
+    }
+
+    public static void deleteAuthCode(String key) {
+        redisUtil.delete(RedisKeyHelper.thirdUserAuth(key));
+    }
+
+    public static void setAuthReturnUrl(String key, String url) {
+        redisUtil.set(RedisKeyHelper.thirdUserAuthReturnUrl(key), url);
+    }
+
+    public static String getAuthReturnUrl(String key) {
+        return (String) redisUtil.get(RedisKeyHelper.thirdUserAuthReturnUrl(key));
+    }
+
+    public static void deleteAuthReturnUrl(String key) {
+        redisUtil.delete(RedisKeyHelper.thirdUserAuthReturnUrl(key));
+    }
+}

+ 0 - 31
teachcloud-report-business/src/main/java/com/qmth/teachcloud/report/business/cache/WhuUserAuthCacheUtil.java

@@ -1,31 +0,0 @@
-package com.qmth.teachcloud.report.business.cache;
-
-import com.qmth.teachcloud.common.bean.dto.UserAuthenticationDto;
-import com.qmth.teachcloud.common.contant.SpringContextHolder;
-import com.qmth.teachcloud.common.contant.SystemConstant;
-import com.qmth.teachcloud.common.util.RedisUtil;
-
-import java.util.concurrent.TimeUnit;
-
-/**
- * @Description: 武大开发鉴权用户临时授权cache
- * @Param:
- * @return:
- * @Author: wangliang
- * @Date: 2021/6/29
- */
-public class WhuUserAuthCacheUtil {
-    private static RedisUtil redisUtil = SpringContextHolder.getBean(RedisUtil.class);
-
-    public static void setAuthCode(UserAuthenticationDto userAuthenticationDto) {
-        redisUtil.set(RedisKeyHelper.whuUserAuth(userAuthenticationDto.getUid()), userAuthenticationDto.getCode(), SystemConstant.REDIS_WHU_USER_AUTH_EXPIRE_TIME, TimeUnit.SECONDS);
-    }
-
-    public static String getAuthCode(String key) {
-        return (String) redisUtil.get(RedisKeyHelper.whuUserAuth(key));
-    }
-
-    public static void deleteAuthCode(String key) {
-        redisUtil.delete(RedisKeyHelper.whuUserAuth(key));
-    }
-}

+ 15 - 11
teachcloud-report-business/src/main/java/com/qmth/teachcloud/report/business/service/ReportCommonService.java

@@ -3,12 +3,10 @@ package com.qmth.teachcloud.report.business.service;
 import com.qmth.teachcloud.common.entity.BasicAttachment;
 import com.qmth.teachcloud.common.enums.UploadFileEnum;
 import com.qmth.teachcloud.report.business.bean.result.*;
-import com.qmth.teachcloud.report.business.entity.TAExamCourse;
 import com.qmth.teachcloud.report.business.enums.SemesterEnum;
 import org.springframework.web.multipart.MultipartFile;
 
 import java.io.IOException;
-import java.io.UnsupportedEncodingException;
 import java.util.List;
 
 /**
@@ -85,14 +83,15 @@ public interface ReportCommonService {
 
     /**
      * 根据参数查找题目信息
-     * @param examId 考试id
-     * @param courseCode 课程编号
-     * @param teachCollegeId 开课学院id
+     *
+     * @param examId           考试id
+     * @param courseCode       课程编号
+     * @param teachCollegeId   开课学院id
      * @param inspectCollegeId 考察学院id
-     * @param teacherId 授课教师id
+     * @param teacherId        授课教师id
      * @return 结果
      */
-    QuestionListResult findQuestionInfo(Long examId, String courseCode, Long teachCollegeId,Long inspectCollegeId,Long teacherId);
+    QuestionListResult findQuestionInfo(Long examId, String courseCode, Long teachCollegeId, Long inspectCollegeId, Long teacherId);
 
     /**
      * 取总体平均分
@@ -110,6 +109,11 @@ public interface ReportCommonService {
      */
     public void whuLogout() throws IOException;
 
+    /**
+     * 第三方退出
+     */
+    public void thirdLogout() throws IOException;
+
     /**
      * 获取开课课程考试课程总览
      *
@@ -124,7 +128,7 @@ public interface ReportCommonService {
      * 保存附件
      *
      * @param file file
-     * @param md5 md5
+     * @param md5  md5
      * @param type type
      * @return 返回
      */
@@ -133,9 +137,9 @@ public interface ReportCommonService {
     /**
      * 保存附件公用
      *
-     * @param file file
-     * @param md5 md5
-     * @param type type
+     * @param file  file
+     * @param md5   md5
+     * @param type  type
      * @param objId objId
      * @return 结果
      */

+ 22 - 0
teachcloud-report-business/src/main/java/com/qmth/teachcloud/report/business/service/impl/ReportCommonServiceImpl.java

@@ -17,6 +17,7 @@ import com.qmth.teachcloud.common.util.JacksonUtil;
 import com.qmth.teachcloud.common.util.ResultUtil;
 import com.qmth.teachcloud.common.util.ServletUtil;
 import com.qmth.teachcloud.report.business.bean.result.*;
+import com.qmth.teachcloud.report.business.cache.ThirdUserAuthCacheUtil;
 import com.qmth.teachcloud.report.business.entity.*;
 import com.qmth.teachcloud.report.business.enums.*;
 import com.qmth.teachcloud.report.business.service.*;
@@ -633,6 +634,27 @@ public class ReportCommonServiceImpl implements ReportCommonService {
         response.sendRedirect(redirectURL);
     }
 
+    /**
+     * 第三方退出
+     *
+     * @throws IOException
+     */
+    @Override
+    public void thirdLogout() throws IOException {
+        HttpServletRequest request = ServletUtil.getRequest();
+        HttpServletResponse response = ServletUtil.getResponse();
+        HttpSession session = request.getSession();
+        if (Objects.nonNull(session)) {
+            session.invalidate();
+            log.info("logout is come in,session:{}", JacksonUtil.parseJson(session));
+        }
+        SysUser sysUser = (SysUser) ServletUtil.getRequestUser();
+        String redirectURL = ThirdUserAuthCacheUtil.getAuthReturnUrl(String.valueOf(sysUser.getId()));
+        ThirdUserAuthCacheUtil.deleteAuthReturnUrl(String.valueOf(sysUser.getId()));
+        response.setHeader("Access-Control-Allow-Origin", "*");
+        response.sendRedirect(redirectURL);
+    }
+
     /**
      * 获取开课课程考试课程总览
      *

+ 85 - 27
teachcloud-report/src/main/java/com/qmth/teachcloud/report/api/SsoApiController.java

@@ -6,30 +6,36 @@ import com.qmth.boot.api.annotation.BOOL;
 import com.qmth.boot.api.constant.ApiConstant;
 import com.qmth.teachcloud.common.SignatureEntityTest;
 import com.qmth.teachcloud.common.bean.dto.UserAuthenticationDto;
+import com.qmth.teachcloud.common.bean.result.LoginResult;
 import com.qmth.teachcloud.common.config.DictionaryConfig;
 import com.qmth.teachcloud.common.contant.SystemConstant;
 import com.qmth.teachcloud.common.entity.*;
+import com.qmth.teachcloud.common.enums.AppSourceEnum;
 import com.qmth.teachcloud.common.enums.ExceptionResultEnum;
 import com.qmth.teachcloud.common.service.*;
 import com.qmth.teachcloud.common.util.AuthThirdUtil;
 import com.qmth.teachcloud.common.util.JacksonUtil;
+import com.qmth.teachcloud.common.util.Result;
+import com.qmth.teachcloud.common.util.ResultUtil;
 import com.qmth.teachcloud.report.business.bean.params.LoginThirdParam;
-import com.qmth.teachcloud.report.business.cache.WhuUserAuthCacheUtil;
+import com.qmth.teachcloud.report.business.cache.ThirdUserAuthCacheUtil;
+import com.qmth.teachcloud.report.business.service.ReportCommonService;
 import io.swagger.annotations.*;
+import org.apache.commons.lang3.StringUtils;
 import org.slf4j.Logger;
 import org.slf4j.LoggerFactory;
+import org.springframework.transaction.annotation.Transactional;
 import org.springframework.validation.annotation.Validated;
-import org.springframework.web.bind.annotation.RequestBody;
-import org.springframework.web.bind.annotation.RequestMapping;
-import org.springframework.web.bind.annotation.RequestMethod;
-import org.springframework.web.bind.annotation.RestController;
+import org.springframework.web.bind.annotation.*;
 
 import javax.annotation.Resource;
 import javax.servlet.http.HttpServletRequest;
 import javax.servlet.http.HttpServletResponse;
 import java.io.IOException;
+import java.io.UnsupportedEncodingException;
 import java.net.URLDecoder;
 import java.net.URLEncoder;
+import java.security.NoSuchAlgorithmException;
 import java.text.MessageFormat;
 import java.util.Objects;
 import java.util.Optional;
@@ -64,10 +70,17 @@ public class SsoApiController {
     @Resource
     SysRoleService sysRoleService;
 
+    @Resource
+    TeachcloudCommonService teachcloudCommonService;
+
+    @Resource
+    ReportCommonService reportCommonService;
+
     @ApiOperation(value = "单点登录接口")
     @ApiResponses({@ApiResponse(code = 200, message = "单点登录接口", response = Object.class)})
     @RequestMapping(value = "/login", method = RequestMethod.POST)
     @Aac(auth = BOOL.FALSE)
+    @Transactional
     public void login(@ApiParam(value = "接收登录数据信息", required = true) @RequestBody String result, HttpServletRequest request, HttpServletResponse response) throws IOException {
         Optional.ofNullable(result).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("数据为空"));
         String decodeJson = URLDecoder.decode(result, SystemConstant.CHARSET_NAME);
@@ -84,38 +97,83 @@ public class SsoApiController {
                 .eq(SysUser::getEnable, true);
         SysUser sysUser = sysUserService.getOne(sysUserQueryWrapper);
         if (Objects.isNull(sysUser)) {//新增
-            //查询学院id
-            QueryWrapper<SysOrg> sysOrgQueryWrapper = new QueryWrapper<>();
-            sysOrgQueryWrapper.lambda().eq(SysOrg::getSchoolId, basicSchool.getId())
-                    .eq(SysOrg::getName, loginThirdParam.getOrgName())
-                    .eq(SysOrg::getEnable, true);
-            SysOrg sysOrg = sysOrgService.getOne(sysOrgQueryWrapper);
-            Optional.ofNullable(sysOrg).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("学院数据为空"));
-
             sysUser = new SysUser(basicSchool.getId(),
                     loginThirdParam.getLoginName(),
                     Objects.nonNull(loginThirdParam.getRealName()) ? loginThirdParam.getRealName() : loginThirdParam.getLoginName(),
-                    Objects.nonNull(loginThirdParam.getMobileNumber()) ? loginThirdParam.getMobileNumber() : null,
-                    sysOrg.getId());
-            sysUserService.save(sysUser);
-
-            //新增用户和角色关系
-            QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
-            sysRoleQueryWrapper.lambda().eq(SysRole::getType, loginThirdParam.getRole())
-                    .eq(SysRole::getEnable, true);
-            SysRole sysRole = sysRoleService.getOne(sysRoleQueryWrapper);
-            Optional.ofNullable(sysRole).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("角色数据为空"));
-
-            SysUserRole sysUserRole = new SysUserRole(sysUser.getId(), sysRole.getId());
-            sysUserRoleService.save(sysUserRole);
+                    Objects.nonNull(loginThirdParam.getMobileNumber()) ? loginThirdParam.getMobileNumber() : null);
+        } else {
+            sysUser.setSchoolId(basicSchool.getId());
+            if (Objects.nonNull(loginThirdParam.getRealName())) {
+                sysUser.setRealName(loginThirdParam.getRealName());
+            }
+            if (Objects.nonNull(loginThirdParam.getMobileNumber())) {
+                sysUser.setMobileNumber(loginThirdParam.getMobileNumber());
+            }
         }
+        //查询学院id
+        QueryWrapper<SysOrg> sysOrgQueryWrapper = new QueryWrapper<>();
+        sysOrgQueryWrapper.lambda().eq(SysOrg::getSchoolId, basicSchool.getId())
+                .eq(SysOrg::getName, loginThirdParam.getOrgName())
+                .eq(SysOrg::getEnable, true);
+        SysOrg sysOrg = sysOrgService.getOne(sysOrgQueryWrapper);
+        Optional.ofNullable(sysOrg).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("学院数据为空"));
+        sysUser.setOrgId(sysOrg.getId());
+        sysUserService.saveOrUpdate(sysUser);
+
+        //新增用户和角色关系
+        QueryWrapper<SysRole> sysRoleQueryWrapper = new QueryWrapper<>();
+        sysRoleQueryWrapper.lambda().eq(SysRole::getType, loginThirdParam.getRole())
+                .eq(SysRole::getEnable, true);
+        SysRole sysRole = sysRoleService.getOne(sysRoleQueryWrapper);
+        Optional.ofNullable(sysRole).orElseThrow(() -> ExceptionResultEnum.PARAMS_ERROR.exception("角色数据为空"));
+
+        SysUserRole sysUserRole = new SysUserRole(sysUser.getId(), sysRole.getId());
+        sysUserRoleService.save(sysUserRole);
 
         UserAuthenticationDto userAuthenticationDto = new UserAuthenticationDto(String.valueOf(sysUser.getId()), SystemConstant.getUuid());
-        WhuUserAuthCacheUtil.setAuthCode(userAuthenticationDto);
+        ThirdUserAuthCacheUtil.setAuthCode(userAuthenticationDto);
         String pattern = "{0}{1}{2}";
         String code = URLEncoder.encode(MessageFormat.format(pattern, userAuthenticationDto.getUid(), SignatureEntityTest.FIELD_JOINER, SignatureEntityTest.encrypt(userAuthenticationDto.getCode())), SystemConstant.CHARSET_NAME);
 
+        ThirdUserAuthCacheUtil.setAuthReturnUrl(String.valueOf(sysUser.getId()), loginThirdParam.getReturnUrl());
         response.setHeader("Access-Control-Allow-Origin", "*");
         response.sendRedirect(dictionaryConfig.sysDomain().getLoginAuthenUrl() + code);
     }
+
+    @ApiOperation(value = "用户临时授权登录接口")
+    @RequestMapping(value = "/user/authentication/login", method = RequestMethod.POST)
+    @ApiResponses({@ApiResponse(code = 200, message = "返回消息", response = LoginResult.class)})
+    @Aac(auth = BOOL.FALSE)
+    public Result login(@ApiParam(value = "授权码信息", required = true) @RequestParam String code) throws NoSuchAlgorithmException, UnsupportedEncodingException {
+        String[] values = StringUtils.split(URLDecoder.decode(code, SystemConstant.CHARSET_NAME), SignatureEntityTest.FIELD_JOINER);
+        if (Objects.isNull(values) || values.length != 2) {
+            throw ExceptionResultEnum.ERROR.exception("临时授权码出错,请重新获取");
+        }
+        log.info("values:{}", JacksonUtil.parseJson(values));
+        SysUser sysUser = sysUserService.getById(Long.parseLong(values[0]));
+        //用户不存在
+        if (Objects.isNull(sysUser)) {
+            throw ExceptionResultEnum.USER_NO_DATA.exception();
+        }
+        //停用
+        if (!sysUser.getEnable()) {
+            throw ExceptionResultEnum.USER_ENABLE.exception();
+        }
+
+        String userAuthCode = ThirdUserAuthCacheUtil.getAuthCode(values[0]);
+        if (Objects.isNull(userAuthCode) || !Objects.equals(values[1], URLDecoder.decode(SignatureEntityTest.encrypt(userAuthCode), SystemConstant.CHARSET_NAME))) {
+            throw ExceptionResultEnum.ERROR.exception("临时授权码已过期");
+        }
+        LoginResult loginResult = teachcloudCommonService.login(sysUser.getPassword(), sysUser, AppSourceEnum.PRINT_THIRD);
+        ThirdUserAuthCacheUtil.deleteAuthCode(values[0]);
+        return ResultUtil.ok(loginResult);
+    }
+
+    @ApiOperation(value = "用户鉴权退出接口")
+    @RequestMapping(value = "/user/authentication/logout", method = RequestMethod.GET)
+    @ApiResponses({@ApiResponse(code = 200, message = "返回消息", response = Result.class)})
+    @Aac(auth = BOOL.FALSE)
+    public void authenticationLogout() throws IOException {
+        reportCommonService.thirdLogout();
+    }
 }

+ 5 - 6
teachcloud-report/src/main/java/com/qmth/teachcloud/report/api/WudaOpenApiController.java

@@ -20,7 +20,7 @@ import com.qmth.teachcloud.common.service.TeachcloudCommonService;
 import com.qmth.teachcloud.common.util.JacksonUtil;
 import com.qmth.teachcloud.common.util.Result;
 import com.qmth.teachcloud.common.util.ResultUtil;
-import com.qmth.teachcloud.report.business.cache.WhuUserAuthCacheUtil;
+import com.qmth.teachcloud.report.business.cache.ThirdUserAuthCacheUtil;
 import com.qmth.teachcloud.report.business.service.ReportCommonService;
 import com.qmth.teachcloud.report.business.utils.EncrypAES;
 import io.swagger.annotations.*;
@@ -75,7 +75,6 @@ public class WudaOpenApiController {
         log.info("student request.getRemoteUser():{}", JacksonUtil.parseJson(request.getRemoteUser()));
         String uid = request.getRemoteUser();
         if (Objects.isNull(uid)) {
-
             throw ExceptionResultEnum.NOT_LOGIN.exception();
         }
         // 测试用代码 --- 开始 ---
@@ -102,7 +101,7 @@ public class WudaOpenApiController {
     @RequestMapping(value = "/user/authentication/logout", method = RequestMethod.GET)
     @ApiResponses({@ApiResponse(code = 200, message = "返回消息", response = Result.class)})
     @Aac(auth = BOOL.FALSE)
-    public void authenticationLogout(HttpServletRequest request, HttpServletResponse response) throws IOException {
+    public void authenticationLogout() throws IOException {
         reportCommonService.whuLogout();
     }
 
@@ -130,7 +129,7 @@ public class WudaOpenApiController {
         }
         // 测试结束
         UserAuthenticationDto userAuthenticationDto = new UserAuthenticationDto(uid, SystemConstant.getUuid());
-        WhuUserAuthCacheUtil.setAuthCode(userAuthenticationDto);
+        ThirdUserAuthCacheUtil.setAuthCode(userAuthenticationDto);
         String pattern = "{0}{1}{2}";
         String code = URLEncoder.encode(MessageFormat.format(pattern, userAuthenticationDto.getUid(), SignatureEntityTest.FIELD_JOINER, SignatureEntityTest.encrypt(userAuthenticationDto.getCode())), SystemConstant.CHARSET_NAME);
         // 测试开始
@@ -181,12 +180,12 @@ public class WudaOpenApiController {
             throw ExceptionResultEnum.USER_ENABLE.exception();
         }
 
-        String userAuthCode = WhuUserAuthCacheUtil.getAuthCode(values[0]);
+        String userAuthCode = ThirdUserAuthCacheUtil.getAuthCode(values[0]);
         if (Objects.isNull(userAuthCode) || !Objects.equals(values[1], URLDecoder.decode(SignatureEntityTest.encrypt(userAuthCode), SystemConstant.CHARSET_NAME))) {
             throw ExceptionResultEnum.ERROR.exception("临时授权码已过期");
         }
         LoginResult loginResult = teachcloudCommonService.login(sysUser.getPassword(), sysUser, AppSourceEnum.WHU_THIRD);
-        WhuUserAuthCacheUtil.deleteAuthCode(values[0]);
+        ThirdUserAuthCacheUtil.deleteAuthCode(values[0]);
         return ResultUtil.ok(loginResult);
     }