LoginController.cs 28 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527
  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 static DingTalk.Api.Response.OapiV2UserGetResponse;
  37. namespace TEAMModelBI.Controllers
  38. {
  39. [ProducesResponseType(StatusCodes.Status200OK)]
  40. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  41. [Route("common/login")]
  42. [ApiController]
  43. public class LoginController : ControllerBase
  44. {
  45. private readonly IConfiguration _configuration;
  46. //数据容器
  47. private readonly AzureCosmosFactory _azureCosmos;
  48. //文件容器
  49. private readonly AzureStorageFactory _azureStorage;
  50. //钉钉提示信息
  51. private readonly DingDing _dingDing;
  52. private readonly Option _option;
  53. //隐式登录
  54. private readonly CoreAPIHttpService _aoreAPIHttpService;
  55. private readonly IHttpClientFactory _http;
  56. private readonly IWebHostEnvironment _environment; //读取文件
  57. string type = "ddteammodel";
  58. public LoginController(IConfiguration configuration, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, CoreAPIHttpService aoreAPIHttpService, IHttpClientFactory http, IWebHostEnvironment environment)
  59. {
  60. _configuration = configuration;
  61. _azureCosmos = azureCosmos;
  62. _azureStorage = azureStorage;
  63. _dingDing = dingDing;
  64. _option = option?.Value;
  65. _aoreAPIHttpService = aoreAPIHttpService;
  66. _http = http;
  67. _environment = environment;
  68. }
  69. /// <summary>
  70. /// 钉钉扫码登录获取扫码信息
  71. /// </summary>
  72. /// <param name="jsonElement"></param>
  73. /// <returns></returns>
  74. [ProducesDefaultResponseType]
  75. [HttpPost("get-ddscancode")]
  76. public async Task<IActionResult> GetDingDingScanCode(JsonElement jsonElement)
  77. {
  78. try
  79. {
  80. string appKey = _configuration["DingDingAuth:appKey"];
  81. string appSecret = _configuration["DingDingAuth:appSecret"];
  82. string divide = _configuration["CustomParam:SiteScope"];
  83. if (string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appSecret))
  84. {
  85. return Ok(new { state = 0, message = "请检查配置钉钉的信息" });
  86. }
  87. //自己传的code
  88. if (!jsonElement.TryGetProperty("code", out JsonElement LoginTempCode)) return BadRequest();
  89. //获取access_token
  90. IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  91. OapiGettokenRequest tokenRequest = new() { Appkey = appKey, Appsecret = appSecret };
  92. tokenRequest.SetHttpMethod("Get");
  93. OapiGettokenResponse tokenRespone = tokenClient.Execute(tokenRequest);
  94. if (tokenRespone.IsError) return BadRequest();
  95. string access_token = tokenRespone.AccessToken;
  96. //获取临时授权码 获取授权用户的个人信息
  97. DefaultDingTalkClient clientinfo = new("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
  98. OapiSnsGetuserinfoBycodeRequest req = new() { TmpAuthCode = $"{LoginTempCode}" }; //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
  99. OapiSnsGetuserinfoBycodeResponse response = clientinfo.Execute(req, appKey, appSecret);
  100. if (response.Errcode.Equals(40078))
  101. {
  102. return Ok(new { state = 0, message = $"state:{response.Errcode};Err{response.Errmsg}/临时授权码过期请重新扫码" });
  103. }
  104. string unionid = response.UserInfo.Unionid;
  105. IDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); //userid地址
  106. OapiUserGetbyunionidRequest byunionidRequest = new() { Unionid = unionid };
  107. OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, access_token);
  108. if (byunionidResponse.IsError || byunionidResponse.Errcode == 60121)
  109. {
  110. return Ok(new { state = 0, message = byunionidResponse.Errmsg });
  111. }
  112. // 根据userId获取用户信息
  113. string userid = byunionidResponse.Result.Userid;
  114. IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  115. OapiV2UserGetRequest v2GetRequest = new()
  116. {
  117. Userid = userid,
  118. Language = "zh_CN"
  119. };
  120. v2GetRequest.SetHttpMethod("POST");
  121. OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
  122. if (v2GetResponse.IsError)
  123. {
  124. return Ok(new { state = 0, message = "扫码登录失败" });
  125. }
  126. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  127. List<DingDingUserInfo> ddusers = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object>() { { "RowKey", $"{v2GetResponse.Result.Userid}" }, { "unionId", $"{v2GetResponse.Result.Unionid}" } });
  128. if (ddusers.Count > 0)
  129. {
  130. List<DingDingUserInfo> ddUserInfos = new List<DingDingUserInfo>();
  131. var id_token = "";
  132. string osblob_uri = null, osblob_sas = null;
  133. List<string> roles = new();//角色列表
  134. List<string> permissions = new List<string>();//权限列表
  135. foreach (var item in ddusers)
  136. {
  137. ddUserInfos.Add(item);
  138. }
  139. foreach (var item in ddUserInfos)
  140. {
  141. if (!string.IsNullOrEmpty(item.tmdId))
  142. {
  143. roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  144. permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
  145. ///在IES5 添加
  146. //id_token = JwtAuthExtension.CreateAuthToken(_option.HostName, item.tmdId?.ToString(), item.tmdName?.ToString(), item.picture?.ToString(), _option.JwtSecretKey, Website: "BI", scope: $"assist", roles: roles?.ToArray(), permissions: permissions?.ToArray(), ddsub: item.RowKey?.ToString());
  147. //自己写的
  148. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, item.tmdId?.ToString(), item.tmdName?.ToString(), item.picture?.ToString(), _option.JwtSecretKey, scope: "assist", Website: "BI", item.RowKey?.ToString(), item.name?.ToString(), item.avatar?.ToString(), roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
  149. (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);
  150. }
  151. else
  152. {
  153. return Ok(new { state = 201, ddUserInfos });
  154. }
  155. }
  156. return Ok(new { state = 200, ddUserInfos, id_token, roles, permissions, osblob_uri, osblob_sas });
  157. }
  158. else
  159. {
  160. DingDingUserInfo dingDingUserInfo = new()
  161. {
  162. PartitionKey = divide,
  163. RowKey = v2GetResponse.Result.Userid,
  164. unionId = v2GetResponse.Result.Unionid,
  165. name = v2GetResponse.Result.Name,
  166. title = v2GetResponse.Result.Title,
  167. mobile = v2GetResponse.Result.Mobile,
  168. jobNumber = v2GetResponse.Result.JobNumber,
  169. pid = 0,
  170. deptId = 0,
  171. deptName = null,
  172. depts = string.Join(",", v2GetResponse.Result.DeptIdList.ToArray()),
  173. avatar = v2GetResponse.Result.Avatar,
  174. isAdmin = v2GetResponse.Result.Admin,
  175. tmdId = "",
  176. tmdName = "",
  177. tmdMobile = "",
  178. mail = "",
  179. picture = "",
  180. roles = "",
  181. permissions = "",
  182. };
  183. await table.Save<DingDingUserInfo>(dingDingUserInfo);
  184. return Ok(new { state = 400, ddUserId = dingDingUserInfo });
  185. }
  186. }
  187. catch (Exception ex)
  188. {
  189. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/get-ddscancode \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  190. return BadRequest();
  191. }
  192. }
  193. /// <summary>
  194. /// 钉钉绑定醍摩豆
  195. /// </summary>
  196. /// <returns></returns>
  197. [ProducesDefaultResponseType]
  198. [HttpPost("set-bind")]
  199. public async Task<IActionResult> BindUser(JsonElement jsonElement)
  200. {
  201. try
  202. {
  203. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  204. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  205. jsonElement.TryGetProperty("id_token", out JsonElement idtoken);
  206. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  207. HttpClient httpClient = _http.CreateClient();
  208. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  209. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  210. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
  211. var id_token = "";
  212. var auth_token = "";
  213. List<DingDingUserInfo> ddUserInfos = new();
  214. List<string> roles = new();//角色列表
  215. List<string> permissions = new();//权限列表
  216. foreach (var itemUser in tempUser)
  217. {
  218. if (!string.IsNullOrEmpty($"{idtoken}"))
  219. {
  220. JwtSecurityToken jwt = new JwtSecurityToken($"{idtoken}");
  221. var tmdId = jwt.Payload.Sub;
  222. jwt.Payload.TryGetValue("name", out object tmdName);
  223. jwt.Payload.TryGetValue("picture", out object picture);
  224. itemUser.tmdId = tmdId;
  225. itemUser.tmdName = $"{tmdName}";
  226. itemUser.tmdMobile = itemUser.mobile;
  227. itemUser.picture = $"{picture}";
  228. }
  229. if (!string.IsNullOrEmpty($"{mobile}"))
  230. {
  231. List<string> mobiles = new() { $"{mobile}" };
  232. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
  233. if (responseMessage.StatusCode == HttpStatusCode.OK)
  234. {
  235. var temp = await responseMessage.Content.ReadAsStringAsync();
  236. if (temp.Length > 0)
  237. {
  238. List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
  239. foreach (var item in itemjson)
  240. {
  241. itemUser.tmdId = item.GetProperty("id").ToString();
  242. itemUser.tmdName = item.GetProperty("name").ToString();
  243. itemUser.tmdMobile = item.GetProperty("mobile").ToString();
  244. itemUser.picture = item.GetProperty("picture").ToString();
  245. itemUser.mail = item.GetProperty("mail").ToString();
  246. }
  247. }
  248. }
  249. else return Ok(new { state = 404, msg = "手机号未找到醍摩豆账户" });
  250. }
  251. if (string.IsNullOrEmpty($"{mobile}") && string.IsNullOrEmpty($"{idtoken}"))
  252. return Ok(new { state = 400, msg = "mobile、idtoken参数错误" });
  253. else
  254. {
  255. ddUserInfos.Add(itemUser);
  256. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  257. //保存操作记录
  258. await _azureStorage.SaveBILog("tabledd-update", $"{itemUser.tmdName}【{itemUser.tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: "BI", httpContext: HttpContext);
  259. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), _option.JwtSecretKey, scope: "assist", Website: "BI", itemUser.RowKey?.ToString(), itemUser.name?.ToString(), itemUser.avatar?.ToString(), roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
  260. }
  261. }
  262. ddUserInfos = await table.UpdateAll(ddUserInfos);
  263. //blob 访问权限
  264. 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);
  265. return Ok(new { state = 200, ddUserInfos, id_token, roles, osblob_uri, osblob_sas });
  266. }
  267. catch (Exception ex)
  268. {
  269. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/set-bind \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  270. return BadRequest();
  271. }
  272. }
  273. /// <summary>
  274. /// 获取钉钉信息详情绑定醍摩豆和钉钉信息 二合一
  275. /// </summary>
  276. /// <param name="jsonElement"></param>
  277. /// <returns></returns>
  278. [ProducesDefaultResponseType]
  279. [HttpPost("get-ddinfo")]
  280. public async Task<IActionResult> GetDingDingInfo(JsonElement jsonElement)
  281. {
  282. try
  283. {
  284. if (!jsonElement.TryGetProperty("mobile", out JsonElement moile)) return BadRequest();
  285. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  286. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  287. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  288. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
  289. List<string> roles = new();//角色列表
  290. List<string> permissions = new();//权限列表
  291. List<DingDingUserInfo> ddUserInfos = new();
  292. var id_token = "";
  293. foreach (var itemUser in tempUser)
  294. {
  295. if (!string.IsNullOrEmpty($"{itemUser.tmdId}") && !string.IsNullOrEmpty($"{itemUser.tmdName}"))
  296. {
  297. //roles = new List<string>(itemUser.roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
  298. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  299. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  300. ddUserInfos.Add(itemUser);
  301. }
  302. else
  303. {
  304. HttpClient httpClient = _http.CreateClient();
  305. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  306. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, moile);
  307. if (responseMessage.StatusCode == HttpStatusCode.OK)
  308. {
  309. var temp = await responseMessage.Content.ReadAsStringAsync();
  310. if (temp.Length > 0)
  311. {
  312. List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
  313. string tmdId = null;
  314. string tmdName = null;
  315. foreach (var item in itemjson)
  316. {
  317. tmdId = item.GetProperty("id").ToString();
  318. tmdName = item.GetProperty("name").ToString();
  319. itemUser.tmdId = tmdId?.ToString();
  320. itemUser.tmdName = tmdName?.ToString();
  321. itemUser.tmdMobile = item.GetProperty("mobile").ToString();
  322. itemUser.picture = item.GetProperty("picture").ToString();
  323. itemUser.mail = item.GetProperty("mail").ToString();
  324. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  325. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  326. ddUserInfos.Add(itemUser);
  327. }
  328. ddUserInfos = await table.UpdateAll<DingDingUserInfo>(ddUserInfos);
  329. //保存操作记录
  330. await _azureStorage.SaveBILog("tabledd-update", $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: "BI", httpContext: HttpContext);
  331. }
  332. else return Ok(new { state = 400, message = "该手机没有注册醍摩豆账号信息" });
  333. }
  334. else return Ok(new { state = responseMessage.StatusCode });
  335. }
  336. ////在IES5 的基础上增加参数
  337. //id_token = JwtAuthExtension.CreateAuthToken(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), _option.JwtSecretKey,Website: "BI", scope: $"assist", roles: roles?.ToArray(), permissions: permissions?.ToArray(), ddsub: itemUser.RowKey?.ToString());
  338. //自己写的
  339. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), _option.JwtSecretKey, scope: "assist", Website: "BI", itemUser.RowKey?.ToString(), itemUser.name?.ToString(), itemUser.avatar?.ToString(), roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
  340. }
  341. 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);
  342. return Ok(new { state = 200, ddUserInfos, id_token, roles, permissions, osblob_uri, osblob_sas });
  343. }
  344. catch (Exception ex)
  345. {
  346. await _dingDing.SendBotMsg($"BI,{_option.Location} /common/login/get-ddinfo \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  347. return BadRequest();
  348. }
  349. }
  350. /// <summary>
  351. /// 企业登录
  352. /// </summary>
  353. /// <param name="jsonElement"></param>
  354. /// <returns></returns>
  355. [ProducesDefaultResponseType]
  356. [HttpPost("get-commpany")]
  357. public async Task<IActionResult> GetCommpanyLogin(JsonElement jsonElement)
  358. {
  359. if (!jsonElement.TryGetProperty("account", out JsonElement accout)) return BadRequest();
  360. if (!jsonElement.TryGetProperty("password", out JsonElement password)) return BadRequest();
  361. StringBuilder sqlTxt = new($"select value(c) from c");
  362. var cosmosClient = _azureCosmos.GetCosmosClient();
  363. var temps = $"{accout}".Contains($"@");
  364. if (temps)
  365. sqlTxt.Append($" where c.emall='{accout}'");
  366. else
  367. sqlTxt.Append($" where c.mobile='{accout}'");
  368. Company company = new();
  369. List<Company> companies = new();
  370. string id_token = "";
  371. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<Company>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Company") }))
  372. {
  373. companies.Add(item);
  374. }
  375. if (companies.Count > 0)
  376. {
  377. foreach (var item in companies)
  378. {
  379. var hashedPw = Utils.HashedPassword(password.ToString(), item.salt.ToString());
  380. if (hashedPw.Equals(item.password))
  381. {
  382. company = item;
  383. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, item.id?.ToString(), item.name?.ToString(), company.picture?.ToString(), _option.JwtSecretKey, scope: "company", Website: "BI", expire: 3);
  384. }
  385. }
  386. }
  387. else return Ok(new { state = 404 });
  388. //保存操作记录
  389. await _azureStorage.SaveBILog("tabledd-update", $"{company.name}【{company.id}】登录商务智能开放平台", _dingDing, tid: company.id, tname: company.name, twebsite: "BI", httpContext: HttpContext);
  390. return Ok(new { error = 200, id_token, company });
  391. }
  392. /// <summary>
  393. /// 企业注册信息
  394. /// </summary>
  395. /// <param name="jsonElement"></param>
  396. /// <returns></returns>
  397. [HttpPost("set-registered")]
  398. public async Task<IActionResult> SetRegistered(JsonElement jsonElement)
  399. {
  400. if (!jsonElement.TryGetProperty("name", out JsonElement name)) return BadRequest();
  401. if (!jsonElement.TryGetProperty("credit", out JsonElement credit)) return BadRequest();
  402. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  403. if (!jsonElement.TryGetProperty("password", out JsonElement password)) return BadRequest();
  404. var cosmosClient = _azureCosmos.GetCosmosClient();
  405. string salt = Utils.CreatSaltString(8);
  406. string sqltxt = $"select value(c) from c where c.mobile='{mobile}'";
  407. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryStreamIterator(queryText: sqltxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Company") }))
  408. {
  409. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  410. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  411. {
  412. return Ok(new { state = 201, msg = "手机号已存在," });
  413. }
  414. }
  415. CreateSchoolInfo createCompanyCode = new CreateSchoolInfo()
  416. {
  417. province = "",
  418. id = "",
  419. name = $"{name}",
  420. city = "",
  421. aname = "",
  422. createCount = 0,
  423. };
  424. //生成企业ID
  425. bool tempStaus = true;
  426. do
  427. {
  428. createCompanyCode = await SchoolCode.GenerateSchoolCode(createCompanyCode, _dingDing, _environment);
  429. var companyState = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{createCompanyCode.id}", new PartitionKey("Company"));
  430. if (companyState.Status != 200) tempStaus = false;
  431. else createCompanyCode.createCount = createCompanyCode.createCount >= 3 ? createCompanyCode.createCount = 3 : createCompanyCode.createCount += 1;
  432. } while (tempStaus);
  433. Company company = new() { name = $"{name}", credit = $"{credit}", mobile = $"{mobile}", salt = salt, password = Utils.HashedPassword($"{password}", salt), pk = "Company", code = "Company", createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() };
  434. company = await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<Company>(company, new PartitionKey("Company"));
  435. //保存操作记录
  436. await _azureStorage.SaveBILog("tabledd-update", $"{company.name}【{company.id}】注册商务智能开放平台", _dingDing, tid: company.id, tname: company.name, twebsite: "BI", httpContext: HttpContext);
  437. return Ok(new { state = 200, company });
  438. }
  439. public record DingDingbinds
  440. {
  441. public string type { get; set; }
  442. /// <summary>
  443. /// 所属部门id列表
  444. /// </summary>
  445. public List<long> deptIdList { get; set; }
  446. /// <summary>
  447. /// 职位名称
  448. /// </summary>
  449. public string title { get; set; }
  450. /// <summary>
  451. /// 钉钉用户名
  452. /// </summary>
  453. public string name { get; set; }
  454. /// <summary>
  455. /// 钉钉unionid
  456. /// </summary>
  457. public string unionid { get; set; }
  458. /// <summary>
  459. /// 钉钉ID
  460. /// </summary>
  461. public string userid { get; set; }
  462. }
  463. }
  464. }