LoginController.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659
  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. ////分开部署,就不需要,一站多用时,取消注释
  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) || response.Errcode.Equals(853002))
  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 (item.isDisable == 0)
  158. return Ok(new { state = RespondCode.Forbidden, msg = "账户被禁用!请联系管理员!" });
  159. if (string.IsNullOrEmpty(item.tmdId))
  160. {
  161. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{item.mobile}" } }, _option.Location, _configuration);
  162. if (coreUser != null && coreUser.id != null)
  163. {
  164. item.tmdId = coreUser.id;
  165. item.tmdName = coreUser.name;
  166. item.tmdMobile = coreUser.mobile;
  167. item.picture = coreUser.picture;
  168. item.mail = coreUser.mail;
  169. }
  170. else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  171. //List<string> mobiles = new() { $"{ item.mobile}" };
  172. //var content = new StringContent(mobiles.ToJsonString(), Encoding.UTF8, "application/json");
  173. //string json = await _coreAPIHttpService.GetUserInfos(content);
  174. //if (!string.IsNullOrEmpty(json))
  175. //{
  176. // List<JsonElement> json_id = json.ToObject<List<JsonElement>>();
  177. // foreach (var tmd in json_id)
  178. // {
  179. // item.tmdId = tmd.GetProperty("id").ToString();
  180. // item.tmdName = tmd.GetProperty("name").ToString();
  181. // item.tmdMobile = tmd.GetProperty("mobile").ToString();
  182. // item.picture = tmd.GetProperty("picture").ToString();
  183. // item.mail = tmd.GetProperty("mail").ToString();
  184. // }
  185. //}
  186. //else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  187. strMsg.Append($"{item.tmdName}【{item.tmdId}】醍摩豆账号和{item.name}【{item.userId}】钉钉账户绑定成功");
  188. //保存操作记录
  189. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", strMsg?.ToString(), _dingDing, httpContext: HttpContext, twebsite: Website, tid: item.tmdId, tname: item.tmdName);
  190. saveInfo.Add(item);
  191. }
  192. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, item.tmdId);
  193. if (schoolIds.Count > 0)
  194. {
  195. item.schoolIds = string.Join("|", schoolIds);
  196. await table.SaveOrUpdate<DingDingUserInfo>(item);
  197. }
  198. roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  199. roles = roles.Where(w => !string.IsNullOrEmpty(w)).ToList();
  200. permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
  201. if (item.depts.Contains($"{proDeptId}")) isExploit = true;
  202. if (item.deptId == long.Parse($"{proDeptId}")) isExploit = true;
  203. if (item.pid == long.Parse($"{proDeptId}")) isExploit = true;
  204. if(roles.Contains("leader")) isExploit= true;
  205. //自己写的
  206. 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());
  207. }
  208. if (saveInfo.Count > 0)
  209. {
  210. ddusers = await table.UpdateAll<DingDingUserInfo>(saveInfo);
  211. }
  212. }
  213. else
  214. {
  215. long joinDate = DateTimeOffset.UtcNow.AddDays(-91).ToUnixTimeMilliseconds();
  216. long isDisable = 0;
  217. if (!string.IsNullOrEmpty($"{v2GetResponse.Result.HiredDate}"))
  218. {
  219. if (v2GetResponse.Result.HiredDate < joinDate)
  220. isDisable = 1;
  221. else
  222. isDisable = 0;
  223. }
  224. DingDingUserInfo ddUserInfo = new()
  225. {
  226. PartitionKey = divide,
  227. RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
  228. userId = v2GetResponse.Result.Userid,
  229. unionId = v2GetResponse.Result.Unionid,
  230. name = v2GetResponse.Result.Name,
  231. title = v2GetResponse.Result.Title,
  232. mobile = v2GetResponse.Result.Mobile,
  233. jobNumber = v2GetResponse.Result.JobNumber,
  234. pid = 0,
  235. deptId = 0,
  236. deptName = null,
  237. depts = string.Join(",", v2GetResponse.Result.DeptIdList.ToArray()),
  238. avatar = v2GetResponse.Result.Avatar,
  239. isAdmin = v2GetResponse.Result.Admin,
  240. roles = "assist",
  241. permissions = "abilitystandard-read,batcharea-read,batchschool-read,orgusers-read",
  242. isDisable = 0
  243. };
  244. if (!string.IsNullOrEmpty($"{ddUserInfo.mobile}"))
  245. {
  246. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{ddUserInfo.mobile}" } }, _option.Location, _configuration);
  247. if (coreUser != null && coreUser.id != null) {
  248. ddUserInfo.tmdId = coreUser.id;
  249. ddUserInfo.tmdName = coreUser.name;
  250. ddUserInfo.tmdMobile = coreUser.mobile;
  251. ddUserInfo.picture = coreUser.mobile;
  252. ddUserInfo.mail = coreUser.mail;
  253. }
  254. else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
  255. }
  256. else return Ok(new { state = 404, msg = "钉钉手机号为空" });
  257. List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, ddUserInfo.tmdId);
  258. if (schoolIds.Count > 0)
  259. {
  260. ddUserInfo.schoolIds = string.Join("|", schoolIds);
  261. }
  262. ddUserInfo = await table.Save<DingDingUserInfo>(ddUserInfo);
  263. //保存操作记录
  264. 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);
  265. if (isDisable == 0)
  266. return Ok(new { state = RespondCode.Forbidden, msg = "账户被禁用!请联系管理员!" });
  267. roles = !string.IsNullOrEmpty($"{ddUserInfo.roles}") ? new List<string>(ddUserInfo.roles.Split(",")) : new List<string>();
  268. roles = roles.Where(w => !string.IsNullOrEmpty(w)).ToList();
  269. permissions = !string.IsNullOrEmpty($"{ddUserInfo.permissions}") ? new List<string>(ddUserInfo.permissions.Split(",")) : new List<string>();
  270. if (ddUserInfo.depts.Contains($"{proDeptId}")) isExploit = true;
  271. if (ddUserInfo.deptId == long.Parse($"{proDeptId}")) isExploit = true;
  272. if (ddUserInfo.pid == long.Parse($"{proDeptId}")) isExploit = true;
  273. if (roles.Contains("leader")) isExploit = true;
  274. //自己写的
  275. 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());
  276. }
  277. if (Website.Equals(BIConst.Global))
  278. {
  279. (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete, BIConst.Global);
  280. }
  281. else
  282. {
  283. (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
  284. }
  285. //(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);
  286. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  287. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  288. var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, _option.Location.Replace("-Dep", "").Replace("-Test", ""));
  289. return Ok(new { state = 200, ddUserInfos = ddusers, id_token, roles, permissions, osblob_uri, osblob_sas , access_token = token.AccessToken });
  290. }
  291. catch (Exception ex)
  292. {
  293. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/get-ddscancode \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  294. return BadRequest();
  295. }
  296. }
  297. /// <summary>
  298. /// 钉钉绑定醍摩豆 已对接
  299. /// </summary>
  300. /// <returns></returns>
  301. [ProducesDefaultResponseType]
  302. [HttpPost("set-bind")]
  303. public async Task<IActionResult> BindUser(JsonElement jsonElement)
  304. {
  305. try
  306. {
  307. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  308. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  309. jsonElement.TryGetProperty("id_token", out JsonElement idtoken);
  310. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  311. jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  312. string Website = "China";
  313. var tableClient = _azureStorage.GetCloudTableClient();
  314. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  315. ////分开部署,就不需要,一站多用时,取消注释
  316. //if ($"{site}".Equals(BIConst.Global))
  317. //{
  318. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  319. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  320. // Website = BIConst.Global;
  321. //}
  322. HttpClient httpClient = _http.CreateClient();
  323. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  324. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "userId", $"{userId}" } });
  325. var id_token = "";
  326. var auth_token = "";
  327. List<DingDingUserInfo> ddUserInfos = new();
  328. List<string> roles = new();//角色列表
  329. List<string> permissions = new();//权限列表
  330. foreach (var itemUser in tempUser)
  331. {
  332. if (!string.IsNullOrEmpty($"{idtoken}"))
  333. {
  334. JwtSecurityToken jwt = new JwtSecurityToken($"{idtoken}");
  335. var tmdId = jwt.Payload.Sub;
  336. jwt.Payload.TryGetValue("name", out object tmdName);
  337. jwt.Payload.TryGetValue("picture", out object picture);
  338. itemUser.tmdId = tmdId;
  339. itemUser.tmdName = $"{tmdName}";
  340. itemUser.tmdMobile = itemUser.mobile;
  341. itemUser.picture = $"{picture}";
  342. }
  343. if (!string.IsNullOrEmpty($"{mobile}"))
  344. {
  345. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{mobile}" } }, _option.Location, _configuration);
  346. if (coreUser != null && coreUser.id != null)
  347. {
  348. itemUser.tmdId = coreUser.id;
  349. itemUser.tmdName = coreUser.name;
  350. itemUser.tmdMobile = coreUser.mobile;
  351. itemUser.picture = coreUser.mobile;
  352. itemUser.mail = coreUser.mail;
  353. }
  354. else return Ok(new { state = 404, msg = "手机号未找到醍摩豆账户" });
  355. }
  356. if (string.IsNullOrEmpty($"{mobile}") && string.IsNullOrEmpty($"{idtoken}"))
  357. return Ok(new { state = 400, msg = "mobile、idtoken参数错误" });
  358. else
  359. {
  360. ddUserInfos.Add(itemUser);
  361. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  362. roles = roles.Where(w => !string.IsNullOrEmpty(w)).ToList();
  363. //保存操作记录
  364. 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);
  365. 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());
  366. }
  367. }
  368. ddUserInfos = await table.UpdateAll(ddUserInfos);
  369. string osblob_uri = null, osblob_sas = null;
  370. if (Website.Equals(BIConst.Global))
  371. {
  372. (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete, BIConst.Global);
  373. }
  374. else
  375. {
  376. (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
  377. }
  378. //blob 访问权限
  379. //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);
  380. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  381. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  382. var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, _option.Location.Replace("-Dep", "").Replace("-Test", ""));
  383. return Ok(new { state = 200, ddUserInfos, id_token, roles, osblob_uri, osblob_sas, access_token = token.AccessToken });
  384. }
  385. catch (Exception ex)
  386. {
  387. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/set-bind \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  388. return BadRequest();
  389. }
  390. }
  391. /// <summary>
  392. /// 获取钉钉信息详情绑定醍摩豆和钉钉信息 二合一
  393. /// </summary>
  394. /// <param name="jsonElement"></param>
  395. /// <returns></returns>
  396. [ProducesDefaultResponseType]
  397. [HttpPost("get-ddinfo")]
  398. public async Task<IActionResult> GetDingDingInfo(JsonElement jsonElement)
  399. {
  400. try
  401. {
  402. if (!jsonElement.TryGetProperty("mobile", out JsonElement moile)) return BadRequest();
  403. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  404. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  405. //jsonElement.TryGetProperty("site", out JsonElement site); //分开部署,就不需要,一站多用时,取消注释
  406. string Website = "China";
  407. var tableClient = _azureStorage.GetCloudTableClient();
  408. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  409. ////分开部署,就不需要,一站多用时,取消注释
  410. //if ($"{site}".Equals(BIConst.Global))
  411. //{
  412. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  413. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  414. // Website = BIConst.Global;
  415. //}
  416. var table = tableClient.GetTableReference("BIDDUserInfo");
  417. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "userId", $"{userId}" } });
  418. List<string> roles = new();//角色列表
  419. List<string> permissions = new();//权限列表
  420. List<DingDingUserInfo> ddUserInfos = new();
  421. var id_token = "";
  422. foreach (var itemUser in tempUser)
  423. {
  424. if (!string.IsNullOrEmpty($"{itemUser.tmdId}") && !string.IsNullOrEmpty($"{itemUser.tmdName}"))
  425. {
  426. //roles = new List<string>(itemUser.roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
  427. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  428. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  429. ddUserInfos.Add(itemUser);
  430. }
  431. else
  432. {
  433. var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{moile}" } }, _option.Location, _configuration);
  434. if (coreUser != null && coreUser.id != null)
  435. {
  436. itemUser.tmdId = coreUser.id;
  437. itemUser.tmdName = coreUser.name;
  438. itemUser.tmdMobile = coreUser.mobile;
  439. itemUser.picture = coreUser.mobile;
  440. itemUser.mail = coreUser.mail;
  441. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  442. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  443. ddUserInfos.Add(itemUser);
  444. 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);
  445. }
  446. else return Ok(new { state = 400, message = "该手机没有注册醍摩豆账号信息" });
  447. }
  448. //自己写的
  449. 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());
  450. }
  451. await table.SaveOrUpdateAll<DingDingUserInfo>(ddUserInfos);
  452. string osblob_uri = null, osblob_sas = null;
  453. if (Website.Equals(BIConst.Global))
  454. {
  455. (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete, BIConst.Global);
  456. }
  457. else
  458. {
  459. (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
  460. }
  461. //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);
  462. return Ok(new { state = 200, ddUserInfos, id_token, roles, permissions, osblob_uri, osblob_sas });
  463. }
  464. catch (Exception ex)
  465. {
  466. await _dingDing.SendBotMsg($"BI,{_option.Location} /common/login/get-ddinfo \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
  467. return BadRequest();
  468. }
  469. }
  470. /// <summary>
  471. /// 登录 第三方用户数据在CosmosDB
  472. /// </summary>
  473. /// <param name="jsonElement"></param>
  474. /// <returns></returns>
  475. [ProducesDefaultResponseType]
  476. [HttpPost("get-bizuser")]
  477. public async Task<IActionResult> GetBizUserLogin(JsonElement jsonElement)
  478. {
  479. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  480. jsonElement.TryGetProperty("mail", out JsonElement mail);
  481. if (!jsonElement.TryGetProperty("pwd", out JsonElement password)) return BadRequest();
  482. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  483. var cosmosClient = _azureCosmos.GetCosmosClient();
  484. var tableClient = _azureStorage.GetCloudTableClient();
  485. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  486. ////分开部署,就不需要,一站多用时,取消注释
  487. //if ($"{site}".Equals(BIConst.Global))
  488. //{
  489. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  490. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  491. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  492. //}
  493. string loginSql = null;
  494. if (!string.IsNullOrEmpty($"{mobile}"))
  495. loginSql = $"select value(c) from c where c.mobile ={mobile}";
  496. else if (!string.IsNullOrEmpty($"{mail}"))
  497. loginSql = $"select value(c) from c where c.mail ={mail}";
  498. else return Ok(new { state = RespondCode.ParamsError, msg = "手机号/和邮箱为空" });
  499. List<BusinessUsers> bizUsers = new();
  500. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BusinessUsers>(queryText:loginSql,requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
  501. {
  502. bizUsers.Add(item);
  503. }
  504. BusinessUsers businessUsers = new(); string openid_token = null;
  505. if (bizUsers.Count > 0)
  506. {
  507. foreach (var item in bizUsers)
  508. {
  509. var hashedPw = Utils.HashedPassword(password.ToString(), item.salt.ToString());
  510. if (hashedPw.Equals(item.pwd))
  511. {
  512. businessUsers = item;
  513. //string id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, bizUser.RowKey?.ToString(), bizUser.name?.ToString(), bizUser.picture?.ToString(), _option.JwtSecretKey, scope: "company", webSite: Website, expire: 3);
  514. openid_token = JwtAuthExtension.CreateBizLoginAuthToken(_option.HostName, businessUsers.id?.ToString(), businessUsers.name?.ToString(), businessUsers.picture?.ToString(), $"{_option.Location}-Open", _option.JwtSecretKey, expire: 3);
  515. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{businessUsers.name}【{businessUsers.id}】登录开放平台", _dingDing, tid: businessUsers.id, tname: businessUsers.name, twebsite: "Open", httpContext: HttpContext);
  516. }
  517. }
  518. }
  519. else return Ok(new { state = RespondCode.NotFound, msg = "未找到该用户!" });
  520. if (businessUsers.id != null)
  521. return Ok(new { state = RespondCode.Ok, openid_token, businessUsers });
  522. else
  523. return Ok(new { state = RespondCode.ForbiddenPwd, msg = "密码错误" });
  524. }
  525. /// <summary>
  526. /// 注册 第三方用户数据在CosmosDB
  527. /// </summary>
  528. /// <param name="jsonElement"></param>
  529. /// <returns></returns>
  530. [ProducesDefaultResponseType]
  531. [HttpPost("set-bizuser")]
  532. public async Task<IActionResult> SetBizUserLogin(JsonElement jsonElement)
  533. {
  534. jsonElement.TryGetProperty("name", out JsonElement name);
  535. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  536. jsonElement.TryGetProperty("mail", out JsonElement mail);
  537. jsonElement.TryGetProperty("pwd", out JsonElement pwd);
  538. //jsonElement.TryGetProperty("site", out JsonElement site);//分开部署,就不需要,一站多用时,取消注释
  539. var cosmosClient = _azureCosmos.GetCosmosClient();
  540. var tableClient = _azureStorage.GetCloudTableClient();
  541. var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
  542. ////分开部署,就不需要,一站多用时,取消注释
  543. //if ($"{site}".Equals(BIConst.Global))
  544. //{
  545. // cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
  546. // tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
  547. // blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
  548. //}
  549. string loginSql = null;
  550. if (!string.IsNullOrEmpty($"{mobile}"))
  551. loginSql = $"select value(c) from c where c.mobile ={mobile}";
  552. else if (!string.IsNullOrEmpty($"{mail}"))
  553. loginSql = $"select value(c) from c where c.mail ={mail}";
  554. else return Ok(new { state = RespondCode.ParamsError, msg = "手机号/和邮箱为空" });
  555. List<BizUsers> tempBizUsers = new();
  556. await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BizUsers>(queryText: loginSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
  557. {
  558. tempBizUsers.Add(item);
  559. }
  560. if (tempBizUsers.Count > 0)
  561. return Ok(new { state = RespondCode.Conflict, msg = "已存在" });
  562. else
  563. {
  564. string salt = Utils.CreatSaltString(8);
  565. BizUsers bizUsers = new()
  566. {
  567. id = Guid.NewGuid().ToString(),
  568. code = "BizUsers",
  569. name = string.IsNullOrEmpty($"{name}") ? $"{mobile}" : $"{name}",
  570. mobile = mobile.GetInt64(),
  571. salt = salt,
  572. pwd = string.IsNullOrEmpty($"{pwd}") ? Utils.HashedPassword($"{mobile}", salt) : Utils.HashedPassword($"{pwd}", salt),
  573. };
  574. bizUsers = await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<BizUsers>(bizUsers, new PartitionKey("BizUsers"));
  575. string log = $"{bizUsers.name}【{bizUsers.id}】注册第三方用户信息基础信息。";
  576. //保存操作记录
  577. await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "login-login", log, _dingDing, httpContext: HttpContext);
  578. var openid_token = JwtAuthExtension.CreateBizLoginAuthToken(_option.HostName, bizUsers.id?.ToString(), bizUsers.name?.ToString(), bizUsers.picture?.ToString(), $"{_option.Location}-Open", _option.JwtSecretKey, expire: 3);
  579. return Ok(new { state = RespondCode.Ok, openid_token, bizUsers });
  580. }
  581. }
  582. }
  583. }