LoginController.cs 30 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611
  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:clientID");
  220. var clientSecret = _configuration.GetValue<string>("HaBookAuth: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.ToJsonString()}" });
  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. if (!jsonElement.TryGetProperty("country", out JsonElement country)) return BadRequest();
  259. if (!jsonElement.TryGetProperty("to", out JsonElement to)) return BadRequest();
  260. if (!jsonElement.TryGetProperty("lang", out JsonElement lang)) return BadRequest();
  261. if (!jsonElement.TryGetProperty("HasUser", out JsonElement HasUser)) return BadRequest();
  262. string smsurl = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  263. HttpClient httpClient = new HttpClient();
  264. var content = new StringContent(jsonElement.ToString(), Encoding.UTF8, "application/json");
  265. HttpResponseMessage responseMessage = await httpClient.PostAsync($"{smsurl}/service/sandsms/pin", content);
  266. if (responseMessage.StatusCode == HttpStatusCode.OK)
  267. {
  268. string str_json = await responseMessage.Content.ReadAsStringAsync();
  269. if (string.IsNullOrEmpty($"{str_json}"))
  270. {
  271. return Ok(new { status =200, message="发送成功" });
  272. }
  273. else {
  274. JsonElement json = str_json.ToObject<JsonElement>();
  275. return Ok( json );
  276. }
  277. }
  278. else
  279. {
  280. return Ok(new { status = 0 , message="发送失败!" });
  281. }
  282. }
  283. /// <summary>
  284. /// 验证码和手机的验证
  285. /// </summary>
  286. /// <param name="jsonElement"></param>
  287. /// <returns></returns>
  288. [ProducesDefaultResponseType]
  289. [HttpPost("verfiypin")]
  290. public async Task<IActionResult> VerifiyPIN(JsonElement jsonElement)
  291. {
  292. if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
  293. if (!jsonElement.TryGetProperty("Authorization_Pin", out JsonElement sms)) return BadRequest();
  294. string smsurl = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  295. HttpClient httpClient = new HttpClient();
  296. var temp_job = new { Authorization_Pin = sms };
  297. var content = new StringContent(temp_job.ToJsonString(), Encoding.UTF8, "application/json");
  298. HttpResponseMessage responseMessage = await httpClient.PostAsync($"{smsurl}/service/verifiy/pin", content);
  299. if (responseMessage.StatusCode == HttpStatusCode.OK)
  300. {
  301. string responseBody = await responseMessage.Content.ReadAsStringAsync();
  302. var json = responseBody.ToObject<JsonElement>().GetProperty("resule").ToString();
  303. string[] mobules = json.Split("-");
  304. string temp_mobile = mobules.Length >= 2 ? mobules[1] : mobules[0];
  305. if (mobile.ToString().Equals(temp_mobile))
  306. {
  307. return Ok(new { status = 200, message = "手机号和验证码验证都过了" });
  308. }
  309. else
  310. {
  311. return Ok(new { status = 1, message = "手机号码不正确" });
  312. }
  313. }
  314. else
  315. {
  316. return Ok(new { status = 0 , message = "发送状态错误"});
  317. }
  318. }
  319. /// <summary>
  320. /// 钉钉绑定醍摩豆信息
  321. /// </summary>
  322. /// <param name="ddbindparam"></param>
  323. /// <returns></returns>
  324. [ProducesDefaultResponseType]
  325. [HttpPost("bind")]
  326. [AllowAnonymous]
  327. public async Task<IActionResult> Bind(JsonElement jsonElement)
  328. {
  329. try
  330. {
  331. jsonElement.TryGetProperty("mobile", out JsonElement mobile);
  332. jsonElement.TryGetProperty("idToken", out JsonElement idToken);
  333. if (!jsonElement.TryGetProperty("param", out JsonElement param)) return BadRequest();
  334. HttpClient httpClient = new HttpClient();
  335. Teacher teacher = new Teacher();
  336. ddbinds ddbinds = param.ToObject<ddbinds>(); //将json数据转换为实体类
  337. TmdidImplicit implicit_token = new TmdidImplicit();
  338. if (!string.IsNullOrEmpty($"{mobile}"))
  339. {
  340. List<JsonElement> mbs = new List<JsonElement>() { mobile };
  341. string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
  342. var content = new StringContent(mbs.ToJsonString(), Encoding.UTF8, "application/json");
  343. HttpResponseMessage responseMessage = await httpClient.PostAsync(url, content);
  344. if (responseMessage.StatusCode == HttpStatusCode.OK)
  345. {
  346. string responseBody = await responseMessage.Content.ReadAsStringAsync();
  347. List<JsonElement> json_id = responseBody.ToObject<List<JsonElement>>();
  348. string temp_id = null;
  349. if (json_id.IsNotEmpty())
  350. {
  351. temp_id = json_id[0].GetProperty("id").ToString();
  352. }
  353. var client = _azureCosmos.GetCosmosClient();
  354. teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(temp_id, new PartitionKey("Base"));
  355. string sql = $"SELECT distinct value(c) FROM c join A1 in c.ddbinds where A1.userid='{ddbinds.userid}' and A1.unionid='{ddbinds.unionid}'";
  356. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sql,
  357. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  358. {
  359. teacher = item;
  360. break;
  361. }
  362. if (teacher != null)
  363. {
  364. if (teacher.id.Equals(temp_id))
  365. {
  366. var infourl = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
  367. var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
  368. var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
  369. var location = _option.Location;
  370. (int code, string temp_content) = await _aoreAPIHttpService.Implicit(clientID, clientSecret, location, $"{infourl}/oauth2/implicit", new Dictionary<string, string>()
  371. {
  372. { "grant_type", "implicit" },
  373. { "client_id",clientID },
  374. { "account",teacher.id },
  375. { "nonce",Guid.NewGuid().ToString()}
  376. });
  377. if (!string.IsNullOrEmpty(temp_content) && code == 200)
  378. {
  379. implicit_token = temp_content.ToObject<TmdidImplicit>();
  380. var ddbind = teacher.ddbinds.Find(x => x.userid.Equals($"{ddbinds.userid}") && x.unionid.Equals($"{ddbinds.unionid}"));
  381. if (ddbind == null)
  382. {
  383. 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}" } };
  384. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
  385. }
  386. }
  387. else
  388. {
  389. if (teacher.ddbinds.IsNotEmpty())
  390. {
  391. teacher.ddbinds.RemoveAll(x => x.userid.Equals(ddbinds.userid) && x.unionid.Equals(ddbinds.unionid));
  392. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
  393. }
  394. return Ok(new { status = 1, message = "绑定失败" });
  395. }
  396. }
  397. else
  398. {
  399. return Ok(new
  400. {
  401. location = _option.Location,
  402. //账号已被别的醍摩豆id绑定
  403. status = 2,
  404. tmdid = teacher.id,
  405. name = teacher.name,
  406. ddid = ddbinds.userid,
  407. ddname = ddbinds.name
  408. });
  409. }
  410. }
  411. else
  412. {
  413. teacher = new Teacher
  414. {
  415. id = temp_id,
  416. pk = "Base",
  417. code = "Base",
  418. name = temp_id,
  419. //创建账号并第一次登录IES5则默认赠送1G
  420. size = 1,
  421. defaultSchool = null,
  422. schools = new List<Teacher.TeacherSchool>(),
  423. 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}" } }
  424. };
  425. var container = _azureStorage.GetBlobContainerClient(temp_id);
  426. await container.CreateIfNotExistsAsync(PublicAccessType.None); //尝试创建Teacher私有容器,如存在则不做任何事,保障容器一定存在
  427. teacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  428. }
  429. }
  430. else
  431. {
  432. return Ok(new { status = 3, message = "通过手机号查询用户信息异常" });
  433. }
  434. }
  435. if (!string.IsNullOrEmpty($"{idToken}"))
  436. {
  437. var jwt = new JwtSecurityToken($"{idToken}");
  438. if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
  439. var id = jwt.Payload.Sub;
  440. jwt.Payload.TryGetValue("name", out object name);
  441. jwt.Payload.TryGetValue("picture", out object picture);
  442. //检查是否有绑定信息
  443. var client = _azureCosmos.GetCosmosClient();
  444. teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
  445. string sql = $"select distinct value(c) from c join A1 in c.ddbinds where A1.userid='{ddbinds.userid}' AND A1.unionid ='{ddbinds.unionid}'";
  446. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sql,
  447. requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  448. {
  449. teacher = item;
  450. break;
  451. }
  452. if (teacher != null)
  453. {
  454. if (teacher.id.Equals(id))
  455. {
  456. var ddbind = teacher.ddbinds.Find(x => x.userid.Equals($"{ddbinds.userid}") && x.unionid.Equals($"{ddbinds.unionid}"));
  457. if (ddbind == null)
  458. {
  459. 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}" } };
  460. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
  461. }
  462. return Ok(new
  463. {
  464. status = 200,
  465. idToken = idToken,
  466. teacher = teacher,
  467. location = _option.Location,
  468. });
  469. }
  470. else
  471. {
  472. return Ok(new
  473. {
  474. location = _option.Location,
  475. //账号已被别的醍摩豆id绑定
  476. status = 2,
  477. tmdid = teacher.id,
  478. name = teacher.name,
  479. userid = ddbinds.userid,
  480. ddname = ddbinds.name
  481. });
  482. }
  483. }
  484. else
  485. {
  486. teacher = new Teacher
  487. {
  488. id = id,
  489. pk = "Base",
  490. code = "Base",
  491. name = name?.ToString(),
  492. picture = picture?.ToString(),
  493. //创建账号并第一次登录IES5则默认赠送1G
  494. size = 1,
  495. defaultSchool = null,
  496. schools = new List<Teacher.TeacherSchool>(),
  497. 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}" } },
  498. };
  499. var container = _azureStorage.GetBlobContainerClient(id);
  500. await container.CreateIfNotExistsAsync(PublicAccessType.None); //尝试创建Teacher私有容器,如存在则不做任何事,保障容器一定存在
  501. teacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
  502. return Ok(new
  503. {
  504. status = 200,
  505. idToken = id,
  506. teacher = teacher,
  507. location = _option.Location,
  508. });
  509. }
  510. }
  511. string temp_idToken = string.IsNullOrEmpty($"{idToken}") ? implicit_token.id_token : idToken.ToString();
  512. return Ok(new
  513. {
  514. status = 200,
  515. idToken = temp_idToken,
  516. teacher = teacher,
  517. location = _option.Location,
  518. });
  519. }
  520. catch (Exception)
  521. {
  522. return Ok(new
  523. {
  524. status = 4,
  525. location = _option.Location
  526. });
  527. }
  528. }
  529. public record ddbinds
  530. {
  531. public string type { get; set; }
  532. /// <summary>
  533. /// 钉钉unionid
  534. /// </summary>
  535. public string unionid { get; set; }
  536. /// <summary>
  537. /// 钉钉ID
  538. /// </summary>
  539. public string userid { get; set; }
  540. /// <summary>
  541. /// 钉钉用户名
  542. /// </summary>
  543. public string name { get; set; }
  544. /// <summary>
  545. /// 手机号
  546. /// </summary>
  547. public string mobile { get; set; }
  548. /// <summary>
  549. /// 钉钉职位名称
  550. /// </summary>
  551. public string title { get; set; }
  552. /// <summary>
  553. /// 所属部门id列表
  554. /// </summary>
  555. public List<long> DeptIdList { get; set; }
  556. /// <summary>
  557. /// 员工工号
  558. /// </summary>
  559. public string jobNumber { get; set; }
  560. }
  561. public record TmdidImplicit
  562. {
  563. public string id_token { get; set; }
  564. public string access_token { get; set; }
  565. public string expires_in { get; set; }
  566. public string token_type { get; set; }
  567. }
  568. }
  569. }