LoginController.cs 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632
  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 static TEAMModelOS.SDK.Models.Teacher;
  18. using Microsoft.Extensions.Options;
  19. using TEAMModelOS.SDK.Extension;
  20. using TEAMModelOS.SDK.Models.Service;
  21. using Microsoft.AspNetCore.Authorization;
  22. using Azure.Storage.Blobs.Models;
  23. using System.IdentityModel.Tokens.Jwt;
  24. using System.Net.Http;
  25. using System.Text;
  26. using System.Net;
  27. using Newtonsoft.Json;
  28. using System.Collections;
  29. using Newtonsoft.Json.Linq;
  30. namespace TEAMModeBI.Controllers
  31. {
  32. [ProducesResponseType(StatusCodes.Status200OK)]
  33. [ProducesResponseType(StatusCodes.Status400BadRequest)]
  34. [Route("common/login")]
  35. [ApiController]
  36. public class LoginController : ControllerBase
  37. {
  38. private readonly IConfiguration _configuration;
  39. //数据容器
  40. private readonly AzureCosmosFactory _azureCosmos;
  41. //文件容器
  42. private readonly AzureStorageFactory _azureStorage;
  43. //钉钉提示信息
  44. private readonly DingDing _dingDing;
  45. private readonly Option _option;
  46. //隐式登录
  47. private readonly CoreAPIHttpService _aoreAPIHttpService;
  48. string type = "ddteammodel";
  49. public LoginController(IConfiguration configuration, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, CoreAPIHttpService aoreAPIHttpService)
  50. {
  51. _configuration = configuration;
  52. _azureCosmos = azureCosmos;
  53. _azureStorage = azureStorage;
  54. _dingDing = dingDing;
  55. _option = option?.Value;
  56. _aoreAPIHttpService = aoreAPIHttpService;
  57. }
  58. /// <summary>
  59. /// 钉钉扫描登录
  60. /// </summary>
  61. /// <param name="loginTmpCode"></param>
  62. /// <returns>Json结果</returns>
  63. [ProducesDefaultResponseType]
  64. [HttpGet("dingding")]
  65. public IActionResult DingDingLogin(string loginTmpCode)
  66. {
  67. string appKey = _configuration["DingDingAuth:appKey"];
  68. string appSecret = _configuration["DingDingAuth:appSecret"];
  69. string getuserinfo_bycode = _configuration["DingDingAuth:getuserinfo_bycode"];
  70. //判断参数是否为空
  71. if (string.IsNullOrEmpty(loginTmpCode))
  72. {
  73. return BadRequest("temp code error");
  74. }
  75. //获取access_token
  76. DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  77. OapiGettokenRequest request = new OapiGettokenRequest();
  78. request.Appkey = appKey;
  79. request.Appsecret = appSecret;
  80. request.SetHttpMethod("Get");
  81. OapiGettokenResponse response = client.Execute(request);
  82. if (response.IsError)
  83. {
  84. return BadRequest();
  85. }
  86. string access_token = response.AccessToken;
  87. //获取临时授权码 获取授权用户的个人信息
  88. DefaultDingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
  89. OapiSnsGetuserinfoBycodeRequest bycodeRequest = new OapiSnsGetuserinfoBycodeRequest()
  90. {
  91. //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
  92. TmpAuthCode = loginTmpCode
  93. };
  94. OapiSnsGetuserinfoBycodeResponse bycodeResponse = client1.Execute(bycodeRequest, appKey, appSecret);
  95. if (bycodeResponse.IsError)
  96. {
  97. return BadRequest();
  98. }
  99. //根据unionid获取userid
  100. string unionid = bycodeResponse.UserInfo.Unionid;
  101. DefaultDingTalkClient clientDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid");
  102. OapiUserGetbyunionidRequest byunionidRequest = new OapiUserGetbyunionidRequest()
  103. {
  104. Unionid = unionid
  105. };
  106. OapiUserGetbyunionidResponse byunionidResponse = clientDingTalkClient.Execute(byunionidRequest, access_token);
  107. if (byunionidResponse.IsError)
  108. {
  109. return BadRequest();
  110. }
  111. string userid = byunionidResponse.Result.Userid;
  112. //根据userId获取用户信息
  113. DefaultDingTalkClient clientDingTalkClient2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  114. OapiV2UserGetRequest getRequest = new OapiV2UserGetRequest()
  115. {
  116. Userid = userid,
  117. Language = "zh_CN"
  118. };
  119. getRequest.SetHttpMethod("Get");
  120. OapiV2UserGetResponse getResponse = clientDingTalkClient2.Execute(getRequest, access_token);
  121. if (getResponse.IsError)
  122. {
  123. return BadRequest();
  124. }
  125. return Ok(getResponse.Body);
  126. }
  127. /// <summary>
  128. /// 钉钉扫码登录
  129. /// 先获取是否在钉钉架构中
  130. /// 获取数据库是否有该人员
  131. /// </summary>
  132. /// <param name="jsonElement"></param>
  133. /// <returns>Json结果</returns>
  134. [ProducesDefaultResponseType]
  135. [HttpPost("DingLogin")]
  136. [AllowAnonymous]
  137. public async Task<IActionResult> DingLogin(JsonElement jsonElement)
  138. {
  139. //state 是前端传入的,钉钉并不会修改,比如有多种登录方式的时候,一个登录方法判断登录方式可以进行不同的处理。
  140. try
  141. {
  142. string str_appKey = _configuration["DingDingAuth:appKey"];
  143. string str_appSecret = _configuration["DingDingAuth:appSecret"];
  144. if (string.IsNullOrWhiteSpace(str_appKey) || string.IsNullOrWhiteSpace(str_appSecret))
  145. {
  146. return Ok(new { status = 0, message = "扫码登录失败" });
  147. }
  148. //自己传的code
  149. if (!jsonElement.TryGetProperty("code", out JsonElement LoginTempCode)) return BadRequest();
  150. //获取企业内部应用的accessToken
  151. DefaultDingTalkClient Iclient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  152. OapiGettokenRequest request = new OapiGettokenRequest();
  153. request.Appkey = str_appKey;
  154. request.Appsecret = str_appSecret;
  155. request.SetHttpMethod("GET");
  156. OapiGettokenResponse tokenResponse = Iclient.Execute(request);
  157. if (tokenResponse.IsError)
  158. {
  159. return Ok(new { status = 0, message = "扫码登录失败" });
  160. }
  161. string access_token = tokenResponse.AccessToken;
  162. //获取临时授权码 获取授权用户的个人信息
  163. DefaultDingTalkClient clientinfo = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
  164. OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest() { TmpAuthCode = $"{LoginTempCode}" }; //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
  165. OapiSnsGetuserinfoBycodeResponse response = clientinfo.Execute(req, str_appKey, str_appSecret);
  166. if (response.IsError)
  167. {
  168. return Ok(new { status = 0, message = "扫码登录失败" });
  169. }
  170. string unionid = response.UserInfo.Unionid;
  171. IDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); //userid地址
  172. OapiUserGetbyunionidRequest byunionidRequest = new OapiUserGetbyunionidRequest() { Unionid = unionid };
  173. OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, access_token);
  174. if (byunionidResponse.IsError)
  175. {
  176. return Ok(new { status = 0, message = "扫码登录失败" });
  177. }
  178. // 根据userId获取用户信息
  179. string userid = byunionidResponse.Result.Userid;
  180. IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  181. OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
  182. {
  183. Userid = userid,
  184. Language = "zh_CN"
  185. };
  186. v2GetRequest.SetHttpMethod("POST");
  187. OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
  188. if (v2GetResponse.IsError)
  189. {
  190. return Ok(new { status = 0, message = "扫码登录失败" });
  191. }
  192. var DDbind = v2GetResponse.Result;
  193. //return Ok(new { v2GetResponse.Result ,v2GetResponse.Body});
  194. DingDingBind dingDingBind = new DingDingBind
  195. {
  196. type = type,
  197. unionid = DDbind.Unionid,
  198. userid = DDbind.Userid,
  199. name = DDbind.Name,
  200. mobile = DDbind.Mobile,
  201. title = DDbind.Title,
  202. deptIdList = DDbind.DeptIdList,
  203. jobNumber = DDbind.JobNumber
  204. };
  205. Teacher teacher = null;
  206. string sql = $"select distinct value(c) from c join A1 in c.ddbinds where A1.userid='{dingDingBind.userid}' AND A1.unionid ='{dingDingBind.unionid}'";
  207. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  208. {
  209. teacher = item;
  210. break;
  211. }
  212. if (teacher == null)
  213. {
  214. return Ok(new { status = 1, dingDingBind = $"{dingDingBind.ToJsonString()}" });
  215. }
  216. else
  217. {
  218. var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  219. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  220. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  221. var logintion = _option.Location;
  222. //隐式登录
  223. (int code, string content) = await _aoreAPIHttpService.Implicit(clientID, clientSecret, logintion, $"{url}/oauth2/implicit",
  224. new Dictionary<string, string>()
  225. {
  226. { "grant_type", "implicit" },
  227. { "client_id",clientID},
  228. { "account",teacher.id},
  229. { "nonce",Guid.NewGuid().ToString()}
  230. });
  231. TmdidImplicit implicit_token = new TmdidImplicit();
  232. if (!string.IsNullOrEmpty(content) && code == 200)
  233. {
  234. implicit_token = content.ToObject<TmdidImplicit>();
  235. var ddbind = teacher.ddbinds.Find(x => x.userid.Equals($"{dingDingBind.userid}") && x.unionid.Equals($"{dingDingBind.unionid}"));
  236. if (ddbind != null)
  237. {
  238. return Ok(new { status = 200, id_token = $"{implicit_token.id_token.ToJsonString()}", access_token = $"{implicit_token.access_token}", expires_in = $"{implicit_token.expires_in}", token_type = $"{implicit_token.token_type}" });
  239. }
  240. }
  241. return Ok(new { status = 1, dingdinginfo = dingDingBind });
  242. }
  243. }
  244. catch (Exception e)
  245. {
  246. return Ok(new { status = 1, message = "code失效" });
  247. }
  248. }
  249. /// <summary>
  250. /// 发送验证码
  251. /// </summary>
  252. /// <param name="jsonElement"></param>
  253. /// <returns></returns>
  254. [ProducesDefaultResponseType]
  255. [HttpPost("send-sms")]
  256. public async Task<IActionResult> send_sms(JsonElement jsonElement)
  257. {
  258. try
  259. {
  260. if (!jsonElement.TryGetProperty("country", out JsonElement country)) return BadRequest();
  261. if (!jsonElement.TryGetProperty("to", out JsonElement to)) return BadRequest();
  262. if (!jsonElement.TryGetProperty("lang", out JsonElement lang)) return BadRequest();
  263. if (!jsonElement.TryGetProperty("HasUser", out JsonElement HasUser)) return BadRequest();
  264. string smsurl = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  265. HttpClient httpClient = new HttpClient();
  266. var content = new StringContent(jsonElement.ToString(), Encoding.UTF8, "application/json");
  267. HttpResponseMessage responseMessage = await httpClient.PostAsync($"{smsurl}/service/sandsms/pin", content);
  268. if (responseMessage.StatusCode == HttpStatusCode.OK)
  269. {
  270. string str_json = await responseMessage.Content.ReadAsStringAsync();
  271. if (string.IsNullOrEmpty($"{str_json}"))
  272. {
  273. return Ok(new { status = 200, message = "发送成功" });
  274. }
  275. else
  276. {
  277. JsonElement json = str_json.ToObject<JsonElement>();
  278. return Ok(json);
  279. }
  280. }
  281. else
  282. {
  283. return Ok(new { status = 0, message = "发送失败!" });
  284. }
  285. }
  286. catch (Exception ex)
  287. {
  288. return Ok(new { status = 0, message = $"发送失败!{ex.Message}" });
  289. }
  290. }
  291. /// <summary>
  292. /// 验证码和手机的验证
  293. /// </summary>
  294. /// <param name="jsonElement"></param>
  295. /// <returns></returns>
  296. [ProducesDefaultResponseType]
  297. [HttpPost("verfiypin")]
  298. public async Task<IActionResult> VerifiyPIN(JsonElement jsonElement)
  299. {
  300. try
  301. {
  302. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  303. if (!jsonElement.TryGetProperty("Authorization_Pin", out JsonElement sms)) return BadRequest();
  304. string smsurl = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  305. HttpClient httpClient = new HttpClient();
  306. var temp_job = new { Authorization_Pin = sms };
  307. var content = new StringContent(temp_job.ToJsonString(), Encoding.UTF8, "application/json");
  308. HttpResponseMessage responseMessage = await httpClient.PostAsync($"{smsurl}/service/verifiy/pin", content);
  309. if (responseMessage.StatusCode == HttpStatusCode.OK)
  310. {
  311. string responseBody = await responseMessage.Content.ReadAsStringAsync();
  312. var json = responseBody.ToObject<JsonElement>();
  313. json.TryGetProperty("resule", out JsonElement jsone);
  314. if (!string.IsNullOrEmpty($"{jsone}"))
  315. {
  316. string[] mobules = $"{jsone}".Split("-");
  317. string temp_mobile = mobules.Length >= 2 ? mobules[1] : mobules[0];
  318. if (mobile.ToString().Equals(temp_mobile))
  319. {
  320. return Ok(new { status = 200, message = "手机号和验证码验证都过了" });
  321. }
  322. else
  323. {
  324. return Ok(new { status = 5, message = "手机号码不正确" });
  325. }
  326. }
  327. else
  328. {
  329. return Ok(json);
  330. }
  331. }
  332. else
  333. {
  334. return Ok(new { status = 0, message = "发送状态错误" });
  335. }
  336. }
  337. catch (Exception ex)
  338. {
  339. return Ok(new { status = 0, message = $"发送状态错误{ex.Message}" });
  340. }
  341. }
  342. /// <summary>
  343. /// 钉钉绑定醍摩豆信息
  344. /// </summary>
  345. /// <param name="ddbindparam"></param>
  346. /// <returns></returns>
  347. [ProducesDefaultResponseType]
  348. [HttpPost("bind")]
  349. [AllowAnonymous]
  350. public async Task<IActionResult> Bind(JsonElement jsonElement)
  351. {
  352. try
  353. {
  354. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  355. jsonElement.TryGetProperty("idToken", out JsonElement idToken);
  356. if (!jsonElement.TryGetProperty("param", out JsonElement param)) return BadRequest();
  357. HttpClient httpClient = new HttpClient();
  358. Teacher teacher = new Teacher();
  359. ddbinds ddbinds = param.ToObject<ddbinds>(); //将json数据转换为实体类
  360. TmdidImplicit implicit_token = new TmdidImplicit();
  361. if (!string.IsNullOrEmpty($"{mobile}"))
  362. {
  363. List<JsonElement> mbs = new List<JsonElement>() { mobile };
  364. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  365. var content = new StringContent(mbs.ToJsonString(), Encoding.UTF8, "application/json");
  366. HttpResponseMessage responseMessage = await httpClient.PostAsync(url, content);
  367. if (responseMessage.StatusCode == HttpStatusCode.OK)
  368. {
  369. string responseBody = await responseMessage.Content.ReadAsStringAsync();
  370. List<JsonElement> json_id = responseBody.ToObject<List<JsonElement>>();
  371. string temp_id = null;
  372. if (json_id.IsNotEmpty())
  373. {
  374. temp_id = json_id[0].GetProperty("id").ToString();
  375. }
  376. var client = _azureCosmos.GetCosmosClient();
  377. teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(temp_id, new PartitionKey("Base"));
  378. string sql = $"SELECT distinct value(c) FROM c join A1 in c.ddbinds where A1.userid='{ddbinds.userid}' and A1.unionid='{ddbinds.unionid}'";
  379. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sql,
  380. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  381. {
  382. teacher = item;
  383. break;
  384. }
  385. if (teacher != null)
  386. {
  387. if (teacher.id.Equals(temp_id))
  388. {
  389. var infourl = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  390. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  391. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  392. var location = _option.Location;
  393. (int code, string temp_content) = await _aoreAPIHttpService.Implicit(clientID, clientSecret, location, $"{infourl}/oauth2/implicit", new Dictionary<string, string>()
  394. {
  395. { "grant_type", "implicit" },
  396. { "client_id",clientID },
  397. { "account",teacher.id },
  398. { "nonce",Guid.NewGuid().ToString()}
  399. });
  400. if (!string.IsNullOrEmpty(temp_content) && code == 200)
  401. {
  402. implicit_token = temp_content.ToObject<TmdidImplicit>();
  403. var ddbind = teacher.ddbinds.Find(x => x.userid.Equals($"{ddbinds.userid}") && x.unionid.Equals($"{ddbinds.unionid}"));
  404. if (ddbind == null)
  405. {
  406. teacher.ddbinds = new List<DingDingBind> { new DingDingBind { type = $"{type}", unionid = $"{ddbinds.unionid}", userid = $"{ddbinds.userid}", name = $"{ddbinds.name}", mobile = $"{ddbinds.mobile}", title = $"{ddbinds.title}", deptIdList = ddbinds.DeptIdList, jobNumber = $"{ddbinds.jobNumber}" } };
  407. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
  408. }
  409. }
  410. else
  411. {
  412. if (teacher.ddbinds.IsNotEmpty())
  413. {
  414. teacher.ddbinds.RemoveAll(x => x.userid.Equals(ddbinds.userid) && x.unionid.Equals(ddbinds.unionid));
  415. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
  416. }
  417. return Ok(new { status = 1, message = "绑定失败" });
  418. }
  419. }
  420. else
  421. {
  422. return Ok(new
  423. {
  424. location = _option.Location,
  425. //账号已被别的醍摩豆id绑定
  426. status = 2,
  427. tmdid = teacher.id,
  428. name = teacher.name,
  429. ddid = ddbinds.userid,
  430. ddname = ddbinds.name
  431. });
  432. }
  433. }
  434. else
  435. {
  436. teacher = new Teacher
  437. {
  438. id = temp_id,
  439. pk = "Base",
  440. code = "Base",
  441. name = temp_id,
  442. //创建账号并第一次登录IES5则默认赠送1G
  443. size = 1,
  444. defaultSchool = null,
  445. schools = new List<Teacher.TeacherSchool>(),
  446. ddbinds = new List<DingDingBind> { new DingDingBind { type = $"{type}", unionid = $"{ddbinds.unionid}", userid = $"{ddbinds.userid}", name = $"{ddbinds.name}", mobile = $"{ddbinds.mobile}", title = $"{ddbinds.title}", deptIdList = ddbinds.DeptIdList, jobNumber = $"{ddbinds.jobNumber}" } }
  447. };
  448. var container = _azureStorage.GetBlobContainerClient(temp_id);
  449. await container.CreateIfNotExistsAsync(PublicAccessType.None); //尝试创建Teacher私有容器,如存在则不做任何事,保障容器一定存在
  450. teacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  451. }
  452. }
  453. else
  454. {
  455. return Ok(new { status = 3, message = "通过手机号查询用户信息异常" });
  456. }
  457. }
  458. if (!string.IsNullOrEmpty($"{idToken}"))
  459. {
  460. var jwt = new JwtSecurityToken($"{idToken}");
  461. if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
  462. var id = jwt.Payload.Sub;
  463. jwt.Payload.TryGetValue("name", out object name);
  464. jwt.Payload.TryGetValue("picture", out object picture);
  465. //检查是否有绑定信息
  466. var client = _azureCosmos.GetCosmosClient();
  467. teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
  468. string sql = $"select distinct value(c) from c join A1 in c.ddbinds where A1.userid='{ddbinds.userid}' AND A1.unionid ='{ddbinds.unionid}'";
  469. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sql,
  470. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  471. {
  472. teacher = item;
  473. break;
  474. }
  475. if (teacher != null)
  476. {
  477. if (teacher.id.Equals(id))
  478. {
  479. var ddbind = teacher.ddbinds.Find(x => x.userid.Equals($"{ddbinds.userid}") && x.unionid.Equals($"{ddbinds.unionid}"));
  480. if (ddbind == null)
  481. {
  482. teacher.ddbinds = new List<DingDingBind> { new DingDingBind { type = $"{type}", unionid = $"{ddbind.unionid}", userid = $"{ddbind.userid}", name = $"{ddbind.name}", mobile = $"{ddbind.mobile}", title = $"{ddbind.title}", deptIdList = ddbind.deptIdList, jobNumber = $"{ddbind.jobNumber}" } };
  483. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
  484. }
  485. return Ok(new
  486. {
  487. status = 200,
  488. idToken = idToken,
  489. teacher = teacher,
  490. location = _option.Location,
  491. });
  492. }
  493. else
  494. {
  495. return Ok(new
  496. {
  497. location = _option.Location,
  498. //账号已被别的醍摩豆id绑定
  499. status = 2,
  500. tmdid = teacher.id,
  501. name = teacher.name,
  502. userid = ddbinds.userid,
  503. ddname = ddbinds.name
  504. });
  505. }
  506. }
  507. else
  508. {
  509. teacher = new Teacher
  510. {
  511. id = id,
  512. pk = "Base",
  513. code = "Base",
  514. name = name?.ToString(),
  515. picture = picture?.ToString(),
  516. //创建账号并第一次登录IES5则默认赠送1G
  517. size = 1,
  518. defaultSchool = null,
  519. schools = new List<Teacher.TeacherSchool>(),
  520. ddbinds = new List<DingDingBind> { new DingDingBind { type = $"{type}", unionid = $"{ddbinds.unionid}", userid = $"{ddbinds.userid}", name = $"{ddbinds.name}", mobile = $"{ddbinds.mobile}", title = $"{ddbinds.title}", deptIdList = ddbinds.DeptIdList, jobNumber = $"{ddbinds.jobNumber}" } },
  521. };
  522. var container = _azureStorage.GetBlobContainerClient(id);
  523. await container.CreateIfNotExistsAsync(PublicAccessType.None); //尝试创建Teacher私有容器,如存在则不做任何事,保障容器一定存在
  524. teacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  525. return Ok(new
  526. {
  527. status = 200,
  528. idToken = id,
  529. teacher = teacher,
  530. location = _option.Location,
  531. });
  532. }
  533. }
  534. string temp_idToken = string.IsNullOrEmpty($"{idToken}") ? implicit_token.id_token : idToken.ToString();
  535. return Ok(new
  536. {
  537. status = 200,
  538. idToken = temp_idToken,
  539. teacher = teacher,
  540. location = _option.Location,
  541. });
  542. }
  543. catch (Exception)
  544. {
  545. return Ok(new
  546. {
  547. status = 1,
  548. location = _option.Location
  549. });
  550. }
  551. }
  552. public record ddbinds
  553. {
  554. public string type { get; set; }
  555. /// <summary>
  556. /// 钉钉unionid
  557. /// </summary>
  558. public string unionid { get; set; }
  559. /// <summary>
  560. /// 钉钉ID
  561. /// </summary>
  562. public string userid { get; set; }
  563. /// <summary>
  564. /// 钉钉用户名
  565. /// </summary>
  566. public string name { get; set; }
  567. /// <summary>
  568. /// 手机号
  569. /// </summary>
  570. public string mobile { get; set; }
  571. /// <summary>
  572. /// 钉钉职位名称
  573. /// </summary>
  574. public string title { get; set; }
  575. /// <summary>
  576. /// 所属部门id列表
  577. /// </summary>
  578. public List<long> DeptIdList { get; set; }
  579. /// <summary>
  580. /// 员工工号
  581. /// </summary>
  582. public string jobNumber { get; set; }
  583. }
  584. public record TmdidImplicit
  585. {
  586. public string id_token { get; set; }
  587. public string access_token { get; set; }
  588. public string expires_in { get; set; }
  589. public string token_type { get; set; }
  590. }
  591. }
  592. }