LoginController.cs 38 KB

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