123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363 |
- using Azure.Cosmos;
- using DingTalk.Api;
- using DingTalk.Api.Request;
- using DingTalk.Api.Response;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Models;
- using HTEXLib.COMM.Helpers;
- using TEAMModelOS.Models;
- using static TEAMModelOS.SDK.Models.Teacher;
- namespace TEAMModeBI.Controllers
- {
- //[ProducesResponseType(StatusCodes.Status200OK)]
- //[ProducesResponseType(StatusCodes.Status400BadRequest)]
- [Route("common/login")]
- [ApiController]
- public class LoginController : ControllerBase
- {
- private readonly IConfiguration _configuration;
- //数据容器
- private readonly AzureCosmosFactory _azureCosmos;
- //文件容器
- private readonly AzureStorageFactory _azureStorage;
- //钉钉提示信息
- private readonly DingDing _dingDing;
- private readonly Option _option;
- public LoginController(IConfiguration configuration, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, Option option)
- {
- _configuration = configuration;
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _dingDing = dingDing;
- _option = option;
- }
- /// <summary>
- /// 钉钉扫描登录
- /// </summary>
- /// <param name="loginTmpCode"></param>
- /// <returns>Json结果</returns>
- [ProducesDefaultResponseType]
- [HttpGet("dingding")]
- public IActionResult DingDingLogin(string loginTmpCode)
- {
- string appKey = _configuration["DingDingAuth:appKey"];
- string appSecret = _configuration["DingDingAuth:appSecret"];
- string getuserinfo_bycode = _configuration["DingDingAuth:getuserinfo_bycode"];
- //判断参数是否为空
- if (string.IsNullOrEmpty(loginTmpCode))
- {
- return BadRequest("temp code error");
- }
- //获取access_token
- DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest request = new OapiGettokenRequest();
- request.Appkey = appKey;
- request.Appsecret = appSecret;
- request.SetHttpMethod("Get");
- OapiGettokenResponse response = client.Execute(request);
- if (response.IsError)
- {
- return BadRequest();
- }
- string access_token = response.AccessToken;
- //获取临时授权码 获取授权用户的个人信息
- DefaultDingTalkClient client1 = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
- OapiSnsGetuserinfoBycodeRequest bycodeRequest = new OapiSnsGetuserinfoBycodeRequest()
- {
- //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
- TmpAuthCode = loginTmpCode
- };
- OapiSnsGetuserinfoBycodeResponse bycodeResponse = client1.Execute(bycodeRequest, appKey, appSecret);
- if (bycodeResponse.IsError)
- {
- return BadRequest();
- }
- //根据unionid获取userid
- string unionid = bycodeResponse.UserInfo.Unionid;
- DefaultDingTalkClient clientDingTalkClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid");
- OapiUserGetbyunionidRequest byunionidRequest = new OapiUserGetbyunionidRequest()
- {
- Unionid = unionid
- };
- OapiUserGetbyunionidResponse byunionidResponse = clientDingTalkClient.Execute(byunionidRequest, access_token);
- if (byunionidResponse.IsError)
- {
- return BadRequest();
- }
- string userid = byunionidResponse.Result.Userid;
- //根据userId获取用户信息
- DefaultDingTalkClient clientDingTalkClient2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
- OapiV2UserGetRequest getRequest = new OapiV2UserGetRequest()
- {
- Userid = userid,
- Language = "zh_CN"
- };
- getRequest.SetHttpMethod("Get");
- OapiV2UserGetResponse getResponse = clientDingTalkClient2.Execute(getRequest, access_token);
- if (getResponse.IsError)
- {
- return BadRequest();
- }
- return Ok(getResponse.Body);
- }
- /// <summary>
- /// 钉钉扫码登录
- /// </summary>
- /// <param name="requert"></param>
- /// <returns>Json结果</returns>
- [ProducesDefaultResponseType]
- [HttpGet("DingLogin")]
- public async Task<IActionResult> DingLogin(JsonElement jsonElement)
- {
- string temp_mess = null;
- //state 是前端传入的,钉钉并不会修改,比如有多种登录方式的时候,一个登录方法判断登录方式可以进行不同的处理。
- try
- {
- string str_appKey = _configuration["DingDingAuth:appKey"];
- string str_appSecret = _configuration["DingDingAuth:appSecret"];
- string str_agentld = "1290158212";
- if (string.IsNullOrWhiteSpace(str_appKey) || string.IsNullOrWhiteSpace(str_appSecret))
- {
- throw new Exception("请先配置钉钉扫码登录信息!");
- }
- //自己传的code
- if (jsonElement.TryGetProperty("tempCode", out JsonElement LoginTempCode)) return BadRequest();
- string accreCode = LoginTempCode.ToString();
- //判断参数是否为空
- if (string.IsNullOrEmpty(LoginTempCode.ToString()))
- {
- return BadRequest("temp code error");
- }
- //获取企业内部应用的accessToken
- DefaultDingTalkClient Iclient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest request = new OapiGettokenRequest();
- request.Appkey = str_appKey;
- request.Appsecret = str_appSecret;
- request.SetHttpMethod("GET");
- OapiGettokenResponse tokenResponse = Iclient.Execute(request);
- if (tokenResponse.IsError)
- {
- return BadRequest();
- }
- //temp_mess = tokenResponse.Body;
- //获取引用后台免登录凭证
- DefaultDingTalkClient NoVoucher = new DefaultDingTalkClient("https://oapi.dingtalk.com/sso/gettoken");
- OapiSsoGettokenRequest ssoRequest = new OapiSsoGettokenRequest();
- ssoRequest.Corpid = str_agentld;
- ssoRequest.Corpsecret = str_appSecret;
- ssoRequest.SetHttpMethod("GET");
- OapiSsoGettokenResponse ssoResponse = new OapiSsoGettokenResponse();
- ssoResponse = NoVoucher.Execute(ssoRequest);
- //temp_mess += "=====" + ssoResponse.Body;
- ////return Ok(tokenResponse.Body);
- ////自己传的code
- //if (!jsonElement.TryGetProperty("accreCode", out JsonElement jsaccreCode)) return BadRequest();
- //string accreCode = jsaccreCode.ToString();
- //自己获取code
- //string accreCode = tokenResponse.AccessToken;
- //temp_mess += "====="+accreCode;
- DefaultDingTalkClient clientinfo = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
- OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest() { TmpAuthCode = accreCode };
- //req.TmpAuthCode = code;
- OapiSnsGetuserinfoBycodeResponse response = clientinfo.Execute(req, str_appKey, str_appSecret);
- //temp_mess += "====="+ response.Body;
- //return Ok(temp_mess);
- ////return Ok(response.Body); //用户信息代检验;
- ////获取到response后就可以进行自己的登录业务处理了
- ////xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- if (response.IsError)
- {
- return BadRequest();
- }
- //temp_mess += response.UserInfo;
- //根据unionid获取userid
- string unionid = response.UserInfo.Unionid;
- IDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); //userid地址
- OapiUserGetbyunionidRequest byunionidRequest = new OapiUserGetbyunionidRequest() { Unionid = unionid };
- OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, accreCode);
- if (byunionidResponse.IsError)
- {
- return BadRequest();
- }
- // 根据userId获取用户信息
- string userid = byunionidResponse.Result.Userid;
- IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
- OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
- {
- Userid = userid,
- Language = "zh_CN"
- };
- v2GetRequest.SetHttpMethod("POST");
- OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, accreCode);
- if (v2GetResponse.IsError)
- {
- return BadRequest();
- }
- var DDbind = v2GetResponse.Result;
- DingDingBind dingDingBind = new()
- {
- type = "ddteammodel",
- loginid = DDbind.LoginId,
- userid = DDbind.Userid,
- userName = DDbind.Name,
- Mobile = DDbind.Mobile,
- email = DDbind.Email,
- sourceid = new HashSet<string> { DDbind.LoginId }
- };
-
- Teacher teacher = null;
- string sql = $"select distinct value(c) c join A1 in c.ddbinds where A1.userid={dingDingBind.userid} AND A1.loginid = {dingDingBind.loginid}";
- await foreach (var item in _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").GetItemQueryIterator<Teacher>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey($"Base") }))
- {
- teacher = item;
- break;
- }
- if (teacher == null)
- {
- return Ok(new { status = 0, msg = "没有绑定!" , dingDingBind });
- }
- else
- {
- var ddbind = teacher.ddbinds.FindAll(x => x.userid.Equals($"{dingDingBind.userid}") && x.loginid.Equals($"{dingDingBind.loginid}"));
- if (ddbind != null)
- {
- return Ok(new { teacher, dingDingBind });
- }
- else
- {
- teacher.ddbinds.Add(dingDingBind);
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
- return Ok(new { teacher, dingDingBind });
- }
- }
- }
- catch (Exception e)
- {
- return BadRequest(temp_mess + "======" + e.Message);
- }
- }
- /// <summary>
- /// 钉钉扫码登录返回String
- /// </summary>
- /// <param name="accreCode"></param>
- /// <param name="state"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpGet("DLogin")]
- public string DLogin(string accreCode, string state)
- {
- //state 是前端传入的,钉钉并不会修改,比如有多种登录方式的时候,一个登录方法判断登录方式可以进行不同的处理。
- OapiSnsGetuserinfoBycodeResponse response = new OapiSnsGetuserinfoBycodeResponse();
- try
- {
- string qrAppId = _configuration["DingDingAuth:appKey"];
- string qrAppSecret = _configuration["DingDingAuth:appSecret"];
- if (string.IsNullOrWhiteSpace(qrAppId) || string.IsNullOrWhiteSpace(qrAppSecret))
- {
- throw new Exception("请先配置钉钉扫码登录信息!");
- }
- DefaultDingTalkClient client = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
- OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest();
- req.TmpAuthCode = accreCode;
- response = client.Execute(req, qrAppId, qrAppSecret);
- //获取到response后就可以进行自己的登录业务处理了
- //xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
- if (response.IsError)
- {
- return "unionid读取失败";
- }
- //根据unionid获取userid
- string unionid = response.UserInfo.Unionid;
- IDingTalkClient client2 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/user/getbyunionid"); //userid地址
- OapiUserGetbyunionidRequest byunionidRequest = new OapiUserGetbyunionidRequest() { Unionid = unionid };
- OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, accreCode);
- if (byunionidResponse.IsError)
- {
- return "userid读取失败";
- }
- // 根据userId获取用户信息
- string userid = byunionidResponse.Result.Userid;
- IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
- OapiV2UserGetRequest v2GetRequest = new OapiV2UserGetRequest()
- {
- Userid = userid,
- Language = "zh_CN"
- };
- v2GetRequest.SetHttpMethod("GET");
- OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, accreCode);
- if (v2GetResponse.IsError)
- {
- return "用户信息读取错误";
- }
- return response.Body;
- }
- catch (Exception e)
- {
- return response.Errmsg = e.Message;
- }
- }
- public async Task<IActionResult> TeamModeBILogin(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
- if (!jsonElement.TryGetProperty("pw", out JsonElement pw)) return BadRequest();
- var client = _azureCosmos.GetCosmosClient();
- var response = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemStreamAsync(id.GetString(), new PartitionKey($"Base"));
- return Ok(new { });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"IES5,{_option.Location},LoginController/TeamModeBILogin\n Error Message{ex.Message} Error sting:{ex.StackTrace}", GroupNames.醍摩豆服務運維群組);
- throw;
- }
- }
-
- }
- }
|