LoginController.cs 32 KB

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