LoginController.cs 36 KB

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