LoginController.cs 39 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720
  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. /// 先获取是否在钉钉架构中
  69. /// 获取数据库是否有该人员
  70. /// </summary>
  71. /// <param name="jsonElement"></param>
  72. /// <returns>Json结果</returns>
  73. [ProducesDefaultResponseType]
  74. [HttpPost("DingLogin")]
  75. [AllowAnonymous]
  76. public async Task<IActionResult> DingLogin(JsonElement jsonElement)
  77. {
  78. //state 是前端传入的,钉钉并不会修改,比如有多种登录方式的时候,一个登录方法判断登录方式可以进行不同的处理。
  79. try
  80. {
  81. string str_appKey = _configuration["DingDingAuth:appKey"];
  82. string str_appSecret = _configuration["DingDingAuth:appSecret"];
  83. if (string.IsNullOrWhiteSpace(str_appKey) || string.IsNullOrWhiteSpace(str_appSecret))
  84. {
  85. return Ok(new { state = 0, message = "扫码登录失败" });
  86. }
  87. //自己传的code
  88. if (!jsonElement.TryGetProperty("code", out JsonElement LoginTempCode)) return BadRequest();
  89. //获取企业内部应用的accessToken
  90. DefaultDingTalkClient Iclient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  91. OapiGettokenRequest request = new OapiGettokenRequest();
  92. request.Appkey = str_appKey;
  93. request.Appsecret = str_appSecret;
  94. request.SetHttpMethod("GET");
  95. OapiGettokenResponse tokenResponse = Iclient.Execute(request);
  96. if (tokenResponse.IsError)
  97. {
  98. return Ok(new { state = 0, message = "扫码登录失败" });
  99. }
  100. string access_token = tokenResponse.AccessToken;
  101. //获取临时授权码 获取授权用户的个人信息
  102. DefaultDingTalkClient clientinfo = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
  103. OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest() { TmpAuthCode = $"{LoginTempCode}" }; //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
  104. OapiSnsGetuserinfoBycodeResponse response = clientinfo.Execute(req, str_appKey, str_appSecret);
  105. if (response.IsError)
  106. {
  107. return Ok(new { state = 0, message = "扫码登录失败" });
  108. }
  109. string unionid = response.UserInfo.Unionid;
  110. IDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); //userid地址
  111. OapiUserGetbyunionidRequest byunionidRequest = new OapiUserGetbyunionidRequest() { Unionid = unionid };
  112. OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, access_token);
  113. if (byunionidResponse.IsError)
  114. {
  115. return Ok(new { state = 0, message = "扫码登录失败" });
  116. }
  117. // 根据userId获取用户信息
  118. string userid = byunionidResponse.Result.Userid;
  119. IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  120. OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
  121. {
  122. Userid = userid,
  123. Language = "zh_CN"
  124. };
  125. v2GetRequest.SetHttpMethod("POST");
  126. OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
  127. if (v2GetResponse.IsError)
  128. {
  129. return Ok(new { state = 0, message = "扫码登录失败" });
  130. }
  131. var DDbind = v2GetResponse.Result;
  132. DingDingbinds dingDingBind = new DingDingbinds
  133. {
  134. type = type,
  135. deptIdList = DDbind.DeptIdList,
  136. title = DDbind.Title,
  137. name = DDbind.Name,
  138. unionid = DDbind.Unionid,
  139. userid = DDbind.Userid,
  140. };
  141. Teacher teacher = null;
  142. string sql = $"select distinct value(c) from c join A1 in c.ddbinds where A1.userid='{dingDingBind.userid}' AND A1.unionid ='{dingDingBind.unionid}'";
  143. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  144. {
  145. teacher = item;
  146. break;
  147. }
  148. if (teacher == null)
  149. {
  150. return Ok(new { state = 1, dingDingBind = dingDingBind });
  151. }
  152. else
  153. {
  154. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  155. var location = _option.Location;
  156. TmdidImplicit implicit_token = await _aoreAPIHttpService.Implicit(
  157. new Dictionary<string, string>()
  158. {
  159. { "grant_type", "implicit" },
  160. { "client_id",clientID },
  161. { "account",teacher.id },
  162. { "nonce",Guid.NewGuid().ToString()}
  163. }, location, _configuration);
  164. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", "authority-bi" } };//设置只访问BI的权限
  165. List<Authority> authorityBIList = await _azureStorage.FindListByDict<Authority>(dic); //获取权限列表
  166. if (implicit_token!=null)
  167. {
  168. var ddbind = teacher.ddbinds.Find(x => x.userid.Equals($"{dingDingBind.userid}") && x.unionid.Equals($"{dingDingBind.unionid}"));
  169. if (ddbind != null)
  170. {
  171. List<string> roles = new List<string>();//角色列表
  172. List<string> permissions = new List<string>();//权限列表
  173. List<string> depts = new List<string>(); //部门id
  174. School school_base = new School();
  175. string school_code = null;
  176. if (teacher.defaultSchool != null)
  177. {
  178. var schoolRoles = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(teacher.id, new PartitionKey($"Teacher-{teacher.defaultSchool}"));
  179. if (schoolRoles.Status == 200)
  180. {
  181. using var json = await JsonDocument.ParseAsync(schoolRoles.ContentStream);
  182. if (json.RootElement.TryGetProperty("roles", out JsonElement _roles) && _roles.ValueKind != JsonValueKind.Null)
  183. {
  184. foreach (var obj in _roles.EnumerateArray())
  185. {
  186. if (obj.GetString().Equals("assist"))
  187. {
  188. roles.Add(obj.GetString());
  189. }
  190. }
  191. }
  192. if (json.RootElement.TryGetProperty("permissions", out JsonElement _permissions) && _permissions.ValueKind != JsonValueKind.Null)
  193. {
  194. foreach (var obj in _permissions.EnumerateArray())
  195. {
  196. foreach (var item in authorityBIList)
  197. {
  198. if (item.RowKey.Equals(obj.GetString()))
  199. {
  200. permissions.Add(obj.GetString());
  201. }
  202. }
  203. }
  204. }
  205. }
  206. school_base = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{teacher.defaultSchool}", new PartitionKey("Base"));
  207. //foreach (var period in school_base.period)
  208. //{
  209. // try
  210. // {
  211. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<ItemCond>($"{period.id}", new PartitionKey($"ItemCond-{teacher.defaultSchool}"));
  212. // }
  213. // catch (CosmosException)
  214. // {
  215. // ItemCond itemCond = new ItemCond
  216. // {
  217. // id = period.id,
  218. // pk = "ItemCond",
  219. // code = $"ItemCond-{teacher.defaultSchool}",
  220. // ttl = -1,
  221. // };
  222. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<ItemCond>(itemCond, new PartitionKey($"ItemCond-{teacher.defaultSchool}"));
  223. // }
  224. //}
  225. school_code = teacher.defaultSchool;
  226. }
  227. foreach (var temp in ddbind.deptIdList)
  228. {
  229. depts.Add(temp.ToString());
  230. }
  231. var auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, teacher.id,teacher.name?.ToString(),teacher.picture?.ToString(),_option.JwtSecretKey, scope: Constant.ScopeTeacher, Website: "BI", schoolID: school_code?.ToString(), standard: school_base.standard, roles:roles.ToArray(),permissions:permissions.ToArray(),ddDepts: depts.ToArray(),ddsub:ddbind.userid);
  232. return Ok(new { state = 200, auth_token = auth_token, teacher = teacher, id_token = implicit_token.id_token, access_token = implicit_token.access_token, expires_in = implicit_token.expires_in, token_type = implicit_token.token_type });
  233. }
  234. }
  235. return Ok(new { state = 1, dingdinginfo = dingDingBind });
  236. }
  237. }
  238. catch (Exception e)
  239. {
  240. return Ok(new { state = 1, message = "code失效" });
  241. }
  242. }
  243. /// <summary>
  244. /// 依据id_Ttoken获取教师信息
  245. /// </summary>
  246. /// <param name="jsonElement"></param>
  247. /// <returns></returns>
  248. [ProducesDefaultResponseType]
  249. [HttpPost("get-teacherinfo")]
  250. public async Task<IActionResult> GetTeacherInfo(JsonElement jsonElement)
  251. {
  252. try
  253. {
  254. if (!jsonElement.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
  255. var jwt = new JwtSecurityToken(id_token.GetString());
  256. //TODO 此驗證IdToken先簡單檢查,後面需向Core ID新API,驗證Token
  257. //if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
  258. var id = jwt.Payload.Sub;
  259. jwt.Payload.TryGetValue("name", out object name);
  260. jwt.Payload.TryGetValue("picture", out object picture);
  261. Teacher teacher = null;
  262. //检查是否有绑定信息
  263. var client = _azureCosmos.GetCosmosClient();
  264. teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>($"{id}", new PartitionKey("Base"));
  265. var auth_token = "";
  266. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  267. var location = _option.Location;
  268. TmdidImplicit implicit_token = await _aoreAPIHttpService.Implicit(
  269. new Dictionary<string, string>()
  270. {
  271. { "grant_type", "implicit" },
  272. { "client_id",clientID },
  273. { "account",teacher.id },
  274. { "nonce",Guid.NewGuid().ToString()}
  275. }, location, _configuration);
  276. Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", "authority-bi" } };//设置只访问BI的权限
  277. List<Authority> authorityBIList = await _azureStorage.FindListByDict<Authority>(dic); //获取权限列表
  278. List<string> roles = new List<string>();//角色列表
  279. List<string> permissions = new List<string>();//权限列表
  280. List<string> depts = new List<string>(); //部门id
  281. School school_base = new School();
  282. string school_code = null;
  283. if (implicit_token!=null)
  284. {
  285. if (teacher.defaultSchool != null)
  286. {
  287. var schoolRoles = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(teacher.id, new PartitionKey($"Teacher-{teacher.defaultSchool}"));
  288. if (schoolRoles.Status == 200)
  289. {
  290. using var json = await JsonDocument.ParseAsync(schoolRoles.ContentStream);
  291. if (json.RootElement.TryGetProperty("roles", out JsonElement _roles) && _roles.ValueKind != JsonValueKind.Null)
  292. {
  293. foreach (var obj in _roles.EnumerateArray())
  294. {
  295. //初始定义顾问的assistant 更改为assist
  296. if (obj.GetString().Equals($"assist"))
  297. {
  298. roles.Add(obj.GetString());
  299. }
  300. }
  301. }
  302. if (json.RootElement.TryGetProperty("permissions", out JsonElement _permissions) && _permissions.ValueKind != JsonValueKind.Null)
  303. {
  304. foreach (var obj in _permissions.EnumerateArray())
  305. {
  306. //限制只显示BI权限
  307. foreach (var aut in authorityBIList)
  308. {
  309. if (aut.RowKey.Equals(obj.GetString()))
  310. {
  311. permissions.Add(obj.GetString());
  312. }
  313. }
  314. }
  315. }
  316. }
  317. school_base = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{teacher.defaultSchool}", new PartitionKey("Base"));
  318. //foreach (var period in school_base.period)
  319. //{
  320. // try
  321. // {
  322. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<ItemCond>($"{period.id}", new PartitionKey($"ItemCond-{teacher.defaultSchool}"));
  323. // }
  324. // catch (CosmosException)
  325. // {
  326. // ItemCond itemCond = new ItemCond
  327. // {
  328. // id = period.id,
  329. // pk = "ItemCond",
  330. // code = $"ItemCond-{teacher.defaultSchool}",
  331. // ttl = -1,
  332. // };
  333. // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<ItemCond>(itemCond, new PartitionKey($"ItemCond-{teacher.defaultSchool}"));
  334. // }
  335. //}
  336. school_code = teacher.defaultSchool;
  337. }
  338. List<Teacher.DingDingBind> ddbinds = teacher.ddbinds;
  339. Teacher.DingDingBind ddbind = new Teacher.DingDingBind();
  340. if (teacher.ddbinds.Count > 0)
  341. {
  342. if (ddbinds != null)
  343. {
  344. foreach (var temp in ddbinds)
  345. {
  346. ddbind.userid = temp.userid;
  347. ddbind.deptIdList = temp.deptIdList;
  348. }
  349. }
  350. foreach (var temp in ddbind.deptIdList)
  351. {
  352. depts.Add(temp.ToString());
  353. }
  354. }
  355. else return Ok(new { state = 1, message = "该账户未绑定钉钉信息!请扫码绑定信息!" });
  356. auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, teacher.id, teacher.name?.ToString(), teacher.picture?.ToString(), _option.JwtSecretKey, scope: Constant.ScopeTeacher, Website: "BI", schoolID: school_code.ToString(), standard: school_base.standard, roles: roles.ToArray(), permissions: permissions.ToArray(), ddDepts: depts.ToArray(), ddsub: ddbind.userid);
  357. }
  358. var (osblob_uri, osblob_sas) = roles.Contains("area") ? _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete) : _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List);
  359. return Ok(new { state = 200, auth_token = auth_token, teacher = teacher, id_token = implicit_token.id_token, access_token = implicit_token.access_token, expires_in = implicit_token.expires_in, token_type = implicit_token.token_type, osblob_uri, osblob_sas });
  360. }
  361. catch (Exception ex)
  362. {
  363. await _dingDing.SendBotMsg($"BI,{_option.Location}, /common/login/get-teacherinfo \n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  364. return BadRequest();
  365. }
  366. }
  367. /// <summary>
  368. /// 钉钉扫码登录获取扫码信息
  369. /// </summary>
  370. /// <param name="jsonElement"></param>
  371. /// <returns></returns>
  372. [ProducesDefaultResponseType]
  373. [HttpPost("get-ddscancode")]
  374. public async Task<IActionResult> GetDingDingScanCode(JsonElement jsonElement)
  375. {
  376. try
  377. {
  378. string appKey = _configuration["DingDingAuth:appKey"];
  379. string appSecret = _configuration["DingDingAuth:appSecret"];
  380. string divide = _configuration["CustomParam:SiteScope"];
  381. if (string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appSecret))
  382. {
  383. return Ok(new { state = 0, message = "请检查配置钉钉的信息" });
  384. }
  385. //自己传的code
  386. if (!jsonElement.TryGetProperty("code", out JsonElement LoginTempCode)) return BadRequest();
  387. //获取access_token
  388. IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  389. OapiGettokenRequest tokenRequest = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
  390. tokenRequest.SetHttpMethod("Get");
  391. OapiGettokenResponse tokenRespone = tokenClient.Execute(tokenRequest);
  392. if (tokenRespone.IsError)
  393. {
  394. return BadRequest();
  395. }
  396. string access_token = tokenRespone.AccessToken;
  397. //获取临时授权码 获取授权用户的个人信息
  398. DefaultDingTalkClient clientinfo = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
  399. OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest() { TmpAuthCode = $"{LoginTempCode}" }; //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
  400. OapiSnsGetuserinfoBycodeResponse response = clientinfo.Execute(req, appKey, appSecret);
  401. if (response.Errcode.Equals(40078))
  402. {
  403. return Ok(new { state = 0, message = $"state:{response.Errcode};Err{response.Errmsg}/临时授权码过期请重新扫码" });
  404. }
  405. string unionid = response.UserInfo.Unionid;
  406. IDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); //userid地址
  407. OapiUserGetbyunionidRequest byunionidRequest = new OapiUserGetbyunionidRequest() { Unionid = unionid };
  408. OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, access_token);
  409. if (byunionidResponse.IsError|| byunionidResponse.Errcode == 60121)
  410. {
  411. return Ok(new { state = 0, message = byunionidResponse.Errmsg });
  412. }
  413. // 根据userId获取用户信息
  414. string userid = byunionidResponse.Result.Userid;
  415. IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  416. OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
  417. {
  418. Userid = userid,
  419. Language = "zh_CN"
  420. };
  421. v2GetRequest.SetHttpMethod("POST");
  422. OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
  423. if (v2GetResponse.IsError)
  424. {
  425. return Ok(new { state = 0, message = "扫码登录失败" });
  426. }
  427. List<DingDingUserInfo> ddusers = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object>() { { "RowKey", $"{v2GetResponse.Result.Userid}" }, { "unionId", $"{v2GetResponse.Result.Unionid}" } });
  428. if (ddusers.Count > 0)
  429. {
  430. List<DingDingUserInfo> ddUserInfos = new List<DingDingUserInfo>();
  431. var id_token = "";
  432. string osblob_uri = null, osblob_sas = null;
  433. List<string> roles = new();//角色列表
  434. List<string> permissions = new List<string>();//权限列表
  435. foreach (var item in ddusers)
  436. {
  437. ddUserInfos.Add(item);
  438. }
  439. foreach (var item in ddUserInfos)
  440. {
  441. if (!string.IsNullOrEmpty(item.tmdId))
  442. {
  443. roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
  444. permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
  445. ///在IES5 添加
  446. //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());
  447. //自己写的
  448. 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);
  449. (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);
  450. }
  451. else
  452. {
  453. return Ok(new { state = 201, ddUserInfos });
  454. }
  455. }
  456. return Ok(new { state = 200, ddUserInfos, id_token, roles, permissions, osblob_uri, osblob_sas });
  457. }
  458. else
  459. {
  460. DingDingUserInfo dingDingUserInfo = new DingDingUserInfo()
  461. {
  462. PartitionKey = divide,
  463. RowKey = v2GetResponse.Result.Userid,
  464. unionId = v2GetResponse.Result.Unionid,
  465. name = v2GetResponse.Result.Name,
  466. title = v2GetResponse.Result.Title,
  467. mobile = v2GetResponse.Result.Mobile,
  468. jobNumber = v2GetResponse.Result.JobNumber,
  469. pid = 0,
  470. deptId = 0,
  471. deptName = null,
  472. depts = string.Join(",", v2GetResponse.Result.DeptIdList.ToArray()),
  473. avatar = v2GetResponse.Result.Avatar,
  474. isAdmin = v2GetResponse.Result.Admin,
  475. tmdId = "",
  476. tmdName = "",
  477. tmdMobile = "",
  478. mail = "",
  479. picture = "",
  480. roles = "",
  481. permissions = "",
  482. };
  483. await _azureStorage.Save<DingDingUserInfo>(dingDingUserInfo);
  484. return Ok(new { state = 400, ddUserId = dingDingUserInfo });
  485. }
  486. }
  487. catch (Exception ex)
  488. {
  489. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/get-ddscancode \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  490. return BadRequest();
  491. }
  492. }
  493. /// <summary>
  494. /// 钉钉绑定醍摩豆
  495. /// </summary>
  496. /// <returns></returns>
  497. [ProducesDefaultResponseType]
  498. [AuthToken(Roles = "assist")]
  499. [HttpPost("binguser")]
  500. public async Task<IActionResult> BindUser(JsonElement jsonElement)
  501. {
  502. try
  503. {
  504. if (!jsonElement.TryGetProperty("mobile", out JsonElement moile)) return BadRequest();
  505. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  506. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  507. HttpClient httpClient = _http.CreateClient();
  508. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  509. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, moile);
  510. if (responseMessage.StatusCode == HttpStatusCode.OK)
  511. {
  512. var temp = await responseMessage.Content.ReadAsStringAsync();
  513. if (temp.Length > 0)
  514. {
  515. List<DingDingUserInfo> ddUserInfos = new();
  516. List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
  517. var tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
  518. foreach (var item in itemjson)
  519. {
  520. foreach (var itemUser in tempUser)
  521. {
  522. var tmdId = item.GetProperty("id").ToString();
  523. var tmdName = item.GetProperty("name").ToString();
  524. itemUser.tmdId = tmdId;
  525. itemUser.tmdName = tmdName;
  526. itemUser.tmdMobile = item.GetProperty("mobile").ToString();
  527. itemUser.picture = item.GetProperty("picture").ToString();
  528. itemUser.mail = item.GetProperty("mail").ToString();
  529. //保存操作记录
  530. await _azureStorage.SaveLog("tabledd-update", $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext);
  531. ddUserInfos.Add(itemUser);
  532. }
  533. }
  534. var dingDingUserInfos = await _azureStorage.UpdateAll<DingDingUserInfo>(ddUserInfos);
  535. return Ok(new { state = 200, ddUsers = dingDingUserInfos });
  536. }
  537. else return Ok(new { state = 400, message = "该手机没有注册提莫信息" });
  538. }
  539. else return Ok(new { state = responseMessage.StatusCode });
  540. }
  541. catch (Exception ex)
  542. {
  543. await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/binguser \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  544. return BadRequest();
  545. }
  546. }
  547. /// <summary>
  548. /// 获取钉钉信息详情绑定醍摩豆和钉钉信息 二合一
  549. /// </summary>
  550. /// <param name="jsonElement"></param>
  551. /// <returns></returns>
  552. [ProducesDefaultResponseType]
  553. [HttpPost("get-ddinfo")]
  554. public async Task<IActionResult> GetDingDingInfo(JsonElement jsonElement)
  555. {
  556. try
  557. {
  558. if (!jsonElement.TryGetProperty("mobile", out JsonElement moile)) return BadRequest();
  559. if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
  560. if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
  561. var tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
  562. List<string> roles = new();//角色列表
  563. List<string> permissions = new List<string>();//权限列表
  564. List<DingDingUserInfo> ddUserInfos = new();
  565. var id_token = "";
  566. foreach (var itemUser in tempUser)
  567. {
  568. if (!string.IsNullOrEmpty($"{itemUser.tmdId}") && !string.IsNullOrEmpty($"{itemUser.tmdName}"))
  569. {
  570. //roles = new List<string>(itemUser.roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
  571. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  572. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  573. ddUserInfos.Add(itemUser);
  574. }
  575. else
  576. {
  577. HttpClient httpClient = _http.CreateClient();
  578. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  579. HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, moile);
  580. if (responseMessage.StatusCode == HttpStatusCode.OK)
  581. {
  582. var temp = await responseMessage.Content.ReadAsStringAsync();
  583. if (temp.Length > 0)
  584. {
  585. List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
  586. string tmdId = null;
  587. string tmdName = null;
  588. foreach (var item in itemjson)
  589. {
  590. tmdId = item.GetProperty("id").ToString();
  591. tmdName = item.GetProperty("name").ToString();
  592. itemUser.tmdId = tmdId?.ToString();
  593. itemUser.tmdName = tmdName?.ToString();
  594. itemUser.tmdMobile = item.GetProperty("mobile").ToString();
  595. itemUser.picture = item.GetProperty("picture").ToString();
  596. itemUser.mail = item.GetProperty("mail").ToString();
  597. roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
  598. permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
  599. ddUserInfos.Add(itemUser);
  600. }
  601. ddUserInfos = await _azureStorage.UpdateAll<DingDingUserInfo>(ddUserInfos);
  602. //保存操作记录
  603. await _azureStorage.SaveLog("tabledd-update", $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext);
  604. }
  605. else return Ok(new { state = 400, message = "该手机没有注册醍摩豆账号信息" });
  606. }
  607. else return Ok(new { state = responseMessage.StatusCode });
  608. }
  609. ////在IES5 的基础上增加参数
  610. //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());
  611. //自己写的
  612. 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);
  613. }
  614. 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);
  615. return Ok(new { state = 200, ddUserInfos, id_token, roles, permissions, osblob_uri, osblob_sas });
  616. }
  617. catch (Exception ex)
  618. {
  619. await _dingDing.SendBotMsg($"BI,{_option.Location} /common/login/get-ddinfo \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
  620. return BadRequest();
  621. }
  622. }
  623. public record DingDingbinds
  624. {
  625. public string type { get; set; }
  626. /// <summary>
  627. /// 所属部门id列表
  628. /// </summary>
  629. public List<long> deptIdList { get; set; }
  630. /// <summary>
  631. /// 职位名称
  632. /// </summary>
  633. public string title { get; set; }
  634. /// <summary>
  635. /// 钉钉用户名
  636. /// </summary>
  637. public string name { get; set; }
  638. /// <summary>
  639. /// 钉钉unionid
  640. /// </summary>
  641. public string unionid { get; set; }
  642. /// <summary>
  643. /// 钉钉ID
  644. /// </summary>
  645. public string userid { get; set; }
  646. }
  647. }
  648. }