LoginController.cs 39 KB

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