LoginController.cs 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363
  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. namespace TEAMModeBI.Controllers
  19. {
  20. //[ProducesResponseType(StatusCodes.Status200OK)]
  21. //[ProducesResponseType(StatusCodes.Status400BadRequest)]
  22. [Route("common/login")]
  23. [ApiController]
  24. public class LoginController : ControllerBase
  25. {
  26. private readonly IConfiguration _configuration;
  27. //数据容器
  28. private readonly AzureCosmosFactory _azureCosmos;
  29. //文件容器
  30. private readonly AzureStorageFactory _azureStorage;
  31. //钉钉提示信息
  32. private readonly DingDing _dingDing;
  33. private readonly Option _option;
  34. public LoginController(IConfiguration configuration, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, Option option)
  35. {
  36. _configuration = configuration;
  37. _azureCosmos = azureCosmos;
  38. _azureStorage = azureStorage;
  39. _dingDing = dingDing;
  40. _option = option;
  41. }
  42. /// <summary>
  43. /// 钉钉扫描登录
  44. /// </summary>
  45. /// <param name="loginTmpCode"></param>
  46. /// <returns>Json结果</returns>
  47. [ProducesDefaultResponseType]
  48. [HttpGet("dingding")]
  49. public IActionResult DingDingLogin(string loginTmpCode)
  50. {
  51. string appKey = _configuration["DingDingAuth:appKey"];
  52. string appSecret = _configuration["DingDingAuth:appSecret"];
  53. string getuserinfo_bycode = _configuration["DingDingAuth:getuserinfo_bycode"];
  54. //判断参数是否为空
  55. if (string.IsNullOrEmpty(loginTmpCode))
  56. {
  57. return BadRequest("temp code error");
  58. }
  59. //获取access_token
  60. DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  61. OapiGettokenRequest request = new OapiGettokenRequest();
  62. request.Appkey = appKey;
  63. request.Appsecret = appSecret;
  64. request.SetHttpMethod("Get");
  65. OapiGettokenResponse response = client.Execute(request);
  66. if (response.IsError)
  67. {
  68. return BadRequest();
  69. }
  70. string access_token = response.AccessToken;
  71. //获取临时授权码 获取授权用户的个人信息
  72. DefaultDingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
  73. OapiSnsGetuserinfoBycodeRequest bycodeRequest = new OapiSnsGetuserinfoBycodeRequest()
  74. {
  75. //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
  76. TmpAuthCode = loginTmpCode
  77. };
  78. OapiSnsGetuserinfoBycodeResponse bycodeResponse = client1.Execute(bycodeRequest, appKey, appSecret);
  79. if (bycodeResponse.IsError)
  80. {
  81. return BadRequest();
  82. }
  83. //根据unionid获取userid
  84. string unionid = bycodeResponse.UserInfo.Unionid;
  85. DefaultDingTalkClient clientDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid");
  86. OapiUserGetbyunionidRequest byunionidRequest = new OapiUserGetbyunionidRequest()
  87. {
  88. Unionid = unionid
  89. };
  90. OapiUserGetbyunionidResponse byunionidResponse = clientDingTalkClient.Execute(byunionidRequest, access_token);
  91. if (byunionidResponse.IsError)
  92. {
  93. return BadRequest();
  94. }
  95. string userid = byunionidResponse.Result.Userid;
  96. //根据userId获取用户信息
  97. DefaultDingTalkClient clientDingTalkClient2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  98. OapiV2UserGetRequest getRequest = new OapiV2UserGetRequest()
  99. {
  100. Userid = userid,
  101. Language = "zh_CN"
  102. };
  103. getRequest.SetHttpMethod("Get");
  104. OapiV2UserGetResponse getResponse = clientDingTalkClient2.Execute(getRequest, access_token);
  105. if (getResponse.IsError)
  106. {
  107. return BadRequest();
  108. }
  109. return Ok(getResponse.Body);
  110. }
  111. /// <summary>
  112. /// 钉钉扫码登录
  113. /// </summary>
  114. /// <param name="requert"></param>
  115. /// <returns>Json结果</returns>
  116. [ProducesDefaultResponseType]
  117. [HttpGet("DingLogin")]
  118. public async Task<IActionResult> DingLogin(JsonElement jsonElement)
  119. {
  120. string temp_mess = null;
  121. //state 是前端传入的,钉钉并不会修改,比如有多种登录方式的时候,一个登录方法判断登录方式可以进行不同的处理。
  122. try
  123. {
  124. string str_appKey = _configuration["DingDingAuth:appKey"];
  125. string str_appSecret = _configuration["DingDingAuth:appSecret"];
  126. string str_agentld = "1290158212";
  127. if (string.IsNullOrWhiteSpace(str_appKey) || string.IsNullOrWhiteSpace(str_appSecret))
  128. {
  129. throw new Exception("请先配置钉钉扫码登录信息!");
  130. }
  131. //自己传的code
  132. if (jsonElement.TryGetProperty("tempCode", out JsonElement LoginTempCode)) return BadRequest();
  133. string accreCode = LoginTempCode.ToString();
  134. //判断参数是否为空
  135. if (string.IsNullOrEmpty(LoginTempCode.ToString()))
  136. {
  137. return BadRequest("temp code error");
  138. }
  139. //获取企业内部应用的accessToken
  140. DefaultDingTalkClient Iclient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
  141. OapiGettokenRequest request = new OapiGettokenRequest();
  142. request.Appkey = str_appKey;
  143. request.Appsecret = str_appSecret;
  144. request.SetHttpMethod("GET");
  145. OapiGettokenResponse tokenResponse = Iclient.Execute(request);
  146. if (tokenResponse.IsError)
  147. {
  148. return BadRequest();
  149. }
  150. //temp_mess = tokenResponse.Body;
  151. //获取引用后台免登录凭证
  152. DefaultDingTalkClient NoVoucher = new DefaultDingTalkClient("https://oapi.dingtalk.com/sso/gettoken");
  153. OapiSsoGettokenRequest ssoRequest = new OapiSsoGettokenRequest();
  154. ssoRequest.Corpid = str_agentld;
  155. ssoRequest.Corpsecret = str_appSecret;
  156. ssoRequest.SetHttpMethod("GET");
  157. OapiSsoGettokenResponse ssoResponse = new OapiSsoGettokenResponse();
  158. ssoResponse = NoVoucher.Execute(ssoRequest);
  159. //temp_mess += "=====" + ssoResponse.Body;
  160. ////return Ok(tokenResponse.Body);
  161. ////自己传的code
  162. //if (!jsonElement.TryGetProperty("accreCode", out JsonElement jsaccreCode)) return BadRequest();
  163. //string accreCode = jsaccreCode.ToString();
  164. //自己获取code
  165. //string accreCode = tokenResponse.AccessToken;
  166. //temp_mess += "====="+accreCode;
  167. DefaultDingTalkClient clientinfo = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
  168. OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest() { TmpAuthCode = accreCode };
  169. //req.TmpAuthCode = code;
  170. OapiSnsGetuserinfoBycodeResponse response = clientinfo.Execute(req, str_appKey, str_appSecret);
  171. //temp_mess += "====="+ response.Body;
  172. //return Ok(temp_mess);
  173. ////return Ok(response.Body); //用户信息代检验;
  174. ////获取到response后就可以进行自己的登录业务处理了
  175. ////xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  176. if (response.IsError)
  177. {
  178. return BadRequest();
  179. }
  180. //temp_mess += response.UserInfo;
  181. //根据unionid获取userid
  182. string unionid = response.UserInfo.Unionid;
  183. IDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); //userid地址
  184. OapiUserGetbyunionidRequest byunionidRequest = new OapiUserGetbyunionidRequest() { Unionid = unionid };
  185. OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, accreCode);
  186. if (byunionidResponse.IsError)
  187. {
  188. return BadRequest();
  189. }
  190. // 根据userId获取用户信息
  191. string userid = byunionidResponse.Result.Userid;
  192. IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  193. OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
  194. {
  195. Userid = userid,
  196. Language = "zh_CN"
  197. };
  198. v2GetRequest.SetHttpMethod("POST");
  199. OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, accreCode);
  200. if (v2GetResponse.IsError)
  201. {
  202. return BadRequest();
  203. }
  204. var DDbind = v2GetResponse.Result;
  205. DingDingBind dingDingBind = new()
  206. {
  207. type = "ddteammodel",
  208. loginid = DDbind.LoginId,
  209. userid = DDbind.Userid,
  210. userName = DDbind.Name,
  211. Mobile = DDbind.Mobile,
  212. email = DDbind.Email,
  213. sourceid = new HashSet<string> { DDbind.LoginId }
  214. };
  215. Teacher teacher = null;
  216. string sql = $"select distinct value(c) c join A1 in c.ddbinds where A1.userid={dingDingBind.userid} AND A1.loginid = {dingDingBind.loginid}";
  217. await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
  218. {
  219. teacher = item;
  220. break;
  221. }
  222. if (teacher == null)
  223. {
  224. return Ok(new { status = 0, msg = "没有绑定!" , dingDingBind });
  225. }
  226. else
  227. {
  228. var ddbind = teacher.ddbinds.FindAll(x => x.userid.Equals($"{dingDingBind.userid}") && x.loginid.Equals($"{dingDingBind.loginid}"));
  229. if (ddbind != null)
  230. {
  231. return Ok(new { teacher, dingDingBind });
  232. }
  233. else
  234. {
  235. teacher.ddbinds.Add(dingDingBind);
  236. await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
  237. return Ok(new { teacher, dingDingBind });
  238. }
  239. }
  240. }
  241. catch (Exception e)
  242. {
  243. return BadRequest(temp_mess + "======" + e.Message);
  244. }
  245. }
  246. /// <summary>
  247. /// 钉钉扫码登录返回String
  248. /// </summary>
  249. /// <param name="accreCode"></param>
  250. /// <param name="state"></param>
  251. /// <returns></returns>
  252. [ProducesDefaultResponseType]
  253. [HttpGet("DLogin")]
  254. public string DLogin(string accreCode, string state)
  255. {
  256. //state 是前端传入的,钉钉并不会修改,比如有多种登录方式的时候,一个登录方法判断登录方式可以进行不同的处理。
  257. OapiSnsGetuserinfoBycodeResponse response = new OapiSnsGetuserinfoBycodeResponse();
  258. try
  259. {
  260. string qrAppId = _configuration["DingDingAuth:appKey"];
  261. string qrAppSecret = _configuration["DingDingAuth:appSecret"];
  262. if (string.IsNullOrWhiteSpace(qrAppId) || string.IsNullOrWhiteSpace(qrAppSecret))
  263. {
  264. throw new Exception("请先配置钉钉扫码登录信息!");
  265. }
  266. DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
  267. OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest();
  268. req.TmpAuthCode = accreCode;
  269. response = client.Execute(req, qrAppId, qrAppSecret);
  270. //获取到response后就可以进行自己的登录业务处理了
  271. //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
  272. if (response.IsError)
  273. {
  274. return "unionid读取失败";
  275. }
  276. //根据unionid获取userid
  277. string unionid = response.UserInfo.Unionid;
  278. IDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); //userid地址
  279. OapiUserGetbyunionidRequest byunionidRequest = new OapiUserGetbyunionidRequest() { Unionid = unionid };
  280. OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, accreCode);
  281. if (byunionidResponse.IsError)
  282. {
  283. return "userid读取失败";
  284. }
  285. // 根据userId获取用户信息
  286. string userid = byunionidResponse.Result.Userid;
  287. IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
  288. OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
  289. {
  290. Userid = userid,
  291. Language = "zh_CN"
  292. };
  293. v2GetRequest.SetHttpMethod("GET");
  294. OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, accreCode);
  295. if (v2GetResponse.IsError)
  296. {
  297. return "用户信息读取错误";
  298. }
  299. return response.Body;
  300. }
  301. catch (Exception e)
  302. {
  303. return response.Errmsg = e.Message;
  304. }
  305. }
  306. public async Task<IActionResult> TeamModeBILogin(JsonElement jsonElement)
  307. {
  308. try
  309. {
  310. if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
  311. if (!jsonElement.TryGetProperty("pw", out JsonElement pw)) return BadRequest();
  312. var client = _azureCosmos.GetCosmosClient();
  313. var response = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Base"));
  314. return Ok(new { });
  315. }
  316. catch (Exception ex)
  317. {
  318. await _dingDing.SendBotMsg($"IES5,{_option.Location},LoginController/TeamModeBILogin\n Error Message{ex.Message} Error sting:{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
  319. throw;
  320. }
  321. }
  322. }
  323. }