Browse Source

添加新的登录流程.

Li 3 years ago
parent
commit
5e79334248

+ 215 - 71
TEAMModeBI/Controllers/LoginController.cs

@@ -64,76 +64,6 @@ namespace TEAMModeBI.Controllers
             _http = http;
         }
 
-        /// <summary>
-        /// 钉钉扫描登录
-        /// </summary>
-        /// <param name="loginTmpCode"></param>
-        /// <returns>Json结果</returns>
-        [ProducesDefaultResponseType]
-        [HttpGet("dingding")]
-        public IActionResult DingDingLogin(string loginTmpCode)
-        {
-            string appKey = _configuration["DingDingAuth:appKey"];
-            string appSecret = _configuration["DingDingAuth:appSecret"];
-            string getuserinfo_bycode = _configuration["DingDingAuth:getuserinfo_bycode"];
-            //判断参数是否为空
-            if (string.IsNullOrEmpty(loginTmpCode))
-            {
-                return BadRequest("temp code error");
-            }
-            //获取access_token
-            DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
-            OapiGettokenRequest request = new OapiGettokenRequest();
-            request.Appkey = appKey;
-            request.Appsecret = appSecret;
-            request.SetHttpMethod("Get");
-            OapiGettokenResponse response = client.Execute(request);
-            if (response.IsError)
-            {
-                return BadRequest();
-            }
-            string access_token = response.AccessToken;
-            //获取临时授权码 获取授权用户的个人信息
-            DefaultDingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
-            OapiSnsGetuserinfoBycodeRequest bycodeRequest = new OapiSnsGetuserinfoBycodeRequest()
-            {
-                //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
-                TmpAuthCode = loginTmpCode
-            };
-            OapiSnsGetuserinfoBycodeResponse bycodeResponse = client1.Execute(bycodeRequest, appKey, appSecret);
-            if (bycodeResponse.IsError)
-            {
-                return BadRequest();
-            }
-            //根据unionid获取userid
-            string unionid = bycodeResponse.UserInfo.Unionid;
-            DefaultDingTalkClient clientDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid");
-            OapiUserGetbyunionidRequest byunionidRequest = new OapiUserGetbyunionidRequest()
-            {
-                Unionid = unionid
-            };
-            OapiUserGetbyunionidResponse byunionidResponse = clientDingTalkClient.Execute(byunionidRequest, access_token);
-            if (byunionidResponse.IsError)
-            {
-                return BadRequest();
-            }
-            string userid = byunionidResponse.Result.Userid;
-            //根据userId获取用户信息
-            DefaultDingTalkClient clientDingTalkClient2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
-            OapiV2UserGetRequest getRequest = new OapiV2UserGetRequest()
-            {
-                Userid = userid,
-                Language = "zh_CN"
-            };
-            getRequest.SetHttpMethod("Get");
-            OapiV2UserGetResponse getResponse = clientDingTalkClient2.Execute(getRequest, access_token);
-            if (getResponse.IsError)
-            {
-                return BadRequest();
-            }
-            return Ok(getResponse.Body);
-        }
-
         /// <summary>
         /// 钉钉扫码登录
         /// 先获取是否在钉钉架构中
@@ -862,11 +792,225 @@ namespace TEAMModeBI.Controllers
             }
             catch (Exception ex)
             {
-                await _dingDing.SendBotMsg($"BI,{_option.Location},common/login/get-teacherinfo \n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
+                await _dingDing.SendBotMsg($"BI,{_option.Location}, /common/login/get-teacherinfo \n{ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
                 return BadRequest();
             }
         }
 
+        /// <summary>
+        /// 钉钉扫码登录获取扫码信息
+        /// </summary>
+        /// <param name="jsonElement"></param>
+        /// <returns></returns>
+        [ProducesDefaultResponseType]
+        [HttpPost("get-ddscancode")]
+        public async Task<IActionResult> GetDingDingScanCode(JsonElement jsonElement)
+        {
+            try
+            {
+                string appKey = _configuration["DingDingAuth:appKey"];
+                string appSecret = _configuration["DingDingAuth:appSecret"];
+                if (string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appSecret))
+                {
+                    return Ok(new { status = 0, message = "请检查配置钉钉的信息" });
+                }
+                //自己传的code
+                if (!jsonElement.TryGetProperty("code", out JsonElement LoginTempCode)) return BadRequest();
+
+                //获取access_token
+                IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
+                OapiGettokenRequest tokenRequest = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
+                tokenRequest.SetHttpMethod("Get");
+                OapiGettokenResponse tokenRespone = tokenClient.Execute(tokenRequest);
+                if (tokenRespone.IsError)
+                {
+                    return BadRequest();
+                }
+
+                string access_token = tokenRespone.AccessToken;
+                //获取临时授权码 获取授权用户的个人信息
+                DefaultDingTalkClient clientinfo = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
+                OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest() { TmpAuthCode = $"{LoginTempCode}" };  //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
+                OapiSnsGetuserinfoBycodeResponse response = clientinfo.Execute(req, appKey, appSecret);
+                if (response.IsError)
+                {
+                    return Ok(new { state = 0, message = "获取个人信息失败!" });
+                }
+
+                string unionid = response.UserInfo.Unionid;
+                IDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); //userid地址
+                OapiUserGetbyunionidRequest byunionidRequest = new OapiUserGetbyunionidRequest() { Unionid = unionid };
+                OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, access_token);
+                if (byunionidResponse.IsError)
+                {
+                    return Ok(new { state = 0, message = "扫码登录失败" });
+                }
+
+                // 根据userId获取用户信息
+                string userid = byunionidResponse.Result.Userid;
+                IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
+                OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
+                {
+                    Userid = userid,
+                    Language = "zh_CN"
+                };
+
+                v2GetRequest.SetHttpMethod("POST");
+                OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
+                if (v2GetResponse.IsError)
+                {
+                    return Ok(new { state = 0, message = "扫码登录失败" });
+                }
+
+                List<DingDingUserInfo> ddusers = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object>() { { "RowKey", $"{v2GetResponse.Result.Userid}" }, { "unionId", $"{v2GetResponse.Result.Unionid}" } });
+
+                if (ddusers.Count > 0)
+                {
+                    DingDingUserInfo ddUserInfo = new DingDingUserInfo();
+                    foreach (var item in ddusers)
+                    {
+                        ddUserInfo = item;
+                    }
+
+                    return Ok(new { state = 200, ddUserId = ddUserInfo });
+                }
+                else
+                {
+                    string divide = appKey.Equals("dingrucgsnt8p13rfbgd") ? "continent" : "international";
+                    DingDingUserInfo dingDingUserInfo = new DingDingUserInfo()
+                    {
+                        PartitionKey = divide,
+                        RowKey = v2GetResponse.Result.Userid,
+                        unionId = v2GetResponse.Result.Unionid,
+                        name = v2GetResponse.Result.Name,
+                        title = v2GetResponse.Result.Title,
+                        mobile = v2GetResponse.Result.Mobile,
+                        jobNumber = v2GetResponse.Result.JobNumber,
+                        pid = 0,
+                        deptId = 0,
+                        deptName = null,
+                        depts = string.Join(",", v2GetResponse.Result.DeptIdList.ToArray()),
+                        avatar = v2GetResponse.Result.Avatar,
+                        isAdmin = v2GetResponse.Result.Admin,
+                        tmdId = "",
+                        tmdName = "",
+                        tmdMobile = "",
+                        mail = "",
+                        picture = "",
+                        roles = "",
+                        permissions = "",
+                    };
+                    await _azureStorage.Save<DingDingUserInfo>(dingDingUserInfo);
+
+                    return Ok(new { state = 400, ddUserId = dingDingUserInfo });
+                }
+            }
+            catch (Exception ex)
+            {
+                await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/ddScan   \n {ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
+                return BadRequest();
+            }
+        }
+
+        /// <summary>
+        /// 钉钉绑定醍摩豆
+        /// </summary>
+        /// <returns></returns>
+        [HttpPost("binguser")]
+        public async Task<IActionResult> BindUser(JsonElement jsonElement) 
+        {
+            try
+            {
+                if (!jsonElement.TryGetProperty("mobile", out JsonElement moile)) return BadRequest();
+                if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
+                if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
+
+                //操作记录
+                OperateLog operateLog = new OperateLog();
+                string blobOrTable = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
+                operateLog.PartitionKey = "OperateLog-BI";
+                operateLog.RowKey = blobOrTable;
+                operateLog.recordID = blobOrTable;
+                operateLog.platformSource = "BI";
+                operateLog.visitApi = "/tabledd/set-ddinductionuser";
+                operateLog.operateTime = DateTime.Now;
+
+                HttpClient httpClient = _http.CreateClient();
+                string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
+                HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, moile);
+
+                if (responseMessage.StatusCode == HttpStatusCode.OK)
+                {
+                    var temp = await responseMessage.Content.ReadAsStringAsync();
+                    if (temp.Length > 0)
+                    {
+                        List<DingDingUserInfo> ddUserInfos = new();
+                        List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
+                        var tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
+                        foreach (var item in itemjson)
+                        {
+                            foreach (var itemUser in tempUser)
+                            {
+                                var tmdId = item.GetProperty("id").ToString();
+                                var tmdName = item.GetProperty("name").ToString();
+                                itemUser.tmdId = tmdId;
+                                itemUser.tmdName = tmdName;
+                                itemUser.tmdMobile = item.GetProperty("mobile").ToString();
+                                itemUser.picture = item.GetProperty("picture").ToString();
+                                itemUser.mail = item.GetProperty("mail").ToString();
+
+                                operateLog.tmdId = item.GetProperty("id").ToString();
+                                operateLog.tmdName = item.GetProperty("name").ToString();
+                                operateLog.operateDescribe = $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功";
+
+                                ddUserInfos.Add(itemUser);
+                            }
+                        }
+
+                        var dingDingUserInfos = await _azureStorage.UpdateAll<DingDingUserInfo>(ddUserInfos);
+                        await _azureStorage.Save<OperateLog>(operateLog); //保存操作记录
+
+                        return Ok(new { state = 200, ddUsers = dingDingUserInfos });
+                    }
+                    else return Ok(new { state = 400, message = "该手机没有注册提莫信息" });
+                }
+                else return Ok(new { state = responseMessage.StatusCode });
+
+            }
+            catch (Exception ex)
+            {
+                await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/binguser   \n {ex.Message}{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
+                return BadRequest();
+            }
+        }
+
+        /// <summary>
+        /// 获取钉钉信息详情
+        /// </summary>
+        /// <param name="jsonElement"></param>
+        /// <returns></returns>
+        [HttpPost("get-ddinfo")]
+        public async Task<IActionResult> GetDingDingInfo(JsonElement jsonElement)
+        {
+            if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
+            if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
+            var tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
+
+            List<string> roles = new();//角色列表
+            List<DingDingUserInfo> ddUserInfos = new();
+            foreach (var itemUser in tempUser)
+            {
+                //roles = new List<string>(itemUser.roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
+
+                roles = !itemUser.roles.Equals("") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
+                ddUserInfos.Add(itemUser);
+            }
+            
+            var (osblob_uri, osblob_sas) = roles.Contains("assist") ? _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete) : _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List);
+
+            return Ok(new { state = 200, ddUserInfos, osblob_uri, osblob_sas });
+        }
+
         public record DingDingbinds
         {
             public string type { get; set; }

+ 11 - 1
TEAMModelOS.SDK/Models/Cosmos/BI/DingDingUserInfo.cs

@@ -57,7 +57,7 @@ namespace TEAMModelOS.SDK.Models.Cosmos.BI
         /// <summary>
         /// 所在企业部门
         /// </summary>
-        public List<long> depts { get; set; }
+        public string depts { get; set; }
 
         /// <summary>
         /// 钉钉头像
@@ -93,5 +93,15 @@ namespace TEAMModelOS.SDK.Models.Cosmos.BI
         /// 醍摩豆头像
         /// </summary>
         public string picture { get; set; }
+
+        /// <summary>
+        /// BI角色
+        /// </summary>
+        public string roles { get; set; }
+        
+        /// <summary>
+        /// BI权限
+        /// </summary>
+        public string permissions { get; set; }
     }
 }