LoginController.cs 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577
  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. var id_token = "";
  129. string osblob_uri = null, osblob_sas = null;
  130. List<string> roles = new();//角色列表
  131. List<string> permissions = new();//权限列表
  132. if (ddusers.Count > 0)
  133. {
  134. StringBuilder strMsg = new();
  135. List<DingDingUserInfo> saveInfo = new();
  136. foreach (var item in ddusers)
  137. {
  138. if (string.IsNullOrEmpty(item.tmdId))
  139. {
  140. HttpClient httpClient = _http.CreateClient();
  141. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  142. List<string> mobiles = new() { $"{ item.mobile}" };
  143. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
  144. if (responseMessage.StatusCode == HttpStatusCode.OK)
  145. {
  146. string temp = responseMessage.Content.ReadAsStringAsync().Result;
  147. List<JsonElement> json_id = temp.ToObject<List<JsonElement>>();
  148. if (json_id.Count > 0)
  149. {
  150. foreach (var tmd in json_id)
  151. {
  152. item.tmdId = tmd.GetProperty("id").ToString();
  153. item.tmdName = tmd.GetProperty("name").ToString();
  154. item.tmdMobile = tmd.GetProperty("mobile").ToString();
  155. item.picture = tmd.GetProperty("picture").ToString();
  156. item.mail = tmd.GetProperty("mail").ToString();
  157. }
  158. }
  159. else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  160. }
  161. strMsg.Append($"{item.tmdName}【{item.tmdId}】醍摩豆账号和{item.name}【{item.RowKey}】钉钉账户绑定成功");
  162. }
  163. saveInfo.Add(item);
  164. roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  165. permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
  166. //自己写的
  167. 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);
  168. (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);
  169. }
  170. if (saveInfo.Count > 0)
  171. {
  172. ddusers = await table.UpdateAll<DingDingUserInfo>(saveInfo);
  173. //保存操作记录
  174. await _azureStorage.SaveBILog("tabledd-update", strMsg?.ToString(), _dingDing, httpContext: HttpContext);
  175. }
  176. }
  177. else
  178. {
  179. DingDingUserInfo ddUserInfo = new()
  180. {
  181. PartitionKey = divide,
  182. RowKey = v2GetResponse.Result.Userid,
  183. unionId = v2GetResponse.Result.Unionid,
  184. name = v2GetResponse.Result.Name,
  185. title = v2GetResponse.Result.Title,
  186. mobile = v2GetResponse.Result.Mobile,
  187. jobNumber = v2GetResponse.Result.JobNumber,
  188. pid = 0,
  189. deptId = 0,
  190. deptName = null,
  191. depts = string.Join(",", v2GetResponse.Result.DeptIdList.ToArray()),
  192. avatar = v2GetResponse.Result.Avatar,
  193. isAdmin = v2GetResponse.Result.Admin,
  194. roles = "assist",
  195. permissions = "abilitystandard-read,batcharea-read,batchschool-read,orgusers-read"
  196. };
  197. if (!string.IsNullOrEmpty($"{ddUserInfo.mobile}"))
  198. {
  199. HttpClient httpClient = _http.CreateClient();
  200. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  201. List<string> mobiles = new() { $"{ ddUserInfo.mobile}" };
  202. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
  203. if (responseMessage.StatusCode == HttpStatusCode.OK)
  204. {
  205. string temp = responseMessage.Content.ReadAsStringAsync().Result;
  206. List<JsonElement> json_id = temp.ToObject<List<JsonElement>>();
  207. if (json_id.Count > 0)
  208. {
  209. foreach (var tmd in json_id)
  210. {
  211. ddUserInfo.tmdId = tmd.GetProperty("id").ToString();
  212. ddUserInfo.tmdName = tmd.GetProperty("name").ToString();
  213. ddUserInfo.tmdMobile = tmd.GetProperty("mobile").ToString();
  214. ddUserInfo.picture = tmd.GetProperty("picture").ToString();
  215. ddUserInfo.mail = tmd.GetProperty("mail").ToString();
  216. }
  217. }
  218. else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  219. }
  220. }
  221. else return Ok(new { state = 404, msg = "钉钉手机号为空" });
  222. ddUserInfo = await table.Save<DingDingUserInfo>(ddUserInfo);
  223. //保存操作记录
  224. await _azureStorage.SaveBILog("tabledd-update", $"{ddUserInfo.tmdName}【{ddUserInfo.tmdId}】醍摩豆账号和{ddUserInfo.name}【{ddUserInfo.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext);
  225. roles = !string.IsNullOrEmpty($"{ddUserInfo.roles}") ? new List<string>(ddUserInfo.roles.Split(",")) : new List<string>();
  226. permissions = !string.IsNullOrEmpty($"{ddUserInfo.permissions}") ? new List<string>(ddUserInfo.permissions.Split(",")) : new List<string>();
  227. //自己写的
  228. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, ddUserInfo.tmdId?.ToString(), ddUserInfo.tmdName?.ToString(), ddUserInfo.picture?.ToString(), _option.JwtSecretKey, scope: "assist", Website: "BI", ddUserInfo.RowKey?.ToString(), ddUserInfo.name?.ToString(), ddUserInfo.avatar?.ToString(), roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
  229. (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);
  230. }
  231. return Ok(new { state = 200, ddUserInfos = ddusers, id_token, roles, permissions, osblob_uri, osblob_sas });
  232. }
  233. catch (Exception ex)
  234. {
  235. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/get-ddscancode \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  236. return BadRequest();
  237. }
  238. }
  239. /// <summary>
  240. /// 钉钉绑定醍摩豆
  241. /// </summary>
  242. /// <returns></returns>
  243. [ProducesDefaultResponseType]
  244. [HttpPost("set-bind")]
  245. public async Task<IActionResult> BindUser(JsonElement jsonElement)
  246. {
  247. try
  248. {
  249. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  250. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  251. jsonElement.TryGetProperty("id_token", out JsonElement idtoken);
  252. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  253. HttpClient httpClient = _http.CreateClient();
  254. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  255. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  256. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
  257. var id_token = "";
  258. var auth_token = "";
  259. List<DingDingUserInfo> ddUserInfos = new();
  260. List<string> roles = new();//角色列表
  261. List<string> permissions = new();//权限列表
  262. foreach (var itemUser in tempUser)
  263. {
  264. if (!string.IsNullOrEmpty($"{idtoken}"))
  265. {
  266. JwtSecurityToken jwt = new JwtSecurityToken($"{idtoken}");
  267. var tmdId = jwt.Payload.Sub;
  268. jwt.Payload.TryGetValue("name", out object tmdName);
  269. jwt.Payload.TryGetValue("picture", out object picture);
  270. itemUser.tmdId = tmdId;
  271. itemUser.tmdName = $"{tmdName}";
  272. itemUser.tmdMobile = itemUser.mobile;
  273. itemUser.picture = $"{picture}";
  274. }
  275. if (!string.IsNullOrEmpty($"{mobile}"))
  276. {
  277. List<string> mobiles = new() { $"{mobile}" };
  278. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
  279. if (responseMessage.StatusCode == HttpStatusCode.OK)
  280. {
  281. var temp = await responseMessage.Content.ReadAsStringAsync();
  282. if (temp.Length > 0)
  283. {
  284. List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
  285. foreach (var item in itemjson)
  286. {
  287. itemUser.tmdId = item.GetProperty("id").ToString();
  288. itemUser.tmdName = item.GetProperty("name").ToString();
  289. itemUser.tmdMobile = item.GetProperty("mobile").ToString();
  290. itemUser.picture = item.GetProperty("picture").ToString();
  291. itemUser.mail = item.GetProperty("mail").ToString();
  292. }
  293. }
  294. }
  295. else return Ok(new { state = 404, msg = "手机号未找到醍摩豆账户" });
  296. }
  297. if (string.IsNullOrEmpty($"{mobile}") && string.IsNullOrEmpty($"{idtoken}"))
  298. return Ok(new { state = 400, msg = "mobile、idtoken参数错误" });
  299. else
  300. {
  301. ddUserInfos.Add(itemUser);
  302. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  303. //保存操作记录
  304. await _azureStorage.SaveBILog("tabledd-update", $"{itemUser.tmdName}【{itemUser.tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: "BI", httpContext: HttpContext);
  305. 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);
  306. }
  307. }
  308. ddUserInfos = await table.UpdateAll(ddUserInfos);
  309. //blob 访问权限
  310. 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);
  311. return Ok(new { state = 200, ddUserInfos, id_token, roles, osblob_uri, osblob_sas });
  312. }
  313. catch (Exception ex)
  314. {
  315. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/set-bind \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  316. return BadRequest();
  317. }
  318. }
  319. /// <summary>
  320. /// 获取钉钉信息详情绑定醍摩豆和钉钉信息 二合一
  321. /// </summary>
  322. /// <param name="jsonElement"></param>
  323. /// <returns></returns>
  324. [ProducesDefaultResponseType]
  325. [HttpPost("get-ddinfo")]
  326. public async Task<IActionResult> GetDingDingInfo(JsonElement jsonElement)
  327. {
  328. try
  329. {
  330. if (!jsonElement.TryGetProperty("mobile", out JsonElement moile)) return BadRequest();
  331. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  332. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  333. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  334. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
  335. List<string> roles = new();//角色列表
  336. List<string> permissions = new();//权限列表
  337. List<DingDingUserInfo> ddUserInfos = new();
  338. var id_token = "";
  339. foreach (var itemUser in tempUser)
  340. {
  341. if (!string.IsNullOrEmpty($"{itemUser.tmdId}") && !string.IsNullOrEmpty($"{itemUser.tmdName}"))
  342. {
  343. //roles = new List<string>(itemUser.roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
  344. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  345. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  346. ddUserInfos.Add(itemUser);
  347. }
  348. else
  349. {
  350. HttpClient httpClient = _http.CreateClient();
  351. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  352. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, moile);
  353. if (responseMessage.StatusCode == HttpStatusCode.OK)
  354. {
  355. var temp = await responseMessage.Content.ReadAsStringAsync();
  356. if (temp.Length > 0)
  357. {
  358. List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
  359. string tmdId = null;
  360. string tmdName = null;
  361. foreach (var item in itemjson)
  362. {
  363. tmdId = item.GetProperty("id").ToString();
  364. tmdName = item.GetProperty("name").ToString();
  365. itemUser.tmdId = tmdId?.ToString();
  366. itemUser.tmdName = tmdName?.ToString();
  367. itemUser.tmdMobile = item.GetProperty("mobile").ToString();
  368. itemUser.picture = item.GetProperty("picture").ToString();
  369. itemUser.mail = item.GetProperty("mail").ToString();
  370. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  371. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  372. ddUserInfos.Add(itemUser);
  373. }
  374. ddUserInfos = await table.UpdateAll<DingDingUserInfo>(ddUserInfos);
  375. //保存操作记录
  376. await _azureStorage.SaveBILog("tabledd-update", $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: "BI", httpContext: HttpContext);
  377. }
  378. else return Ok(new { state = 400, message = "该手机没有注册醍摩豆账号信息" });
  379. }
  380. else return Ok(new { state = responseMessage.StatusCode });
  381. }
  382. //自己写的
  383. 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);
  384. }
  385. 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);
  386. return Ok(new { state = 200, ddUserInfos, id_token, roles, permissions, osblob_uri, osblob_sas });
  387. }
  388. catch (Exception ex)
  389. {
  390. await _dingDing.SendBotMsg($"BI,{_option.Location} /common/login/get-ddinfo \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  391. return BadRequest();
  392. }
  393. }
  394. /// <summary>
  395. /// 企业登录
  396. /// </summary>
  397. /// <param name="jsonElement"></param>
  398. /// <returns></returns>
  399. [ProducesDefaultResponseType]
  400. [HttpPost("get-commpany")]
  401. public async Task<IActionResult> GetCommpanyLogin(JsonElement jsonElement)
  402. {
  403. if (!jsonElement.TryGetProperty("account", out JsonElement accout)) return BadRequest();
  404. if (!jsonElement.TryGetProperty("password", out JsonElement password)) return BadRequest();
  405. StringBuilder sqlTxt = new($"select value(c) from c");
  406. var cosmosClient = _azureCosmos.GetCosmosClient();
  407. var temps = $"{accout}".Contains($"@");
  408. if (temps)
  409. sqlTxt.Append($" where c.emall='{accout}'");
  410. else
  411. sqlTxt.Append($" where c.mobile='{accout}'");
  412. Company company = new();
  413. List<Company> companies = new();
  414. string id_token = "";
  415. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<Company>(queryText: sqlTxt.ToString(), requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Company") }))
  416. {
  417. companies.Add(item);
  418. }
  419. if (companies.Count > 0)
  420. {
  421. foreach (var item in companies)
  422. {
  423. var hashedPw = Utils.HashedPassword(password.ToString(), item.salt.ToString());
  424. if (hashedPw.Equals(item.password))
  425. {
  426. company = item;
  427. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, item.id?.ToString(), item.name?.ToString(), company.picture?.ToString(), _option.JwtSecretKey, scope: "company", Website: "BI", expire: 3);
  428. }
  429. }
  430. }
  431. else return Ok(new { state = 404 });
  432. //保存操作记录
  433. await _azureStorage.SaveBILog("tabledd-update", $"{company.name}【{company.id}】登录商务智能开放平台", _dingDing, tid: company.id, tname: company.name, twebsite: "BI", httpContext: HttpContext);
  434. return Ok(new { error = 200, id_token, company });
  435. }
  436. /// <summary>
  437. /// 企业注册信息
  438. /// </summary>
  439. /// <param name="jsonElement"></param>
  440. /// <returns></returns>
  441. [HttpPost("set-registered")]
  442. public async Task<IActionResult> SetRegistered(JsonElement jsonElement)
  443. {
  444. if (!jsonElement.TryGetProperty("name", out JsonElement name)) return BadRequest();
  445. if (!jsonElement.TryGetProperty("credit", out JsonElement credit)) return BadRequest();
  446. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  447. if (!jsonElement.TryGetProperty("password", out JsonElement password)) return BadRequest();
  448. var cosmosClient = _azureCosmos.GetCosmosClient();
  449. string salt = Utils.CreatSaltString(8);
  450. string sqltxt = $"select value(c) from c where c.mobile='{mobile}'";
  451. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryStreamIterator(queryText: sqltxt, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("Company") }))
  452. {
  453. using var json = await JsonDocument.ParseAsync(item.ContentStream);
  454. if (json.RootElement.TryGetProperty("_count", out JsonElement count) && count.GetUInt16() > 0)
  455. {
  456. return Ok(new { state = 201, msg = "手机号已存在," });
  457. }
  458. }
  459. CreateSchoolInfo createCompanyCode = new CreateSchoolInfo()
  460. {
  461. province = "",
  462. id = "",
  463. name = $"{name}",
  464. city = "",
  465. aname = "",
  466. createCount = 0,
  467. };
  468. //生成企业ID
  469. bool tempStaus = true;
  470. do
  471. {
  472. createCompanyCode = await SchoolCode.GenerateSchoolCode(createCompanyCode, _dingDing, _environment);
  473. var companyState = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{createCompanyCode.id}", new PartitionKey("Company"));
  474. if (companyState.Status != 200) tempStaus = false;
  475. else createCompanyCode.createCount = createCompanyCode.createCount >= 3 ? createCompanyCode.createCount = 3 : createCompanyCode.createCount += 1;
  476. } while (tempStaus);
  477. Company company = new() { name = $"{name}", credit = $"{credit}", mobile = $"{mobile}", salt = salt, password = Utils.HashedPassword($"{password}", salt), pk = "Company", code = "Company", createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds() };
  478. company = await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<Company>(company, new PartitionKey("Company"));
  479. //保存操作记录
  480. await _azureStorage.SaveBILog("tabledd-update", $"{company.name}【{company.id}】注册商务智能开放平台", _dingDing, tid: company.id, tname: company.name, twebsite: "BI", httpContext: HttpContext);
  481. return Ok(new { state = 200, company });
  482. }
  483. public record DingDingbinds
  484. {
  485. public string type { get; set; }
  486. /// <summary>
  487. /// 所属部门id列表
  488. /// </summary>
  489. public List<long> deptIdList { get; set; }
  490. /// <summary>
  491. /// 职位名称
  492. /// </summary>
  493. public string title { get; set; }
  494. /// <summary>
  495. /// 钉钉用户名
  496. /// </summary>
  497. public string name { get; set; }
  498. /// <summary>
  499. /// 钉钉unionid
  500. /// </summary>
  501. public string unionid { get; set; }
  502. /// <summary>
  503. /// 钉钉ID
  504. /// </summary>
  505. public string userid { get; set; }
  506. }
  507. }
  508. }