LoginController.cs 34 KB

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