LoginController.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420
  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 static DingTalk.Api.Response.OapiV2UserGetResponse;
  36. namespace TEAMModelBI.Controllers
  37. {
  38. [ProducesResponseType(StatusCodes.Status200OK)]
  39. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  40. [Route("common/login")]
  41. [ApiController]
  42. public class LoginController : ControllerBase
  43. {
  44. private readonly IConfiguration _configuration;
  45. //数据容器
  46. private readonly AzureCosmosFactory _azureCosmos;
  47. //文件容器
  48. private readonly AzureStorageFactory _azureStorage;
  49. //钉钉提示信息
  50. private readonly DingDing _dingDing;
  51. private readonly Option _option;
  52. //隐式登录
  53. private readonly CoreAPIHttpService _aoreAPIHttpService;
  54. private readonly IHttpClientFactory _http;
  55. string type = "ddteammodel";
  56. public LoginController(IConfiguration configuration, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, CoreAPIHttpService aoreAPIHttpService, IHttpClientFactory http)
  57. {
  58. _configuration = configuration;
  59. _azureCosmos = azureCosmos;
  60. _azureStorage = azureStorage;
  61. _dingDing = dingDing;
  62. _option = option?.Value;
  63. _aoreAPIHttpService = aoreAPIHttpService;
  64. _http = http;
  65. }
  66. /// <summary>
  67. /// 钉钉扫码登录获取扫码信息
  68. /// </summary>
  69. /// <param name="jsonElement"></param>
  70. /// <returns></returns>
  71. [ProducesDefaultResponseType]
  72. [HttpPost("get-ddscancode")]
  73. public async Task<IActionResult> GetDingDingScanCode(JsonElement jsonElement)
  74. {
  75. try
  76. {
  77. string appKey = _configuration["DingDingAuth:appKey"];
  78. string appSecret = _configuration["DingDingAuth:appSecret"];
  79. string divide = _configuration["CustomParam:SiteScope"];
  80. if (string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appSecret))
  81. {
  82. return Ok(new { state = 0, message = "请检查配置钉钉的信息" });
  83. }
  84. //自己传的code
  85. if (!jsonElement.TryGetProperty("code", out JsonElement LoginTempCode)) return BadRequest();
  86. //获取access_token
  87. IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  88. OapiGettokenRequest tokenRequest = new() { Appkey = appKey, Appsecret = appSecret };
  89. tokenRequest.SetHttpMethod("Get");
  90. OapiGettokenResponse tokenRespone = tokenClient.Execute(tokenRequest);
  91. if (tokenRespone.IsError) return BadRequest();
  92. string access_token = tokenRespone.AccessToken;
  93. //获取临时授权码 获取授权用户的个人信息
  94. DefaultDingTalkClient clientinfo = new("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
  95. OapiSnsGetuserinfoBycodeRequest req = new() { TmpAuthCode = $"{LoginTempCode}" }; //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
  96. OapiSnsGetuserinfoBycodeResponse response = clientinfo.Execute(req, appKey, appSecret);
  97. if (response.Errcode.Equals(40078))
  98. {
  99. return Ok(new { state = 0, message = $"state:{response.Errcode};Err{response.Errmsg}/临时授权码过期请重新扫码" });
  100. }
  101. string unionid = response.UserInfo.Unionid;
  102. IDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); //userid地址
  103. OapiUserGetbyunionidRequest byunionidRequest = new() { Unionid = unionid };
  104. OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, access_token);
  105. if (byunionidResponse.IsError || byunionidResponse.Errcode == 60121)
  106. {
  107. return Ok(new { state = 0, message = byunionidResponse.Errmsg });
  108. }
  109. // 根据userId获取用户信息
  110. string userid = byunionidResponse.Result.Userid;
  111. IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  112. OapiV2UserGetRequest v2GetRequest = new()
  113. {
  114. Userid = userid,
  115. Language = "zh_CN"
  116. };
  117. v2GetRequest.SetHttpMethod("POST");
  118. OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
  119. if (v2GetResponse.IsError)
  120. {
  121. return Ok(new { state = 0, message = "扫码登录失败" });
  122. }
  123. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  124. List<DingDingUserInfo> ddusers = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object>() { { "RowKey", $"{v2GetResponse.Result.Userid}" }, { "unionId", $"{v2GetResponse.Result.Unionid}" } });
  125. if (ddusers.Count > 0)
  126. {
  127. List<DingDingUserInfo> ddUserInfos = new List<DingDingUserInfo>();
  128. var id_token = "";
  129. string osblob_uri = null, osblob_sas = null;
  130. List<string> roles = new();//角色列表
  131. List<string> permissions = new List<string>();//权限列表
  132. foreach (var item in ddusers)
  133. {
  134. ddUserInfos.Add(item);
  135. }
  136. foreach (var item in ddUserInfos)
  137. {
  138. if (!string.IsNullOrEmpty(item.tmdId))
  139. {
  140. roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  141. permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
  142. ///在IES5 添加
  143. //id_token = JwtAuthExtension.CreateAuthToken(_option.HostName, item.tmdId?.ToString(), item.tmdName?.ToString(), item.picture?.ToString(), _option.JwtSecretKey, Website: "BI", scope: $"assist", roles: roles?.ToArray(), permissions: permissions?.ToArray(), ddsub: item.RowKey?.ToString());
  144. //自己写的
  145. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, item.tmdId?.ToString(), item.tmdName?.ToString(), item.picture?.ToString(), item.RowKey?.ToString(), item.name?.ToString(), item.avatar?.ToString(), _option.JwtSecretKey, scope: "assist", Website: "BI", roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
  146. (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);
  147. }
  148. else
  149. {
  150. return Ok(new { state = 201, ddUserInfos });
  151. }
  152. }
  153. return Ok(new { state = 200, ddUserInfos, id_token, roles, permissions, osblob_uri, osblob_sas });
  154. }
  155. else
  156. {
  157. DingDingUserInfo dingDingUserInfo = new()
  158. {
  159. PartitionKey = divide,
  160. RowKey = v2GetResponse.Result.Userid,
  161. unionId = v2GetResponse.Result.Unionid,
  162. name = v2GetResponse.Result.Name,
  163. title = v2GetResponse.Result.Title,
  164. mobile = v2GetResponse.Result.Mobile,
  165. jobNumber = v2GetResponse.Result.JobNumber,
  166. pid = 0,
  167. deptId = 0,
  168. deptName = null,
  169. depts = string.Join(",", v2GetResponse.Result.DeptIdList.ToArray()),
  170. avatar = v2GetResponse.Result.Avatar,
  171. isAdmin = v2GetResponse.Result.Admin,
  172. tmdId = "",
  173. tmdName = "",
  174. tmdMobile = "",
  175. mail = "",
  176. picture = "",
  177. roles = "",
  178. permissions = "",
  179. };
  180. await table.Save<DingDingUserInfo>(dingDingUserInfo);
  181. return Ok(new { state = 400, ddUserId = dingDingUserInfo });
  182. }
  183. }
  184. catch (Exception ex)
  185. {
  186. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/get-ddscancode \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  187. return BadRequest();
  188. }
  189. }
  190. /// <summary>
  191. /// 钉钉绑定醍摩豆
  192. /// </summary>
  193. /// <returns></returns>
  194. [ProducesDefaultResponseType]
  195. [HttpPost("set-bind")]
  196. public async Task<IActionResult> BindUser(JsonElement jsonElement)
  197. {
  198. try
  199. {
  200. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  201. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  202. jsonElement.TryGetProperty("id_token", out JsonElement idtoken);
  203. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  204. HttpClient httpClient = _http.CreateClient();
  205. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  206. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  207. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
  208. var id_token = "";
  209. var auth_token = "";
  210. List<DingDingUserInfo> ddUserInfos = new();
  211. List<string> roles = new();//角色列表
  212. List<string> permissions = new();//权限列表
  213. foreach (var itemUser in tempUser)
  214. {
  215. if (!string.IsNullOrEmpty($"{idtoken}"))
  216. {
  217. JwtSecurityToken jwt = new JwtSecurityToken($"{idtoken}");
  218. var tmdId = jwt.Payload.Sub;
  219. jwt.Payload.TryGetValue("name", out object tmdName);
  220. jwt.Payload.TryGetValue("picture", out object picture);
  221. itemUser.tmdId = tmdId;
  222. itemUser.tmdName = $"{tmdName}";
  223. itemUser.tmdMobile = itemUser.mobile;
  224. itemUser.picture = $"{picture}";
  225. }
  226. if (!string.IsNullOrEmpty($"{mobile}"))
  227. {
  228. List<string> mobiles = new() { $"{mobile}" };
  229. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
  230. if (responseMessage.StatusCode == HttpStatusCode.OK)
  231. {
  232. var temp = await responseMessage.Content.ReadAsStringAsync();
  233. if (temp.Length > 0)
  234. {
  235. List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
  236. foreach (var item in itemjson)
  237. {
  238. itemUser.tmdId = item.GetProperty("id").ToString();
  239. itemUser.tmdName = item.GetProperty("name").ToString();
  240. itemUser.tmdMobile = item.GetProperty("mobile").ToString();
  241. itemUser.picture = item.GetProperty("picture").ToString();
  242. itemUser.mail = item.GetProperty("mail").ToString();
  243. }
  244. }
  245. }
  246. else return Ok(new { state = 404, msg = "手机号未找到醍摩豆账户" });
  247. }
  248. if (string.IsNullOrEmpty($"{mobile}") && string.IsNullOrEmpty($"{idtoken}"))
  249. return Ok(new { state = 400, msg = "mobile、idtoken参数错误" });
  250. else
  251. {
  252. ddUserInfos.Add(itemUser);
  253. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  254. //保存操作记录
  255. await _azureStorage.SaveBILog("tabledd-update", $"{itemUser.tmdName}【{itemUser.tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext);
  256. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), itemUser.RowKey?.ToString(), itemUser.name?.ToString(), itemUser.avatar?.ToString(), _option.JwtSecretKey, scope: "assist", Website: "BI", roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
  257. }
  258. }
  259. ddUserInfos = await table.UpdateAll(ddUserInfos);
  260. //blob 访问权限
  261. 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);
  262. return Ok(new { state = 200, ddUserInfos, id_token, roles, osblob_uri, osblob_sas });
  263. }
  264. catch (Exception ex)
  265. {
  266. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/set-bind \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  267. return BadRequest();
  268. }
  269. }
  270. /// <summary>
  271. /// 获取钉钉信息详情绑定醍摩豆和钉钉信息 二合一
  272. /// </summary>
  273. /// <param name="jsonElement"></param>
  274. /// <returns></returns>
  275. [ProducesDefaultResponseType]
  276. [HttpPost("get-ddinfo")]
  277. public async Task<IActionResult> GetDingDingInfo(JsonElement jsonElement)
  278. {
  279. try
  280. {
  281. if (!jsonElement.TryGetProperty("mobile", out JsonElement moile)) return BadRequest();
  282. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  283. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  284. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  285. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
  286. List<string> roles = new();//角色列表
  287. List<string> permissions = new();//权限列表
  288. List<DingDingUserInfo> ddUserInfos = new();
  289. var id_token = "";
  290. foreach (var itemUser in tempUser)
  291. {
  292. if (!string.IsNullOrEmpty($"{itemUser.tmdId}") && !string.IsNullOrEmpty($"{itemUser.tmdName}"))
  293. {
  294. //roles = new List<string>(itemUser.roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
  295. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  296. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  297. ddUserInfos.Add(itemUser);
  298. }
  299. else
  300. {
  301. HttpClient httpClient = _http.CreateClient();
  302. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  303. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, moile);
  304. if (responseMessage.StatusCode == HttpStatusCode.OK)
  305. {
  306. var temp = await responseMessage.Content.ReadAsStringAsync();
  307. if (temp.Length > 0)
  308. {
  309. List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
  310. string tmdId = null;
  311. string tmdName = null;
  312. foreach (var item in itemjson)
  313. {
  314. tmdId = item.GetProperty("id").ToString();
  315. tmdName = item.GetProperty("name").ToString();
  316. itemUser.tmdId = tmdId?.ToString();
  317. itemUser.tmdName = tmdName?.ToString();
  318. itemUser.tmdMobile = item.GetProperty("mobile").ToString();
  319. itemUser.picture = item.GetProperty("picture").ToString();
  320. itemUser.mail = item.GetProperty("mail").ToString();
  321. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  322. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  323. ddUserInfos.Add(itemUser);
  324. }
  325. ddUserInfos = await table.UpdateAll<DingDingUserInfo>(ddUserInfos);
  326. //保存操作记录
  327. await _azureStorage.SaveBILog("tabledd-update", $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext);
  328. }
  329. else return Ok(new { state = 400, message = "该手机没有注册醍摩豆账号信息" });
  330. }
  331. else return Ok(new { state = responseMessage.StatusCode });
  332. }
  333. ////在IES5 的基础上增加参数
  334. //id_token = JwtAuthExtension.CreateAuthToken(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), _option.JwtSecretKey,Website: "BI", scope: $"assist", roles: roles?.ToArray(), permissions: permissions?.ToArray(), ddsub: itemUser.RowKey?.ToString());
  335. //自己写的
  336. id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), itemUser.RowKey?.ToString(), itemUser.name?.ToString(), itemUser.avatar?.ToString(), _option.JwtSecretKey, scope: "assist", Website: "BI", roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
  337. }
  338. 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);
  339. return Ok(new { state = 200, ddUserInfos, id_token, roles, permissions, osblob_uri, osblob_sas });
  340. }
  341. catch (Exception ex)
  342. {
  343. await _dingDing.SendBotMsg($"BI,{_option.Location} /common/login/get-ddinfo \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  344. return BadRequest();
  345. }
  346. }
  347. public record DingDingbinds
  348. {
  349. public string type { get; set; }
  350. /// <summary>
  351. /// 所属部门id列表
  352. /// </summary>
  353. public List<long> deptIdList { get; set; }
  354. /// <summary>
  355. /// 职位名称
  356. /// </summary>
  357. public string title { get; set; }
  358. /// <summary>
  359. /// 钉钉用户名
  360. /// </summary>
  361. public string name { get; set; }
  362. /// <summary>
  363. /// 钉钉unionid
  364. /// </summary>
  365. public string unionid { get; set; }
  366. /// <summary>
  367. /// 钉钉ID
  368. /// </summary>
  369. public string userid { get; set; }
  370. }
  371. }
  372. }