LoginController.cs 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413
  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. [AuthToken(Roles = "assist")]
  196. [HttpPost("set-bind")]
  197. public async Task<IActionResult> BindUser(JsonElement jsonElement)
  198. {
  199. try
  200. {
  201. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  202. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  203. jsonElement.TryGetProperty("id_token", out JsonElement idtoken);
  204. jsonElement.TryGetProperty("mobile", out JsonElement moile);
  205. HttpClient httpClient = _http.CreateClient();
  206. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  207. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  208. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
  209. var id_token = "";
  210. var auth_token = "";
  211. List<DingDingUserInfo> ddUserInfos = new();
  212. List<string> roles = new();//角色列表
  213. List<string> permissions = new();//权限列表
  214. foreach (var itemUser in tempUser)
  215. {
  216. if (!string.IsNullOrEmpty($"{idtoken}"))
  217. {
  218. JwtSecurityToken jwt = new JwtSecurityToken($"{idtoken}");
  219. var tmdId = jwt.Payload.Sub;
  220. jwt.Payload.TryGetValue("name", out object tmdName);
  221. jwt.Payload.TryGetValue("picture", out object picture);
  222. itemUser.tmdId = tmdId;
  223. itemUser.tmdName = $"{tmdName}";
  224. itemUser.tmdMobile = itemUser.mobile;
  225. itemUser.picture = $"{picture}";
  226. }
  227. if (!string.IsNullOrEmpty($"{moile}"))
  228. {
  229. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, moile);
  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. }
  247. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  248. //保存操作记录
  249. await _azureStorage.SaveBILog("tabledd-update", $"{itemUser.tmdName}【{itemUser.tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext);
  250. auth_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);
  251. }
  252. ddUserInfos = await table.UpdateAll(ddUserInfos);
  253. //blob 访问权限
  254. 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);
  255. return Ok(new { state = 200, ddUserInfos, id_token, auth_token, roles, osblob_uri, osblob_sas });
  256. }
  257. catch (Exception ex)
  258. {
  259. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/binguser \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  260. return BadRequest();
  261. }
  262. }
  263. /// <summary>
  264. /// 获取钉钉信息详情绑定醍摩豆和钉钉信息 二合一
  265. /// </summary>
  266. /// <param name="jsonElement"></param>
  267. /// <returns></returns>
  268. [ProducesDefaultResponseType]
  269. [HttpPost("get-ddinfo")]
  270. public async Task<IActionResult> GetDingDingInfo(JsonElement jsonElement)
  271. {
  272. try
  273. {
  274. if (!jsonElement.TryGetProperty("mobile", out JsonElement moile)) return BadRequest();
  275. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  276. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  277. var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
  278. var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
  279. List<string> roles = new();//角色列表
  280. List<string> permissions = new();//权限列表
  281. List<DingDingUserInfo> ddUserInfos = new();
  282. var id_token = "";
  283. foreach (var itemUser in tempUser)
  284. {
  285. if (!string.IsNullOrEmpty($"{itemUser.tmdId}") && !string.IsNullOrEmpty($"{itemUser.tmdName}"))
  286. {
  287. //roles = new List<string>(itemUser.roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
  288. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  289. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  290. ddUserInfos.Add(itemUser);
  291. }
  292. else
  293. {
  294. HttpClient httpClient = _http.CreateClient();
  295. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  296. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, moile);
  297. if (responseMessage.StatusCode == HttpStatusCode.OK)
  298. {
  299. var temp = await responseMessage.Content.ReadAsStringAsync();
  300. if (temp.Length > 0)
  301. {
  302. List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
  303. string tmdId = null;
  304. string tmdName = null;
  305. foreach (var item in itemjson)
  306. {
  307. tmdId = item.GetProperty("id").ToString();
  308. tmdName = item.GetProperty("name").ToString();
  309. itemUser.tmdId = tmdId?.ToString();
  310. itemUser.tmdName = tmdName?.ToString();
  311. itemUser.tmdMobile = item.GetProperty("mobile").ToString();
  312. itemUser.picture = item.GetProperty("picture").ToString();
  313. itemUser.mail = item.GetProperty("mail").ToString();
  314. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  315. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  316. ddUserInfos.Add(itemUser);
  317. }
  318. ddUserInfos = await table.UpdateAll<DingDingUserInfo>(ddUserInfos);
  319. //保存操作记录
  320. await _azureStorage.SaveBILog("tabledd-update", $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext);
  321. }
  322. else return Ok(new { state = 400, message = "该手机没有注册醍摩豆账号信息" });
  323. }
  324. else return Ok(new { state = responseMessage.StatusCode });
  325. }
  326. ////在IES5 的基础上增加参数
  327. //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());
  328. //自己写的
  329. 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);
  330. }
  331. 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);
  332. return Ok(new { state = 200, ddUserInfos, id_token, roles, permissions, osblob_uri, osblob_sas });
  333. }
  334. catch (Exception ex)
  335. {
  336. await _dingDing.SendBotMsg($"BI,{_option.Location} /common/login/get-ddinfo \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  337. return BadRequest();
  338. }
  339. }
  340. public record DingDingbinds
  341. {
  342. public string type { get; set; }
  343. /// <summary>
  344. /// 所属部门id列表
  345. /// </summary>
  346. public List<long> deptIdList { get; set; }
  347. /// <summary>
  348. /// 职位名称
  349. /// </summary>
  350. public string title { get; set; }
  351. /// <summary>
  352. /// 钉钉用户名
  353. /// </summary>
  354. public string name { get; set; }
  355. /// <summary>
  356. /// 钉钉unionid
  357. /// </summary>
  358. public string unionid { get; set; }
  359. /// <summary>
  360. /// 钉钉ID
  361. /// </summary>
  362. public string userid { get; set; }
  363. }
  364. }
  365. }