Kaynağa Gözat

web端单点登录

pengjing 4 ay önce
ebeveyn
işleme
5c533663ae

+ 7 - 0
src/main/java/com/ghsc/partybuild/AppConfig.java

@@ -151,6 +151,13 @@ public class AppConfig {
     @Value("${wechat-pay-config.accessScope}")
     public String accessScope;
 
+    @Value("${portal.isPortalLogin}")
+    public Boolean isPortalLogin;
+    @Value("${portal.oauthUrl}")
+    public String portal_oauthUrl;
+    @Value("${portal.webUrl}")
+    public String portal_webUrl;
+
     /**
      * @Description //TODO 静态文件路径
      * @Date 10:17 2019/10/9

+ 70 - 2
src/main/java/com/ghsc/partybuild/controller/AppController.java

@@ -59,13 +59,25 @@ public class AppController {
 
 
     @GetMapping("")
-    public String Web(HttpServletRequest request, HttpServletResponse response) {
+    public String app(HttpServletRequest request, HttpServletResponse response, String ticket) {
+        if (appConfig.isPortalLogin && !stringUtils.IsNullOrEmpty(ticket)) {
+            if (portalLogin(request, response, ticket)) {
+                return "redirect:/app/main/index.html/#/portalLogin";
+            }
+        }
 
         return "redirect:/app/main/index.html";
+
     }
 
     @GetMapping("web")
-    public String Web() {
+    public String web(HttpServletRequest request, HttpServletResponse response, String ticket) {
+        if (appConfig.isPortalLogin && !stringUtils.IsNullOrEmpty(ticket)) {
+            if (portalLogin(request, response, ticket)) {
+                return "redirect:/app/main/index.html/#/portalLogin";
+            }
+        }
+
         return "redirect:/app/main/index.html";
     }
 
@@ -78,4 +90,60 @@ public class AppController {
         return "redirect:/mobile/index.html/#/index?code=" + (!stringUtils.IsNullOrEmpty(code) ? code : "");
     }
 
+    /**
+     * 单点登录,验证ticket
+     * @param request
+     * @param response
+     * @param ticket
+     * @return
+     */
+    public Boolean portalLogin(HttpServletRequest request, HttpServletResponse response, String ticket) {
+        Boolean result = false;
+        try {
+            String validateUrl = appConfig.portal_oauthUrl + "/lyuapServer/serviceValidate";
+            logger.info("JXCasLogin,ticket:" + ticket);
+            Map<String, String> mapParams = new HashMap<>();
+            mapParams.put("ticket", ticket);
+            mapParams.put("service", appConfig.portal_webUrl);
+            FileInputStream streamCer = new FileInputStream(appConfig.certPath + "/lyuap.cer");
+            String reqData = remoteHelper.SSLGet(mapParams, validateUrl, "UTF-8", streamCer);
+            //String reqData="<cas:authenticationSuccess><cas:user>2001001www</cas:user><cas:attributes>...</cas:attributes></cas:authenticationSuccess>";
+            int i = reqData.indexOf("<cas:user>");
+            int j = reqData.indexOf("</cas:user>");
+
+            String userId = reqData.substring(i + "<cas:user>".length(), j);
+
+            logger.info("PortalLogin,userId:" + userId);
+
+            CfUsers User = userService.getUserByKey(userId);
+            if (org.apache.commons.lang3.StringUtils.isBlank(User.getUserid())) {
+                User = userService.getUserByOAName(userId);
+            }
+            if (User != null && org.apache.commons.lang3.StringUtils.isNotBlank(User.getUsername())) {
+
+                Cookie cookie = new Cookie(jwtUtils.getTokenName(), jwtUtils.generateToken(User.getUserid()));
+                cookie.setHttpOnly(true);
+                cookie.setPath("/");
+                response.addCookie(cookie);
+
+                List<HashMap<String, Object>> roleList = this.roleService.getRoleByUserName(User.getUsername());
+                if (roleList == null || roleList.isEmpty()) {
+                    this.roleService.insertUserRole(User.getUsername(), "0b45886a-a8db-4f85-af76-61a8ea7c1dab");
+                }
+                userService.loginForceStatu(User.getUserid(), 0);
+                logService.log("用户单点登录", User.getUserid(), "PortalLogin");
+
+                result = true;
+
+            } else {
+                logger.info("PortalLogin,单点登陆失败!");
+            }
+
+        } catch (Exception ex) {
+            logger.error("单点登陆异常:" + ex);
+        }
+
+        return result;
+    }
+
 }

+ 76 - 0
src/main/java/com/ghsc/partybuild/controller/portal/OAuthController.java

@@ -0,0 +1,76 @@
+package com.ghsc.partybuild.controller.portal;
+
+import com.ghsc.partybuild.AppConfig;
+import com.ghsc.partybuild.filter.exception.BaseResponse;
+import com.ghsc.partybuild.filter.exception.RespGenerstor;
+import com.ghsc.partybuild.util.StringUtils;
+import lombok.extern.slf4j.Slf4j;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.web.bind.annotation.GetMapping;
+import org.springframework.web.bind.annotation.RequestMapping;
+import org.springframework.web.bind.annotation.RestController;
+
+import java.io.IOException;
+import java.net.HttpURLConnection;
+import java.net.InetAddress;
+import java.net.URL;
+
+
+@RestController
+@RequestMapping(value = "/api/oauth")
+@Slf4j
+public class OAuthController {
+    @Autowired
+    private AppConfig appConfig;
+
+    @Autowired
+    private StringUtils stringUtils;
+
+    @GetMapping("/getOAuthUrl")
+    public BaseResponse<Object> getOAuthUrl() {
+        String url = "";
+        if (appConfig.isPortalLogin) {
+            if (!isUrlReachable(appConfig.portal_oauthUrl)) {
+                return RespGenerstor.fail("", "服务器无法访问统一身份验证平台,请使用党建系统账号密码登录!");
+            }
+
+            url = String.format("%s/lyuapServer/login?service=%s", appConfig.portal_oauthUrl, appConfig.portal_webUrl);
+        }
+
+        return RespGenerstor.success(url);
+    }
+
+    public static boolean isReachable(String address) {
+        try {
+            return InetAddress.getByName(address).isReachable(5000); // 超时时间设置为5秒
+        } catch (Exception e) {
+            e.printStackTrace();
+            return false;
+        }
+    }
+
+    public static boolean isUrlReachable(String urlString) {
+        HttpURLConnection urlConnection = null;
+        try {
+            URL url = new URL(urlString);
+            urlConnection = (HttpURLConnection) url.openConnection();
+            urlConnection.setRequestMethod("GET");
+            urlConnection.setConnectTimeout(5000); // 设置连接超时
+            urlConnection.setReadTimeout(5000);    // 设置读取超时
+            urlConnection.connect();
+
+            int responseCode = urlConnection.getResponseCode();
+            return (responseCode == HttpURLConnection.HTTP_OK);
+        } catch (IOException e) {
+            e.printStackTrace();
+            return false;
+        } finally {
+            if (urlConnection != null) {
+                urlConnection.disconnect();
+            }
+        }
+    }
+
+
+
+}

+ 1 - 0
src/main/java/com/ghsc/partybuild/shiro/ShiroConfiguration.java

@@ -120,6 +120,7 @@ public class ShiroConfiguration {
         filterChainDefinitionMap.put("/wxapi/pay/getOpenID", "anon");
         filterChainDefinitionMap.put("/appApi/fileMgr/showDoc/**", "anon");
         filterChainDefinitionMap.put("/wxapi/cp/**", "anon");
+        filterChainDefinitionMap.put("/api/oauth/**", "anon");
         filterChainDefinitionMap.put("/**", "authc");
 
         // 如果不设置默认会自动寻找Web工程根目录下的"/login.jsp"页面

+ 4 - 0
src/main/resources/application.yml

@@ -166,4 +166,8 @@ wx:
       corpsecret: ohU54VhB-POaD5g4h-ZT3M72BgdAp279VuW_l-v6FWI
       agentId: 1000004
       redirectUrl: www.bowintek.com/ghsc/mobile
+portal:
+  isPortalLogin: true
+  oauthUrl: 'https://cas.gzws.edu.cn'
+  webUrl: ''
 

+ 19 - 1
src/main/resources/static/app/main/app.js

@@ -22,7 +22,7 @@
         //    duration:3
         //});
 
-        $urlRouterProvider.otherwise("/login");
+        $urlRouterProvider.otherwise("/default");
 
         /*
         添加CSS和JS示例
@@ -56,6 +56,24 @@
                     return $ocLazyLoad.load('login.js?' + window.sysVersion);
                 }]
             }
+        }).state("default", {
+            url: "/default",
+            templateUrl: "default.html?" + window.sysVersion,
+            controller: "defaultCtrl",
+            resolve: {
+                load: ['$ocLazyLoad', function ($ocLazyLoad) {
+                    return $ocLazyLoad.load('default.js?' + window.sysVersion);
+                }]
+            }
+        }).state("portalLogin", {
+            url: "/portalLogin",
+            templateUrl: "portalLogin.html?" + window.sysVersion,
+            controller: "portalLoginCtrl",
+            resolve: {
+                load: ['$ocLazyLoad', function ($ocLazyLoad) {
+                    return $ocLazyLoad.load('portalLogin.js?' + window.sysVersion);
+                }]
+            }
         }).state("localLogin", {
             url: "/login1",
             templateUrl: "login.html?" + window.sysVersion,

+ 3 - 3
src/main/resources/static/app/main/controllers.js

@@ -271,7 +271,7 @@
                     }
                 } else {
                     AuthUser.clearUser();
-                    $state.go("localLogin");
+                    $state.go("login");
                 }
 
             });
@@ -304,7 +304,7 @@
                 }*/
                 $rootScope.menuToggle=true;
                 AuthUser.clearUser();
-                $state.go("localLogin");
+                $state.go("login");
 
             }, function (err) {
 
@@ -316,7 +316,7 @@
                     show: true,
                     duration: 3
                 });
-                $state.go("localLogin");
+                $state.go("login");
             });
         };
 

+ 1 - 0
src/main/resources/static/app/main/default.html

@@ -0,0 +1 @@
+<div style="font-size: 26px;font-weight: bold;">系统加载中,请稍等...</div>

+ 31 - 0
src/main/resources/static/app/main/default.js

@@ -0,0 +1,31 @@
+(function ($ang, win) {
+    'use strict';
+    $ang.module('gtPartyApp').controller("defaultCtrl", ['$scope', '$state', '$http', '$loading', '$alert', '$desData', '$modal', 'AuthUser', function ($scope, $state, $http, $loading, $alert, $desData, $modal, AuthUser) {
+        if (AuthUser && AuthUser.getUser().Id && AuthUser.getUser().Id != 'null') {
+            $state.go('homeTabs');
+        } else {
+            $http.get("../../api/oauth/getOAuthUrl", {}).then(function (res) {
+                if (res.data.success && res.data.item) {
+                    window.location.href = res.data.item;
+                } else {
+                    $scope.showMsg('提示', res.data.msg);
+                    $state.go('login');
+                }
+            }, () => {
+                $state.go('login');
+            });
+        }
+
+        $scope.showMsg = function (title, content) {
+            $alert({
+                title: title + ':',
+                content: content,
+                placement: 'top',
+                type: 'info',
+                show: true,
+                duration: 5
+            });
+
+        };
+    }]);
+})(angular, this);

+ 1 - 1
src/main/resources/static/app/main/partyUser/admit/register/edit.js

@@ -74,7 +74,7 @@
         };
 
         $scope.back = function () {
-            $state.go("localLogin");
+            $state.go("login");
         };
 
         //民族

+ 1 - 1
src/main/resources/static/app/main/partyUser/admit/register/success.js

@@ -1,7 +1,7 @@
 var successCtrl = function ($scope, $state, $http, $alert, $loading) {
     $scope.confirmMsg = function () {
         $scope.$hide();
-        $state.go("localLogin");
+        $state.go("login");
     };
 };
 

+ 1 - 0
src/main/resources/static/app/main/portalLogin.html

@@ -0,0 +1 @@
+<div style="font-size: 26px;font-weight: bold;">统一身份信息验证中,请稍等...</div>

+ 45 - 0
src/main/resources/static/app/main/portalLogin.js

@@ -0,0 +1,45 @@
+(function ($ang, win) {
+    'use strict';
+    $ang.module('gtPartyApp').controller("portalLoginCtrl", ['$scope', '$state', '$http', '$loading', '$alert', '$desData', '$modal', 'AuthUser', function ($scope, $state, $http, $loading, $alert, $desData, $modal, AuthUser) {
+        $scope.sysName = window.sysCompanyName;
+        $scope.errorMsg = '';
+        //站点ID
+        $scope.menudatas = {
+            appkey: "appId",
+            defrolekey: "DefaultRoleId",
+            getMenuUrl: '../../api/user/getmenubyuid',
+            toggle: true
+        };
+        $scope.loadCurUser = function () {
+            $http.get("../../api/user/curloginuser", {params: {appkey: $scope.menudatas.appkey}}).then(function (res) {
+                if (res.data.success) {
+                    if (res.data.item) {
+                        angular.extend(res.data.item, {dataDzzdm: res.data.extdata.dataDzzdm});
+                        angular.extend(res.data.item, {gddwdm: res.data.extdata.gddwdm});
+                        angular.extend(res.data.item, {userType: res.data.extdata.userType});
+                        angular.extend(res.data.item, {dataScope: res.data.extdata.dataScope});
+                        angular.extend(res.data.item, {dwId: res.data.extdata.dwId});
+                        angular.extend(res.data.item, {dwName: res.data.extdata.dwName});
+                        angular.extend(res.data.item, {oaUserId: res.data.extdata.oaUserId});
+                        angular.extend(res.data.item, {oaIdCard: res.data.extdata.oaIdCard});
+                        angular.extend(res.data.item, {generalPartyCode: res.data.extdata.generalPartyCode});
+                        AuthUser.setUser(res.data.item);
+                        AuthUser.clearExtData();
+
+                        $state.go('homeTabs');
+                    }
+                } else {
+                    $scope.showMsg('失败','单点登录失败!');
+                    $state.go('login');
+                }
+            }, () => {
+                $scope.showMsg('失败','单点登录失败!');
+                $state.go('login');
+            });
+        };
+
+
+        $scope.loadCurUser();
+
+    }]);
+})(angular, this);