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

华为WeLink应用集成功能

fancy 5 лет назад
Родитель
Сommit
7d317929da

+ 2 - 0
o2server/x_base_core_project/src/main/java/com/x/base/core/project/config/WeLink.java

@@ -57,6 +57,8 @@ public class WeLink extends ConfigObject {
         this.oapiAddress = default_oapiAddress;
     }
 
+    public static String WeLink_Auth_Head_Key = "x-wlk-Authorization";
+
     private static String cachedAccessToken;
     private static Date cachedAccessTokenDate;
 

+ 2 - 0
o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/jaxrs/ActionApplication.java

@@ -11,6 +11,7 @@ import com.x.organization.assemble.authentication.jaxrs.dingding.DingdingAction;
 import com.x.organization.assemble.authentication.jaxrs.oauth.OauthAction;
 import com.x.organization.assemble.authentication.jaxrs.qiyeweixin.QiyeweixinAction;
 import com.x.organization.assemble.authentication.jaxrs.sso.SsoAction;
+import com.x.organization.assemble.authentication.jaxrs.welink.WeLinkAction;
 import com.x.organization.assemble.authentication.jaxrs.zhengwudingding.ZhengwuDingdingAction;
 
 @ApplicationPath("jaxrs")
@@ -24,6 +25,7 @@ public class ActionApplication extends AbstractActionApplication {
 		classes.add(QiyeweixinAction.class);
 		classes.add(DingdingAction.class);
 		classes.add(ZhengwuDingdingAction.class);
+		classes.add(WeLinkAction.class);
 		return classes;
 	}
 

+ 10 - 0
o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/jaxrs/WeLinkJaxrsFilter.java

@@ -0,0 +1,10 @@
+package com.x.organization.assemble.authentication.jaxrs;
+
+import com.x.base.core.project.jaxrs.AnonymousCipherManagerUserJaxrsFilter;
+
+import javax.servlet.annotation.WebFilter;
+
+@WebFilter(urlPatterns = "/jaxrs/welink/*", asyncSupported = true)
+public class WeLinkJaxrsFilter extends AnonymousCipherManagerUserJaxrsFilter {
+
+}

+ 148 - 0
o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/jaxrs/welink/ActionLogin.java

@@ -0,0 +1,148 @@
+package com.x.organization.assemble.authentication.jaxrs.welink;
+
+import com.rometools.rome.feed.impl.ToStringBean;
+import com.x.base.core.container.EntityManagerContainer;
+import com.x.base.core.container.factory.EntityManagerContainerFactory;
+import com.x.base.core.entity.JpaObject;
+import com.x.base.core.project.bean.NameValuePair;
+import com.x.base.core.project.bean.WrapCopier;
+import com.x.base.core.project.bean.WrapCopierFactory;
+import com.x.base.core.project.config.Config;
+import com.x.base.core.project.config.WeLink;
+import com.x.base.core.project.connection.HttpConnection;
+import com.x.base.core.project.http.ActionResult;
+import com.x.base.core.project.http.EffectivePerson;
+import com.x.base.core.project.http.HttpToken;
+import com.x.base.core.project.http.TokenType;
+import com.x.base.core.project.logger.Logger;
+import com.x.base.core.project.logger.LoggerFactory;
+import com.x.organization.assemble.authentication.Business;
+import com.x.organization.core.entity.Person;
+import org.apache.commons.lang3.StringUtils;
+import org.apache.commons.lang3.builder.ToStringBuilder;
+import org.apache.commons.lang3.builder.ToStringStyle;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import java.util.ArrayList;
+import java.util.List;
+
+/**
+ * Created by fancyLou on 2020-07-27.
+ * Copyright © 2020 O2. All rights reserved.
+ */
+public class ActionLogin extends BaseAction {
+
+    private static Logger logger = LoggerFactory.getLogger(ActionLogin.class);
+
+    ActionResult<Wo> execute(HttpServletRequest request, HttpServletResponse response, EffectivePerson effectivePerson,
+                             String code) throws Exception {
+        ActionResult<Wo> result = new ActionResult<>();
+        try (EntityManagerContainer emc = EntityManagerContainerFactory.instance().create()) {
+            String url = "https://open.welink.huaweicloud.com/api/auth/v2/userid?code="+code;
+            logger.info(url);
+            List<NameValuePair> heads = new ArrayList<>();
+            heads.add(new NameValuePair(WeLink.WeLink_Auth_Head_Key, Config.weLink().accessToken()));
+            Resp resp = HttpConnection.getAsObject(url, heads, Resp.class);
+            logger.info(resp.toString());
+            if (!resp.getCode().equals("0")) {
+                throw new ExceptionWeLink(resp.getCode(), resp.getMessage());
+            }
+            String userId = resp.getUserId();
+            Business business = new Business(emc);
+            String personId = business.person().getWithCredential(userId);
+            if (StringUtils.isEmpty(personId)) {
+                throw new ExceptionPersonNotExist(userId);
+            }
+            Person person = emc.find(personId, Person.class);
+            Wo wo = Wo.copier.copy(person);
+            List<String> roles = business.organization().role().listWithPerson(person.getDistinguishedName());
+            wo.setRoleList(roles);
+            EffectivePerson effective = new EffectivePerson(wo.getDistinguishedName(), TokenType.user,
+                    Config.token().getCipher());
+            wo.setToken(effective.getToken());
+            HttpToken httpToken = new HttpToken();
+            httpToken.setToken(request, response, effective);
+            result.setData(wo);
+        }
+        return result;
+    }
+
+
+    public static class Resp {
+        private String code;
+        private String message;
+        private String userId;
+        private String tenantId;//租户id
+
+        public String getCode() {
+            return code;
+        }
+
+        public void setCode(String code) {
+            this.code = code;
+        }
+
+        public String getMessage() {
+            return message;
+        }
+
+        public void setMessage(String message) {
+            this.message = message;
+        }
+
+        public String getUserId() {
+            return userId;
+        }
+
+        public void setUserId(String userId) {
+            this.userId = userId;
+        }
+
+        public String getTenantId() {
+            return tenantId;
+        }
+
+        public void setTenantId(String tenantId) {
+            this.tenantId = tenantId;
+        }
+
+        @Override
+        public String toString() {
+            return ToStringBuilder.reflectionToString(this, ToStringStyle.JSON_STYLE);
+        }
+    }
+
+
+    public static class Wo extends Person {
+
+        private static final long serialVersionUID = 4901269474728548509L;
+
+        public static List<String> Excludes = new ArrayList<>(JpaObject.FieldsInvisible);
+
+        static {
+            Excludes.add("password");
+        }
+
+        static WrapCopier<Person, Wo> copier = WrapCopierFactory.wo(Person.class, Wo.class, null, Excludes);
+
+        private String token;
+        private List<String> roleList;
+
+        public String getToken() {
+            return token;
+        }
+
+        public void setToken(String token) {
+            this.token = token;
+        }
+
+        public List<String> getRoleList() {
+            return roleList;
+        }
+
+        public void setRoleList(List<String> roleList) {
+            this.roleList = roleList;
+        }
+    }
+}

+ 34 - 0
o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/jaxrs/welink/BaseAction.java

@@ -0,0 +1,34 @@
+package com.x.organization.assemble.authentication.jaxrs.welink;
+
+import com.x.base.core.project.jaxrs.StandardJaxrsAction;
+import com.x.base.core.project.logger.Logger;
+import com.x.base.core.project.logger.LoggerFactory;
+import com.x.base.core.project.tools.DefaultCharset;
+import org.apache.commons.io.IOUtils;
+
+import javax.net.ssl.HttpsURLConnection;
+import java.io.InputStream;
+import java.net.URL;
+
+abstract class BaseAction extends StandardJaxrsAction {
+
+	private static Logger logger = LoggerFactory.getLogger(BaseAction.class);
+
+	protected String get(String address) throws Exception {
+		HttpsURLConnection connection = null;
+		URL url = new URL(address);
+		connection = (HttpsURLConnection) url.openConnection();
+		connection.setRequestMethod("GET");
+		connection.setUseCaches(false);
+		connection.setDoOutput(false);
+		connection.setDoInput(true);
+		/** 访问主机上的端口 */
+		connection.connect();
+		byte[] buffer = null;
+		try (InputStream input = connection.getInputStream()) {
+			buffer = IOUtils.toByteArray(input);
+			String str = new String(buffer, DefaultCharset.name);
+			return str;
+		}
+	}
+}

+ 12 - 0
o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/jaxrs/welink/ExceptionPersonNotExist.java

@@ -0,0 +1,12 @@
+package com.x.organization.assemble.authentication.jaxrs.welink;
+
+import com.x.base.core.project.exception.PromptException;
+
+class ExceptionPersonNotExist extends PromptException {
+
+	private static final long serialVersionUID = 4132300948670472899L;
+
+	ExceptionPersonNotExist(String name) {
+		super("person:{} not exist.", name);
+	}
+}

+ 12 - 0
o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/jaxrs/welink/ExceptionWeLink.java

@@ -0,0 +1,12 @@
+package com.x.organization.assemble.authentication.jaxrs.welink;
+
+import com.x.base.core.project.exception.PromptException;
+
+class ExceptionWeLink extends PromptException {
+
+	private static final long serialVersionUID = 4132300948670472899L;
+
+	ExceptionWeLink(String errcode, String errmsg) {
+		super("WeLink返回错误: errcode: {}, errmsg:{}.", errcode, errmsg);
+	}
+}

+ 52 - 0
o2server/x_organization_assemble_authentication/src/main/java/com/x/organization/assemble/authentication/jaxrs/welink/WeLinkAction.java

@@ -0,0 +1,52 @@
+package com.x.organization.assemble.authentication.jaxrs.welink;
+
+import com.x.base.core.project.annotation.JaxrsDescribe;
+import com.x.base.core.project.annotation.JaxrsMethodDescribe;
+import com.x.base.core.project.annotation.JaxrsParameterDescribe;
+import com.x.base.core.project.http.ActionResult;
+import com.x.base.core.project.http.EffectivePerson;
+import com.x.base.core.project.http.HttpMediaType;
+import com.x.base.core.project.jaxrs.ResponseFactory;
+import com.x.base.core.project.jaxrs.StandardJaxrsAction;
+import com.x.base.core.project.logger.Logger;
+import com.x.base.core.project.logger.LoggerFactory;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.*;
+import javax.ws.rs.container.AsyncResponse;
+import javax.ws.rs.container.Suspended;
+import javax.ws.rs.core.Context;
+import javax.ws.rs.core.MediaType;
+
+/**
+ * Created by fancyLou on 2020-07-27.
+ * Copyright © 2020 O2. All rights reserved.
+ */
+
+@Path("welink")
+@JaxrsDescribe("WeLink单点登录")
+public class WeLinkAction extends StandardJaxrsAction {
+
+
+    private static Logger logger = LoggerFactory.getLogger(WeLinkAction.class);
+
+    @JaxrsMethodDescribe(value = "WeLink单点登录.", action = ActionLogin.class)
+    @GET
+    @Path("code/{code}")
+    @Produces(HttpMediaType.APPLICATION_JSON_UTF_8)
+    @Consumes(MediaType.APPLICATION_JSON)
+    public void getLogin(@Suspended final AsyncResponse asyncResponse, @Context HttpServletRequest request,
+                         @Context HttpServletResponse response, @JaxrsParameterDescribe("登录code") @PathParam("code") String code) {
+        ActionResult<ActionLogin.Wo> result = new ActionResult<>();
+        EffectivePerson effectivePerson = this.effectivePerson(request);
+        try {
+            result = new ActionLogin().execute(request, response, effectivePerson, code);
+        } catch (Exception e) {
+            logger.error(e, effectivePerson, request, null);
+            result.error(e);
+        }
+        asyncResponse.resume(ResponseFactory.getEntityTagActionResultResponse(request, result));
+    }
+
+}

+ 3 - 2
o2server/x_program_center/src/main/java/com/x/program/center/welink/WeLinkFactory.java

@@ -2,6 +2,7 @@ package com.x.program.center.welink;
 
 import com.x.base.core.project.bean.NameValuePair;
 import com.x.base.core.project.config.Config;
+import com.x.base.core.project.config.WeLink;
 import com.x.base.core.project.connection.HttpConnection;
 import com.x.base.core.project.gson.GsonPropertyObject;
 import com.x.base.core.project.logger.Logger;
@@ -96,7 +97,7 @@ public class WeLinkFactory {
         //deptCode
         //recursiveflag 0 :查询下级部门信息 1 :查询递归获取所有子部门
         List<NameValuePair> heads = new ArrayList<>();
-        heads.add(new NameValuePair("x-wlk-Authorization", this.accessToken));
+        heads.add(new NameValuePair(WeLink.WeLink_Auth_Head_Key, this.accessToken));
         OrgListResp resp = HttpConnection.getAsObject(address, heads, OrgListResp.class);
         logger.info("orgs response:{}.", resp);
         if (!resp.getCode().equals("0") && !resp.getCode().equals("47009") && !resp.getCode().equals("47012")) {
@@ -133,7 +134,7 @@ public class WeLinkFactory {
     private UserListResp users(String deptCode, int pageNo) throws Exception {
         String address = Config.weLink().getOapiAddress() + "/contact/v1/user/users?deptCode="+deptCode+"&pageNo="+pageNo+"&pageSize=50";
         List<NameValuePair> heads = new ArrayList<>();
-        heads.add(new NameValuePair("x-wlk-Authorization", this.accessToken));
+        heads.add(new NameValuePair(WeLink.WeLink_Auth_Head_Key, this.accessToken));
         UserListResp resp = HttpConnection.getAsObject(address, heads, UserListResp.class);
         logger.info("users response:{}.", resp);
         if (!resp.getCode().equals("0") && !resp.getCode().equals("47009") && !resp.getCode().equals("47012")) {

+ 170 - 0
o2web/source/x_desktop/js/welinksso.js

@@ -0,0 +1,170 @@
+layout = window.layout || {};
+var locate = window.location;
+layout.protocol = locate.protocol;
+var href = locate.href;
+if (href.indexOf("debugger") !== -1) layout.debugger = true;
+layout.desktop = layout;
+layout.session = layout.session || {};
+
+o2.addReady(function () {
+  o2.load(["../o2_lib/mootools/plugin/mBox.Notice.js", "../o2_lib/mootools/plugin/mBox.Tooltip.js"], { "sequence": true }, function () {
+    MWF.loadLP("zh-cn");
+    MWF.require("MWF.xDesktop.Layout", function () {
+      MWF.require("MWF.xDesktop.Authentication", null, false);
+      MWF.require("MWF.xDesktop.Common", null, false);
+
+      (function () {
+        layout.load = function () {
+          var uri = href.toURI();
+          var redirect = uri.getData("redirect");
+          MWF.require("MWF.xDesktop.Actions.RestActions", function () {
+            var action = new MWF.xDesktop.Actions.RestActions("", "x_organization_assemble_authentication", "");
+            action.getActions = function (actionCallback) {
+              this.actions = {
+                "auth": { "uri": "/jaxrs/welink/code/{code}" }
+              };
+              if (actionCallback) actionCallback();
+            };
+
+            HWH5.getAuthCode().then(function (data) {
+              console.log(data.code);
+              action.invoke({
+                "name": "auth",
+                "async": true,
+                "parameter": { "code": data.code },
+                "success": function (json) {
+                  layout.session.user = json.data;
+                  if (redirect) {
+                    history.replaceState(null, "page", redirect);
+                    redirect.toURI().go();
+                  } else {
+                    history.replaceState(null, "page", "../x_desktop/appMobile.html?app=process.TaskCenter");
+                    "appMobile.html?app=process.TaskCenter".toURI().go();
+                  }
+                }.bind(this),
+                "failure": function (xhr, text, error) {
+                  history.replaceState(null, "page", "../x_desktop/appMobile.html?app=process.TaskCenter");
+                  "appMobile.html?app=process.TaskCenter".toURI().go();
+                }.bind(this)
+              });
+            }).catch(function (error) {
+              console.log('获取异常', error);
+            });
+
+           
+
+
+            // action.invoke({
+            //     "name": "info", "async": true, "data": { "url": href }, "success": function (json) {
+            //         var _config = json.data;
+            //         //document.all.testaaa.set("value", "0");
+            //         dd.config({
+            //             agentId: _config.agentid,
+            //             corpId: _config.corpId,
+            //             timeStamp: _config.timeStamp,
+            //             nonceStr: _config.nonceStr,
+            //             signature: _config.signature,
+            //             jsApiList: ['runtime.info']
+            //         });
+
+            //         //document.all.testaaa.set("value", "1");
+            //         // dd.biz.navigation.setTitle({
+            //         //     title: ''
+            //         // });
+            //         // dd.runtime.info({
+            //         //     onSuccess : function(info) {
+            //         //         logger.e('runtime info: ' + JSON.stringify(info));
+            //         //     },
+            //         //     onFail : function(err) {
+            //         //         logger.e('fail: ' + JSON.stringify(err));
+            //         //     }
+            //         // });
+            //         //document.all.testaaa.set("value", "before");
+            //         dd.runtime.permission.requestAuthCode({
+
+            //             corpId: _config.corpId,
+            //             onSuccess: function (info) {
+            //                 action.invoke({
+            //                     "name": "auth", "async": true, "parameter": { "code": info.code },
+            //                     "success": function (json) {
+            //                         //document.all.testaaa.set("value", "auth");
+            //                         // "appMobile.html?app=process.TaskCenter".toURI().go();
+
+            //                         if (redirect) {
+            //                             history.replaceState(null, "page", redirect);
+            //                             redirect.toURI().go();
+            //                         } else {
+            //                             history.replaceState(null, "page", "../x_desktop/appMobile.html?app=process.TaskCenter");
+            //                             "appMobile.html?app=process.TaskCenter".toURI().go();
+            //                         }
+
+            //                     }.bind(this), "failure": function (xhr, text, error) {
+            //                         history.replaceState(null, "page", "../x_desktop/appMobile.html?app=process.TaskCenter");
+            //                         "appMobile.html?app=process.TaskCenter".toURI().go();
+            //                     }.bind(this)
+            //                 });
+            //             }.bind(this),
+            //             onFail: function (err) { }
+            //         });
+
+
+            //     }.bind(this), "failure": function (xhr, text, error) { }.bind(this)
+            // });
+
+          });
+        };
+
+        layout.isAuthentication = function () {
+          layout.authentication = new MWF.xDesktop.Authentication({
+            "onLogin": layout.load.bind(layout)
+          });
+
+          var returnValue = true;
+          this.authentication.isAuthenticated(function (json) {
+            this.user = json.data;
+            layout.session.user = json.data;
+          }.bind(this), function () {
+            this.authentication.loadLogin(this.node);
+            returnValue = false;
+          }.bind(this));
+          return returnValue;
+        };
+
+        layout.notice = function (content, type, target, where, offset) {
+          if (!where) where = { "x": "right", "y": "top" };
+          if (!target) target = this.content;
+          if (!type) type = "ok";
+          var noticeTarget = target || $(document.body);
+          var off = offset;
+          if (!off) {
+            off = {
+              x: 10,
+              y: where.y.toString().toLowerCase() == "bottom" ? 10 : 10
+            };
+          }
+
+          new mBox.Notice({
+            type: type,
+            position: where,
+            move: false,
+            target: noticeTarget,
+            delayClose: (type == "error") ? 10000 : 5000,
+            offset: off,
+            content: content
+          });
+        };
+
+        MWF.getJSON("res/config/config.json", function (config) {
+          layout.config = config;
+          MWF.xDesktop.getServiceAddress(layout.config, function (service, center) {
+            layout.serviceAddressList = service;
+            layout.centerServer = center;
+            layout.load();
+          }.bind(this));
+        });
+
+      })();
+
+    });
+  });
+});

+ 23 - 0
o2web/source/x_desktop/welinksso.html

@@ -0,0 +1,23 @@
+<!DOCTYPE html>
+<html lang="zh-CN">
+<head>
+    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
+    <link rel="stylesheet" type="text/css" href="css/style.css" charset="UTF-8" />
+    <link rel="stylesheet" href="css/mBoxNotice.css" charset="UTF-8" />
+    <link rel="stylesheet" href="css/mBoxTooltip.css" charset="UTF-8" />
+    <script src="../o2_core/o2.min.js"></script>
+    <script src="https://open-doc.welink.huaweicloud.com/docs/jsapi/2.0.4/hwh5-cloudonline.js"></script>
+    <script src="js/welinksso.js"></script>
+    <script src="../o2_lib/Decimal.js"></script>
+
+    <title></title>
+    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
+    <meta content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=0" name="viewport" />
+    <meta content="yes" name="apple-mobile-web-app-capable" />
+    <meta content="black" name="apple-mobile-web-app-status-bar-style" />
+    <meta content="telephone=no" name="format-detection" />
+</head>
+<body>
+<div id="layout" style="overflow: auto; height:100%"></div>
+</body>
+</html>