LoginController.cs 46 KB

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