LoginController.cs 39 KB

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