LoginController.cs 53 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903
  1. using Azure.Cosmos;
  2. using DingTalk.Api;
  3. using DingTalk.Api.Request;
  4. using DingTalk.Api.Response;
  5. using Microsoft.AspNetCore.Http;
  6. using Microsoft.AspNetCore.Mvc;
  7. using Microsoft.Extensions.Configuration;
  8. using System;
  9. using System.Collections.Generic;
  10. using System.Linq;
  11. using System.Text.Json;
  12. using System.Threading.Tasks;
  13. using TEAMModelOS.SDK.DI;
  14. using TEAMModelOS.SDK.Models;
  15. using HTEXLib.COMM.Helpers;
  16. using TEAMModelOS.Models;
  17. using Microsoft.Extensions.Options;
  18. using TEAMModelOS.SDK.Extension;
  19. using TEAMModelOS.SDK.Models.Service;
  20. using Microsoft.AspNetCore.Authorization;
  21. using Azure.Storage.Blobs.Models;
  22. using System.IdentityModel.Tokens.Jwt;
  23. using System.Net.Http;
  24. using System.Text;
  25. using System.Net;
  26. using Newtonsoft.Json;
  27. using System.Collections;
  28. using Newtonsoft.Json.Linq;
  29. using TEAMModelOS.SDK.Models.Cosmos.BI;
  30. using Azure.Storage.Sas;
  31. using System.Net.Http.Json;
  32. using TEAMModelBI.Filter;
  33. using TEAMModelBI.Models.Extension;
  34. using TEAMModelOS.SDK;
  35. using Microsoft.AspNetCore.Hosting;
  36. using TEAMModelBI.Tool;
  37. using TEAMModelBI.DI.BIAzureStorage;
  38. using TEAMModelOS.SDK.Models.Table;
  39. using TEAMModelOS.SDK.Context.Constant;
  40. using TEAMModelBI.Models;
  41. using TEAMModelOS.SDK.Context.BI;
  42. using TEAMModelOS.SDK.Models.Cosmos.BI.BINormal;
  43. //using static DingTalk.Api.Response.OapiV2UserGetResponse;
  44. namespace TEAMModelBI.Controllers
  45. {
  46. [ProducesResponseType(StatusCodes.Status200OK)]
  47. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  48. [Route("common/login")]
  49. [ApiController]
  50. public class LoginController : ControllerBase
  51. {
  52. private readonly IConfiguration _configuration;
  53. //数据容器
  54. private readonly AzureCosmosFactory _azureCosmos;
  55. //文件容器
  56. private readonly AzureStorageFactory _azureStorage;
  57. //钉钉提示信息
  58. private readonly DingDing _dingDing;
  59. private readonly Option _option;
  60. //隐式登录
  61. private readonly CoreAPIHttpService _coreAPIHttpService;
  62. private readonly IHttpClientFactory _http;
  63. private readonly IWebHostEnvironment _environment; //读取文件
  64. public LoginController(IConfiguration configuration, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, CoreAPIHttpService coreAPIHttpService, IHttpClientFactory http, IWebHostEnvironment environment)
  65. {
  66. _configuration = configuration;
  67. _azureCosmos = azureCosmos;
  68. _azureStorage = azureStorage;
  69. _dingDing = dingDing;
  70. _option = option?.Value;
  71. _coreAPIHttpService = coreAPIHttpService;
  72. _http = http;
  73. _environment = environment;
  74. }
  75. /// <summary>
  76. /// 钉钉扫码登录获取扫码信息
  77. /// </summary>
  78. /// <param name="jsonElement"></param>
  79. /// <returns></returns>
  80. [ProducesDefaultResponseType]
  81. [HttpPost("get-ddscancode")]
  82. public async Task<IActionResult> GetDingDingScanCode(JsonElement jsonElement)
  83. {
  84. try
  85. {
  86. string appKey = _configuration["DingDingAuth:appKey"];
  87. string appSecret = _configuration["DingDingAuth:appSecret"];
  88. string proDeptId = _configuration["CustomParam:proDeptId"];
  89. //string divide = _configuration["CustomParam:SiteScope"];
  90. string divide = _option.Location;
  91. var cosmosClient = _azureCosmos.GetCosmosClient();
  92. string Website = "China";
  93. if (string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appSecret))
  94. {
  95. return Ok(new { state = 0, msg = "请检查配置钉钉的信息" });
  96. }
  97. //自己传的code
  98. if (!jsonElement.TryGetProperty("code", out JsonElement LoginTempCode)) return BadRequest();
  99. jsonElement.TryGetProperty("site", out JsonElement site);
  100. var tableClient = _azureStorage.GetCloudTableClient();
  101. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  102. if ($"{site}".Equals(BIConst.Global))
  103. {
  104. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  105. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  106. Website = BIConst.Global;
  107. }
  108. //获取access_token
  109. IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  110. OapiGettokenRequest tokenRequest = new() { Appkey = appKey, Appsecret = appSecret };
  111. tokenRequest.SetHttpMethod("Get");
  112. OapiGettokenResponse tokenRespone = tokenClient.Execute(tokenRequest);
  113. if (tokenRespone.IsError) return BadRequest();
  114. string access_token = tokenRespone.AccessToken;
  115. //获取临时授权码 获取授权用户的个人信息
  116. DefaultDingTalkClient clientinfo = new("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
  117. OapiSnsGetuserinfoBycodeRequest req = new() { TmpAuthCode = $"{LoginTempCode}" }; //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
  118. OapiSnsGetuserinfoBycodeResponse response = clientinfo.Execute(req, appKey, appSecret);
  119. if (response.Errcode.Equals(40078))
  120. {
  121. return Ok(new { state = 0, msg = $"state:{response.Errcode};Err{response.Errmsg}/临时授权码过期请重新扫码" });
  122. }
  123. string unionid = response.UserInfo.Unionid;
  124. IDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); //userid地址
  125. OapiUserGetbyunionidRequest byunionidRequest = new() { Unionid = unionid };
  126. OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, access_token);
  127. if (byunionidResponse.IsError || byunionidResponse.Errcode == 60121)
  128. {
  129. return Ok(new { state = 0, msg = byunionidResponse.Errmsg });
  130. }
  131. // 根据userId获取用户信息
  132. string userid = byunionidResponse.Result.Userid;
  133. IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  134. OapiV2UserGetRequest v2GetRequest = new()
  135. {
  136. Userid = userid,
  137. Language = "zh_CN"
  138. };
  139. v2GetRequest.SetHttpMethod("POST");
  140. OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
  141. if (v2GetResponse.IsError)
  142. {
  143. return Ok(new { state = 0, msg = "扫码登录失败" });
  144. }
  145. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  146. var id_token = "";
  147. string osblob_uri = null, osblob_sas = null;
  148. List<string> roles = new();//角色列表
  149. List<string> permissions = new();//权限列表
  150. bool isExploit = false;
  151. List<DingDingUserInfo> ddusers = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object>() { { "PartitionKey", $"{divide}"},{ "userId", $"{v2GetResponse.Result.Userid}" }, { "unionId", $"{v2GetResponse.Result.Unionid}" } });
  152. if (ddusers.Count > 0)
  153. {
  154. List<DingDingUserInfo> saveInfo = new();
  155. StringBuilder strMsg = new();
  156. foreach (var item in ddusers)
  157. {
  158. if (string.IsNullOrEmpty(item.tmdId))
  159. {
  160. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{item.mobile}" } }, _option.Location, _configuration);
  161. if (coreUser != null && coreUser.id != null)
  162. {
  163. item.tmdId = coreUser.id;
  164. item.tmdName = coreUser.name;
  165. item.tmdMobile = coreUser.mobile;
  166. item.picture = coreUser.picture;
  167. item.mail = coreUser.mail;
  168. }
  169. else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  170. //List<string> mobiles = new() { $"{ item.mobile}" };
  171. //var content = new StringContent(mobiles.ToJsonString(), Encoding.UTF8, "application/json");
  172. //string json = await _coreAPIHttpService.GetUserInfos(content);
  173. //if (!string.IsNullOrEmpty(json))
  174. //{
  175. // List<JsonElement> json_id = json.ToObject<List<JsonElement>>();
  176. // foreach (var tmd in json_id)
  177. // {
  178. // item.tmdId = tmd.GetProperty("id").ToString();
  179. // item.tmdName = tmd.GetProperty("name").ToString();
  180. // item.tmdMobile = tmd.GetProperty("mobile").ToString();
  181. // item.picture = tmd.GetProperty("picture").ToString();
  182. // item.mail = tmd.GetProperty("mail").ToString();
  183. // }
  184. //}
  185. //else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  186. strMsg.Append($"{item.tmdName}【{item.tmdId}】醍摩豆账号和{item.name}【{item.userId}】钉钉账户绑定成功");
  187. //保存操作记录
  188. //await _azureStorage.SaveBILog("tabledd-update", strMsg?.ToString(), _dingDing, httpContext: HttpContext, twebsite: Website, tid: item.tmdId, tname: item.tmdName);
  189. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", strMsg?.ToString(), _dingDing, httpContext: HttpContext, twebsite: Website, tid: item.tmdId, tname: item.tmdName);
  190. saveInfo.Add(item);
  191. }
  192. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, item.tmdId);
  193. if (schoolIds.Count > 0)
  194. {
  195. item.schoolIds = string.Join("|", schoolIds);
  196. await table.SaveOrUpdate<DingDingUserInfo>(item);
  197. }
  198. roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  199. roles = roles.Where(w => !string.IsNullOrEmpty(w)).ToList();
  200. permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
  201. if (item.depts.Contains($"{proDeptId}")) isExploit = true;
  202. if (item.deptId == long.Parse($"{proDeptId}")) isExploit = true;
  203. if (item.pid == long.Parse($"{proDeptId}")) isExploit = true;
  204. //自己写的
  205. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, item.tmdId?.ToString(), item.tmdName?.ToString(), item.picture?.ToString(), _option.JwtSecretKey, scope: "assist", webSite: Website, isex: isExploit, item.userId?.ToString(), item.name?.ToString(), item.avatar?.ToString(), roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
  206. }
  207. if (saveInfo.Count > 0)
  208. {
  209. ddusers = await table.UpdateAll<DingDingUserInfo>(saveInfo);
  210. }
  211. }
  212. else
  213. {
  214. DingDingUserInfo ddUserInfo = new()
  215. {
  216. PartitionKey = divide,
  217. RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
  218. userId = v2GetResponse.Result.Userid,
  219. unionId = v2GetResponse.Result.Unionid,
  220. name = v2GetResponse.Result.Name,
  221. title = v2GetResponse.Result.Title,
  222. mobile = v2GetResponse.Result.Mobile,
  223. jobNumber = v2GetResponse.Result.JobNumber,
  224. pid = 0,
  225. deptId = 0,
  226. deptName = null,
  227. depts = string.Join(",", v2GetResponse.Result.DeptIdList.ToArray()),
  228. avatar = v2GetResponse.Result.Avatar,
  229. isAdmin = v2GetResponse.Result.Admin,
  230. roles = "assist",
  231. permissions = "abilitystandard-read,batcharea-read,batchschool-read,orgusers-read"
  232. };
  233. if (!string.IsNullOrEmpty($"{ddUserInfo.mobile}"))
  234. {
  235. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{ddUserInfo.mobile}" } }, _option.Location, _configuration);
  236. if (coreUser != null && coreUser.id != null) {
  237. ddUserInfo.tmdId = coreUser.id;
  238. ddUserInfo.tmdName = coreUser.name;
  239. ddUserInfo.tmdMobile = coreUser.mobile;
  240. ddUserInfo.picture = coreUser.mobile;
  241. ddUserInfo.mail = coreUser.mail;
  242. }
  243. else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  244. //HttpClient httpClient = _http.CreateClient();
  245. //string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  246. //List<string> mobiles = new() { $"{ ddUserInfo.mobile}" };
  247. //HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
  248. //if (responseMessage.StatusCode == HttpStatusCode.OK)
  249. //{
  250. // string temp = responseMessage.Content.ReadAsStringAsync().Result;
  251. // List<JsonElement> json_id = temp.ToObject<List<JsonElement>>();
  252. // if (json_id.Count > 0)
  253. // {
  254. // foreach (var tmd in json_id)
  255. // {
  256. // ddUserInfo.tmdId = tmd.GetProperty("id").ToString();
  257. // ddUserInfo.tmdName = tmd.GetProperty("name").ToString();
  258. // ddUserInfo.tmdMobile = tmd.GetProperty("mobile").ToString();
  259. // ddUserInfo.picture = tmd.GetProperty("picture").ToString();
  260. // ddUserInfo.mail = tmd.GetProperty("mail").ToString();
  261. // }
  262. // }
  263. // else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  264. //}
  265. }
  266. else return Ok(new { state = 404, msg = "钉钉手机号为空" });
  267. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, ddUserInfo.tmdId);
  268. if (schoolIds.Count > 0)
  269. {
  270. ddUserInfo.schoolIds = string.Join("|", schoolIds);
  271. }
  272. ddUserInfo = await table.Save<DingDingUserInfo>(ddUserInfo);
  273. //保存操作记录
  274. //await _azureStorage.SaveBILog("tabledd-update", $"{ddUserInfo.tmdName}【{ddUserInfo.tmdId}】醍摩豆账号和{ddUserInfo.name}【{ddUserInfo.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext, tid: ddUserInfo.tmdId, tname: ddUserInfo.tmdName, twebsite: Website);
  275. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{ddUserInfo.tmdName}【{ddUserInfo.tmdId}】醍摩豆账号和{ddUserInfo.name}【{ddUserInfo.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext, tid: ddUserInfo.tmdId, tname: ddUserInfo.tmdName, twebsite: Website);
  276. roles = !string.IsNullOrEmpty($"{ddUserInfo.roles}") ? new List<string>(ddUserInfo.roles.Split(",")) : new List<string>();
  277. roles = roles.Where(w => !string.IsNullOrEmpty(w)).ToList();
  278. permissions = !string.IsNullOrEmpty($"{ddUserInfo.permissions}") ? new List<string>(ddUserInfo.permissions.Split(",")) : new List<string>();
  279. if (ddUserInfo.depts.Contains($"{proDeptId}")) isExploit = true;
  280. if (ddUserInfo.deptId == long.Parse($"{proDeptId}")) isExploit = true;
  281. if (ddUserInfo.pid == long.Parse($"{proDeptId}")) isExploit = true;
  282. //自己写的
  283. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, ddUserInfo.tmdId?.ToString(), ddUserInfo.tmdName?.ToString(), ddUserInfo.picture?.ToString(), _option.JwtSecretKey, scope: "assist", webSite: Website, isex: isExploit, ddUserInfo.userId?.ToString(), ddUserInfo.name?.ToString(), ddUserInfo.avatar?.ToString(), roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
  284. }
  285. if (Website.Equals(BIConst.Global))
  286. {
  287. (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete, BIConst.Global);
  288. }
  289. else
  290. {
  291. (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
  292. }
  293. //(osblob_uri, osblob_sas) = roles.Contains("assist") ? _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete) : _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List, BIConst.Global);
  294. return Ok(new { state = 200, ddUserInfos = ddusers, id_token, roles, permissions, osblob_uri, osblob_sas });
  295. }
  296. catch (Exception ex)
  297. {
  298. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/get-ddscancode \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  299. return BadRequest();
  300. }
  301. }
  302. /// <summary>
  303. /// 钉钉绑定醍摩豆
  304. /// </summary>
  305. /// <returns></returns>
  306. [ProducesDefaultResponseType]
  307. [HttpPost("set-bind")]
  308. public async Task<IActionResult> BindUser(JsonElement jsonElement)
  309. {
  310. try
  311. {
  312. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  313. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  314. jsonElement.TryGetProperty("id_token", out JsonElement idtoken);
  315. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  316. jsonElement.TryGetProperty("site", out JsonElement site);
  317. string Website = "China";
  318. var tableClient = _azureStorage.GetCloudTableClient();
  319. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  320. if ($"{site}".Equals(BIConst.Global))
  321. {
  322. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  323. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  324. Website = BIConst.Global;
  325. }
  326. HttpClient httpClient = _http.CreateClient();
  327. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  328. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "userId", $"{userId}" } });
  329. var id_token = "";
  330. var auth_token = "";
  331. List<DingDingUserInfo> ddUserInfos = new();
  332. List<string> roles = new();//角色列表
  333. List<string> permissions = new();//权限列表
  334. foreach (var itemUser in tempUser)
  335. {
  336. if (!string.IsNullOrEmpty($"{idtoken}"))
  337. {
  338. JwtSecurityToken jwt = new JwtSecurityToken($"{idtoken}");
  339. var tmdId = jwt.Payload.Sub;
  340. jwt.Payload.TryGetValue("name", out object tmdName);
  341. jwt.Payload.TryGetValue("picture", out object picture);
  342. itemUser.tmdId = tmdId;
  343. itemUser.tmdName = $"{tmdName}";
  344. itemUser.tmdMobile = itemUser.mobile;
  345. itemUser.picture = $"{picture}";
  346. }
  347. if (!string.IsNullOrEmpty($"{mobile}"))
  348. {
  349. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{mobile}" } }, _option.Location, _configuration);
  350. if (coreUser != null && coreUser.id != null)
  351. {
  352. itemUser.tmdId = coreUser.id;
  353. itemUser.tmdName = coreUser.name;
  354. itemUser.tmdMobile = coreUser.mobile;
  355. itemUser.picture = coreUser.mobile;
  356. itemUser.mail = coreUser.mail;
  357. }
  358. else return Ok(new { state = 404, msg = "手机号未找到醍摩豆账户" });
  359. //string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  360. //List<string> mobiles = new() { $"{mobile}" };
  361. //HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
  362. //if (responseMessage.StatusCode == HttpStatusCode.OK)
  363. //{
  364. // var temp = await responseMessage.Content.ReadAsStringAsync();
  365. // if (temp.Length > 0)
  366. // {
  367. // List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
  368. // foreach (var item in itemjson)
  369. // {
  370. // itemUser.tmdId = item.GetProperty("id").ToString();
  371. // itemUser.tmdName = item.GetProperty("name").ToString();
  372. // itemUser.tmdMobile = item.GetProperty("mobile").ToString();
  373. // itemUser.picture = item.GetProperty("picture").ToString();
  374. // itemUser.mail = item.GetProperty("mail").ToString();
  375. // }
  376. // }
  377. //}
  378. //else return Ok(new { state = 404, msg = "手机号未找到醍摩豆账户" });
  379. }
  380. if (string.IsNullOrEmpty($"{mobile}") && string.IsNullOrEmpty($"{idtoken}"))
  381. return Ok(new { state = 400, msg = "mobile、idtoken参数错误" });
  382. else
  383. {
  384. ddUserInfos.Add(itemUser);
  385. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  386. roles = roles.Where(w => !string.IsNullOrEmpty(w)).ToList();
  387. //保存操作记录
  388. //await _azureStorage.SaveBILog("tabledd-update", $"{itemUser.tmdName}【{itemUser.tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.userId}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: Website, httpContext: HttpContext);
  389. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{itemUser.tmdName}【{itemUser.tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.userId}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: Website, httpContext: HttpContext);
  390. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), _option.JwtSecretKey, scope: "assist", webSite: Website, isex: false, itemUser.userId?.ToString(), itemUser.name?.ToString(), itemUser.avatar?.ToString(), roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
  391. }
  392. }
  393. ddUserInfos = await table.UpdateAll(ddUserInfos);
  394. string osblob_uri = null, osblob_sas = null;
  395. if (Website.Equals(BIConst.Global))
  396. {
  397. (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete, BIConst.Global);
  398. }
  399. else
  400. {
  401. (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
  402. }
  403. //blob 访问权限
  404. //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);
  405. return Ok(new { state = 200, ddUserInfos, id_token, roles, osblob_uri, osblob_sas });
  406. }
  407. catch (Exception ex)
  408. {
  409. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/set-bind \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  410. return BadRequest();
  411. }
  412. }
  413. /// <summary>
  414. /// 获取钉钉信息详情绑定醍摩豆和钉钉信息 二合一
  415. /// </summary>
  416. /// <param name="jsonElement"></param>
  417. /// <returns></returns>
  418. [ProducesDefaultResponseType]
  419. [HttpPost("get-ddinfo")]
  420. public async Task<IActionResult> GetDingDingInfo(JsonElement jsonElement)
  421. {
  422. try
  423. {
  424. if (!jsonElement.TryGetProperty("mobile", out JsonElement moile)) return BadRequest();
  425. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  426. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  427. jsonElement.TryGetProperty("site", out JsonElement site);
  428. string Website = "China";
  429. var tableClient = _azureStorage.GetCloudTableClient();
  430. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  431. if ($"{site}".Equals(BIConst.Global))
  432. {
  433. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  434. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  435. Website = BIConst.Global;
  436. }
  437. var table = tableClient.GetTableReference("BIDDUserInfo");
  438. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "userId", $"{userId}" } });
  439. List<string> roles = new();//角色列表
  440. List<string> permissions = new();//权限列表
  441. List<DingDingUserInfo> ddUserInfos = new();
  442. var id_token = "";
  443. foreach (var itemUser in tempUser)
  444. {
  445. if (!string.IsNullOrEmpty($"{itemUser.tmdId}") && !string.IsNullOrEmpty($"{itemUser.tmdName}"))
  446. {
  447. //roles = new List<string>(itemUser.roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
  448. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  449. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  450. ddUserInfos.Add(itemUser);
  451. }
  452. else
  453. {
  454. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{moile}" } }, _option.Location, _configuration);
  455. if (coreUser != null && coreUser.id != null)
  456. {
  457. itemUser.tmdId = coreUser.id;
  458. itemUser.tmdName = coreUser.name;
  459. itemUser.tmdMobile = coreUser.mobile;
  460. itemUser.picture = coreUser.mobile;
  461. itemUser.mail = coreUser.mail;
  462. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  463. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  464. ddUserInfos.Add(itemUser);
  465. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{coreUser.name}【{coreUser.id}】醍摩豆账号和{itemUser.name}【{itemUser.userId}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: Website, httpContext: HttpContext);
  466. }
  467. else return Ok(new { state = 400, message = "该手机没有注册醍摩豆账号信息" });
  468. //HttpClient httpClient = _http.CreateClient();
  469. //string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  470. //HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, moile);
  471. //if (responseMessage.StatusCode == HttpStatusCode.OK)
  472. //{
  473. // var temp = await responseMessage.Content.ReadAsStringAsync();
  474. // if (temp.Length > 0)
  475. // {
  476. // List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
  477. // string tmdId = null;
  478. // string tmdName = null;
  479. // foreach (var item in itemjson)
  480. // {
  481. // tmdId = item.GetProperty("id").ToString();
  482. // tmdName = item.GetProperty("name").ToString();
  483. // itemUser.tmdId = tmdId?.ToString();
  484. // itemUser.tmdName = tmdName?.ToString();
  485. // itemUser.tmdMobile = item.GetProperty("mobile").ToString();
  486. // itemUser.picture = item.GetProperty("picture").ToString();
  487. // itemUser.mail = item.GetProperty("mail").ToString();
  488. // roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  489. // permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  490. // ddUserInfos.Add(itemUser);
  491. // }
  492. // ddUserInfos = await table.UpdateAll<DingDingUserInfo>(ddUserInfos);
  493. // //保存操作记录
  494. // //await _azureStorage.SaveBILog("tabledd-update", $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.userId}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: Website, httpContext: HttpContext);
  495. // await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.userId}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: Website, httpContext: HttpContext);
  496. // }
  497. // else return Ok(new { state = 400, message = "该手机没有注册醍摩豆账号信息" });
  498. //}
  499. //else return Ok(new { state = responseMessage.StatusCode });
  500. }
  501. //自己写的
  502. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), _option.JwtSecretKey, scope: "assist", webSite: Website, isex: false, itemUser.userId?.ToString(), itemUser.name?.ToString(), itemUser.avatar?.ToString(), roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
  503. }
  504. await table.SaveOrUpdateAll<DingDingUserInfo>(ddUserInfos);
  505. string osblob_uri = null, osblob_sas = null;
  506. if (Website.Equals(BIConst.Global))
  507. {
  508. (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete, BIConst.Global);
  509. }
  510. else
  511. {
  512. (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
  513. }
  514. //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);
  515. return Ok(new { state = 200, ddUserInfos, id_token, roles, permissions, osblob_uri, osblob_sas });
  516. }
  517. catch (Exception ex)
  518. {
  519. await _dingDing.SendBotMsg($"BI,{_option.Location} /common/login/get-ddinfo \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  520. return BadRequest();
  521. }
  522. }
  523. /// <summary>
  524. /// 企业登录
  525. /// </summary>
  526. /// <param name="jsonElement"></param>
  527. /// <returns></returns>
  528. [ProducesDefaultResponseType]
  529. [HttpPost("get-bizuserlogin")]
  530. public async Task<IActionResult> GetCommpanyLogin(JsonElement jsonElement)
  531. {
  532. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  533. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  534. jsonElement.TryGetProperty("mail", out JsonElement mail);
  535. if (!jsonElement.TryGetProperty("pwd", out JsonElement password)) return BadRequest();
  536. jsonElement.TryGetProperty("site", out JsonElement site);
  537. string Website = "China";
  538. var cosmosClient = _azureCosmos.GetCosmosClient();
  539. var tableClient = _azureStorage.GetCloudTableClient();
  540. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  541. if ($"{site}".Equals(BIConst.Global))
  542. {
  543. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  544. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  545. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  546. Website = BIConst.Global;
  547. }
  548. Dictionary<string, object> tableDic = new();
  549. string tableSql = null;
  550. if (!string.IsNullOrEmpty($"{mail}"))
  551. {
  552. tableSql = $" PartitionKey eq 'BusinessUser' and mail eq '{mail}'";
  553. tableDic = new Dictionary<string, object>() { { "PartitionKey", "BizRelUser" }, { "mail", $"{mail}" } };
  554. }
  555. if (!string.IsNullOrEmpty($"{tmdId}"))
  556. {
  557. tableSql = $" PartitionKey eq 'BusinessUser' and tmdId eq '{tmdId}'";
  558. tableDic = new Dictionary<string, object>() { { "PartitionKey", "BizRelUser" }, { "tmdId", $"{tmdId}" } };
  559. }
  560. if (!string.IsNullOrEmpty($"{mobile}"))
  561. {
  562. tableSql = $" PartitionKey eq 'BusinessUser' and mobile eq '{mobile}'";
  563. tableDic = new Dictionary<string, object>() { { "PartitionKey", "BizRelUser" }, { "mobile", $"{mobile}" } };
  564. }
  565. if (!string.IsNullOrEmpty(tableSql))
  566. {
  567. var table = tableClient.GetTableReference("IESOpenApi");
  568. List<BusinessUser> findBizUsers = await table.QueryWhereString<BusinessUser>(tableSql);
  569. //List<BusinessUser> findBizUsers = await table.FindListByDict<BusinessUser>(tableDic);
  570. if (findBizUsers.Count > 0)
  571. {
  572. BusinessUser bizUser = new();
  573. foreach (var item in findBizUsers)
  574. {
  575. bizUser.PartitionKey = item.PartitionKey;
  576. bizUser.RowKey = item.RowKey;
  577. bizUser.name = item.name;
  578. bizUser.picture = item.picture;
  579. bizUser.tmdId = item.tmdId;
  580. bizUser.mobile = item.mobile;
  581. bizUser.mail = item.mail;
  582. bizUser.salt = item.salt;
  583. bizUser.pwd = item.pwd;
  584. }
  585. List<BizRelUser> bizRelUsers = new();
  586. List<RelBizInfo> relBizInfos = new();
  587. if (bizUser != null)
  588. {
  589. string tableSqlUser = $"PartitionKey eq 'BizRelUser' and userId eq '{bizUser.RowKey}'";
  590. bizRelUsers = await table.QueryWhereString<BizRelUser>(tableSqlUser);
  591. if (bizRelUsers.Count > 0)
  592. {
  593. foreach (var item in bizRelUsers)
  594. {
  595. BusinessConfig businessConfig = table.Get<BusinessConfig>("BusinessConfig", item.bizId);
  596. RelBizInfo relBizInfo = new()
  597. {
  598. userRowKey = item.userId,
  599. relId = item.RowKey,
  600. bizRowKey = item.bizId,
  601. roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(',')) : new List<string>()
  602. };
  603. if (businessConfig != null)
  604. {
  605. relBizInfo.bizName = businessConfig.name;
  606. relBizInfo.bizCredit = businessConfig.credit;
  607. relBizInfo.bizPicture = businessConfig.picture;
  608. relBizInfos.Add(relBizInfo);
  609. }
  610. }
  611. }
  612. }
  613. var hashedPw = Utils.HashedPassword(password.ToString(), bizUser.salt.ToString());
  614. if (hashedPw.Equals(bizUser.pwd))
  615. {
  616. //string id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, bizUser.RowKey?.ToString(), bizUser.name?.ToString(), bizUser.picture?.ToString(), _option.JwtSecretKey, scope: "company", webSite: Website, expire: 3);
  617. string openid_token = JwtAuthExtension.CreateBizLoginAuthToken(_option.HostName, bizUser.RowKey?.ToString(), bizUser.name?.ToString(), bizUser.picture?.ToString(),$"{Website}-Open",_option.JwtSecretKey, expire: 3);
  618. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{bizUser.name}【{bizUser.RowKey}】登录商务智能开放平台", _dingDing, tid: bizUser.RowKey, tname: bizUser.name, twebsite: Website?.ToString(), httpContext: HttpContext);
  619. return Ok(new { state = RespondCode.Ok, openid_token, bizUser, relBizInfos });
  620. }
  621. else return Ok(new { state = RespondCode.ForbiddenPwd, msg = "密码错误!" });
  622. }
  623. else return Ok(new { state = RespondCode.NotFound, msg = "该账户不存在" });
  624. }
  625. else return Ok(new { state = RespondCode.ParamsError, msg = "参数错误" });
  626. }
  627. /// <summary>
  628. /// 用户信息注册
  629. /// </summary>
  630. /// <param name="jsonElement"></param>
  631. /// <returns></returns>
  632. [HttpPost("set-ropen")]
  633. public async Task<IActionResult> SetRegistered(JsonElement jsonElement)
  634. {
  635. if (!jsonElement.TryGetProperty("name", out JsonElement name)) return BadRequest();
  636. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  637. jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
  638. jsonElement.TryGetProperty("mail", out JsonElement mail);
  639. jsonElement.TryGetProperty("pwd", out JsonElement pwd);
  640. jsonElement.TryGetProperty("site", out JsonElement site);
  641. string Website = "China";
  642. var cosmosClient = _azureCosmos.GetCosmosClient();
  643. var tableClient = _azureStorage.GetCloudTableClient();
  644. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  645. if ($"{site}".Equals(BIConst.Global))
  646. {
  647. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  648. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  649. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  650. Website = BIConst.Global;
  651. }
  652. var table = tableClient.GetTableReference("IESOpenApi");
  653. string salt = Utils.CreatSaltString(8);
  654. BusinessUser bizUser = null;
  655. List<BusinessUser> findBizUsers = await table.QueryWhereString<BusinessUser>($" PartitionKey eq 'BusinessUser' and mobile eq '{mobile}'");
  656. if (findBizUsers.Count <= 0)
  657. {
  658. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{mobile}" } }, _option.Location, _configuration);
  659. if (coreUser != null)
  660. bizUser = new() { RowKey = Guid.NewGuid().ToString(), name = coreUser.name, tmdId = coreUser.id, mobile = coreUser.mobile, mail = coreUser.mail, salt = salt, pwd = string.IsNullOrEmpty($"{pwd}") ? Utils.HashedPassword($"{mobile}", salt) : Utils.HashedPassword($"{pwd}", salt) };
  661. else
  662. bizUser = new() { RowKey = Guid.NewGuid().ToString(), name = $"{name}", mobile = $"{mobile}", salt = salt, pwd = string.IsNullOrEmpty($"{pwd}") ? Utils.HashedPassword($"{mobile}", salt) : Utils.HashedPassword($"{pwd}", salt) };
  663. bizUser = await table.Save<BusinessUser>(bizUser);
  664. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "bizUser-update", $"{bizUser.name}【{bizUser.RowKey}】注册开放平台用户", _dingDing, tid: bizUser.RowKey, tname: bizUser.name, twebsite: Website?.ToString(), httpContext: HttpContext);
  665. return Ok(new { state = RespondCode.Ok, bizUser });
  666. }
  667. else return Ok(new { state = RespondCode.Conflict, msg = "该手机号已注册开放平台,请直接登录" });
  668. }
  669. /// <summary>
  670. /// 登录 第三方用户数据在CosmosDB
  671. /// </summary>
  672. /// <param name="jsonElement"></param>
  673. /// <returns></returns>
  674. [ProducesDefaultResponseType]
  675. [HttpPost("get-bizuser")]
  676. public async Task<IActionResult> GetBizUserLogin(JsonElement jsonElement)
  677. {
  678. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  679. jsonElement.TryGetProperty("mail", out JsonElement mail);
  680. if (!jsonElement.TryGetProperty("pwd", out JsonElement password)) return BadRequest();
  681. jsonElement.TryGetProperty("site", out JsonElement site);
  682. var cosmosClient = _azureCosmos.GetCosmosClient();
  683. var tableClient = _azureStorage.GetCloudTableClient();
  684. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  685. if ($"{site}".Equals(BIConst.Global))
  686. {
  687. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  688. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  689. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  690. }
  691. string loginSql = null;
  692. if (!string.IsNullOrEmpty($"{mobile}"))
  693. loginSql = $"select value(c) from c where c.mobile ={mobile}";
  694. else if (!string.IsNullOrEmpty($"{mail}"))
  695. loginSql = $"select value(c) from c where c.mail ={mail}";
  696. else return Ok(new { state = RespondCode.ParamsError, msg = "手机号/和邮箱为空" });
  697. List<BusinessUsers> bizUsers = new();
  698. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BusinessUsers>(queryText:loginSql,requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
  699. {
  700. bizUsers.Add(item);
  701. }
  702. BusinessUsers businessUsers = new(); string openid_token = null;
  703. if (bizUsers.Count > 0)
  704. {
  705. foreach (var item in bizUsers)
  706. {
  707. var hashedPw = Utils.HashedPassword(password.ToString(), item.salt.ToString());
  708. if (hashedPw.Equals(item.pwd))
  709. {
  710. businessUsers = item;
  711. //string id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, bizUser.RowKey?.ToString(), bizUser.name?.ToString(), bizUser.picture?.ToString(), _option.JwtSecretKey, scope: "company", webSite: Website, expire: 3);
  712. openid_token = JwtAuthExtension.CreateBizLoginAuthToken(_option.HostName, businessUsers.id?.ToString(), businessUsers.name?.ToString(), businessUsers.picture?.ToString(), $"{_option.Location}-Open", _option.JwtSecretKey, expire: 3);
  713. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{businessUsers.name}【{businessUsers.id}】登录开放平台", _dingDing, tid: businessUsers.id, tname: businessUsers.name, twebsite: "Open", httpContext: HttpContext);
  714. }
  715. }
  716. }
  717. else return Ok(new { state = RespondCode.NotFound, msg = "未找到该用户!" });
  718. if (businessUsers.id != null)
  719. return Ok(new { state = RespondCode.Ok, openid_token, businessUsers });
  720. else
  721. return Ok(new { state = RespondCode.ForbiddenPwd, msg = "密码错误" });
  722. }
  723. /// <summary>
  724. /// 注册 第三方用户数据在CosmosDB
  725. /// </summary>
  726. /// <param name="jsonElement"></param>
  727. /// <returns></returns>
  728. [HttpPost("set-bizuser")]
  729. public async Task<IActionResult> SetBizUserLogin(JsonElement jsonElement)
  730. {
  731. jsonElement.TryGetProperty("name", out JsonElement name);
  732. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  733. jsonElement.TryGetProperty("mail", out JsonElement mail);
  734. jsonElement.TryGetProperty("pwd", out JsonElement pwd);
  735. jsonElement.TryGetProperty("site", out JsonElement site);
  736. var cosmosClient = _azureCosmos.GetCosmosClient();
  737. var tableClient = _azureStorage.GetCloudTableClient();
  738. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  739. if ($"{site}".Equals(BIConst.Global))
  740. {
  741. cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  742. tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  743. blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  744. }
  745. string loginSql = null;
  746. if (!string.IsNullOrEmpty($"{mobile}"))
  747. loginSql = $"select value(c) from c where c.mobile ={mobile}";
  748. else if (!string.IsNullOrEmpty($"{mail}"))
  749. loginSql = $"select value(c) from c where c.mail ={mail}";
  750. else return Ok(new { state = RespondCode.ParamsError, msg = "手机号/和邮箱为空" });
  751. List<BizUsers> tempBizUsers = new();
  752. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BizUsers>(queryText: loginSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
  753. {
  754. tempBizUsers.Add(item);
  755. }
  756. if (tempBizUsers.Count > 0)
  757. return Ok(new { state = RespondCode.Conflict, msg = "已存在" });
  758. else
  759. {
  760. string salt = Utils.CreatSaltString(8);
  761. BizUsers bizUsers = new()
  762. {
  763. id = Guid.NewGuid().ToString(),
  764. code = "BizUsers",
  765. name = string.IsNullOrEmpty($"{name}") ? $"{mobile}" : $"{name}",
  766. mobile = mobile.GetInt64(),
  767. salt = salt,
  768. pwd = string.IsNullOrEmpty($"{pwd}") ? Utils.HashedPassword($"{mobile}", salt) : Utils.HashedPassword($"{pwd}", salt),
  769. };
  770. bizUsers = await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<BizUsers>(bizUsers, new PartitionKey("BizUsers"));
  771. string log = $"{bizUsers.name}【{bizUsers.id}】注册第三方用户信息基础信息。";
  772. //保存操作记录
  773. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "login-login", log, _dingDing, httpContext: HttpContext);
  774. var openid_token = JwtAuthExtension.CreateBizLoginAuthToken(_option.HostName, bizUsers.id?.ToString(), bizUsers.name?.ToString(), bizUsers.picture?.ToString(), $"{_option.Location}-Open", _option.JwtSecretKey, expire: 3);
  775. return Ok(new { state = RespondCode.Ok, openid_token, bizUsers });
  776. }
  777. }
  778. public record DingDingbinds
  779. {
  780. public string type { get; set; }
  781. /// <summary>
  782. /// 所属部门id列表
  783. /// </summary>
  784. public List<long> deptIdList { get; set; }
  785. /// <summary>
  786. /// 职位名称
  787. /// </summary>
  788. public string title { get; set; }
  789. /// <summary>
  790. /// 钉钉用户名
  791. /// </summary>
  792. public string name { get; set; }
  793. /// <summary>
  794. /// 钉钉unionid
  795. /// </summary>
  796. public string unionid { get; set; }
  797. /// <summary>
  798. /// 钉钉ID
  799. /// </summary>
  800. public string userid { get; set; }
  801. }
  802. }
  803. }