123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263 |
- 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;
- using Microsoft.Extensions.Options;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models.Service;
- using static TEAMModelOS.Controllers.Third.ScController;
- 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;
- //隐世登录
- private readonly CoreAPIHttpService _accountHttpService;
- string type = "ddteammodel";
- public LoginController(IConfiguration configuration, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, CoreAPIHttpService coreAPIHttpService)
- {
- _configuration = configuration;
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _dingDing = dingDing;
- _option = option?.Value;
- _accountHttpService = coreAPIHttpService;
- }
- /// <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(string LoginTempCode)
- {
- string temp_mess = null;
- //state 是前端传入的,钉钉并不会修改,比如有多种登录方式的时候,一个登录方法判断登录方式可以进行不同的处理。
- try
- {
- string str_appKey = _configuration["DingDingAuth:appKey"];
- string str_appSecret = _configuration["DingDingAuth:appSecret"];
- if (string.IsNullOrWhiteSpace(str_appKey) || string.IsNullOrWhiteSpace(str_appSecret))
- {
- return BadRequest("请先配置钉钉扫码登录信息!");
- }
- //自己传的code
- //if (!jsonElement.TryGetProperty("tempCode", out JsonElement LoginTempCode)) return BadRequest();
- string loginTempCode = 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 Ok(new { ddbinds = $"status=-1"});
- }
- string access_token = tokenResponse.AccessToken;
- //获取临时授权码 获取授权用户的个人信息
- DefaultDingTalkClient clientinfo = new DefaultDingTalkClient("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
- OapiSnsGetuserinfoBycodeRequest req = new OapiSnsGetuserinfoBycodeRequest() { TmpAuthCode = loginTempCode }; //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
- OapiSnsGetuserinfoBycodeResponse response = clientinfo.Execute(req, str_appKey, str_appSecret);
- if (response.IsError)
- {
- return BadRequest();
- }
- 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, access_token);
- 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, access_token);
- if (v2GetResponse.IsError)
- {
- return BadRequest();
- }
- var DDbind = v2GetResponse.Result;
- //return Ok(new { v2GetResponse.Result ,v2GetResponse.Body});
- DingDingBind 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,
- };
- Teacher teacher = null;
- string sql = $"select distinct value(c) from c join A1 in c.ddbinds where A1.userid='{dingDingBind.userid}' AND A1.unionid ='{dingDingBind.unionid}'";
- 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 { ddbinds = $"status=0&dingDingBind={dingDingBind.ToJsonString()}" });
- }
- else
- {
- var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
- var clientID = _configuration.GetValue<string>("HaBookAuth:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:clientSecret");
- var logintion = _option.Location;
- //隐式登录
- (int code, string content) = await _accountHttpService.Implicit(clientID, clientSecret, logintion, $"{url}/oauth2/implicit",
- new Dictionary<string, string>()
- {
- { "grant_type", "implicit" },
- { "client_id",clientID},
- { "account",teacher.id},
- { "nonce",Guid.NewGuid().ToString()}
- });
- TmdidImplicit implicit_token = new TmdidImplicit();
- if (!string.IsNullOrEmpty(content) && code == 200)
- {
- implicit_token = content.ToObject<TmdidImplicit>();
- var ddbind = teacher.ddbinds.Find(x => x.userid.Equals($"{dingDingBind.userid}") && x.unionid.Equals($"{dingDingBind.unionid}"));
- if (ddbind != null)
- {
- return Ok(new { ddbinds = $"status=200$id_token={implicit_token.id_token}&access_token={implicit_token.access_token}&expires_in={implicit_token.expires_in}&token_type={implicit_token.token_type}" });
- }
- }
- return Ok(new { ddbinds= $"status=1¶m={dingDingBind.ToJsonString()}&type={type}&bindurl=sc/bind" });
- }
- }
- catch (Exception e)
- {
- return BadRequest($"{temp_mess }{e.Message}{e.StackTrace} ");
- }
- }
-
- }
- }
|