123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882 |
- 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 Microsoft.Extensions.Options;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models.Service;
- using Microsoft.AspNetCore.Authorization;
- using Azure.Storage.Blobs.Models;
- using System.IdentityModel.Tokens.Jwt;
- using System.Net.Http;
- using System.Text;
- using System.Net;
- using Newtonsoft.Json;
- using System.Collections;
- using Newtonsoft.Json.Linq;
- using static TEAMModelOS.SDK.Models.Teacher;
- //using static DingTalk.Api.Response.OapiV2UserGetResponse;
- 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 _aoreAPIHttpService;
- string type = "ddteammodel";
- public LoginController(IConfiguration configuration, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, CoreAPIHttpService aoreAPIHttpService)
- {
- _configuration = configuration;
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _dingDing = dingDing;
- _option = option?.Value;
- _aoreAPIHttpService = aoreAPIHttpService;
- }
- /// <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="jsonElement"></param>
- /// <returns>Json结果</returns>
- [ProducesDefaultResponseType]
- [HttpPost("DingLogin")]
- [AllowAnonymous]
- public async Task<IActionResult> DingLogin(JsonElement jsonElement)
- {
- //state 是前端传入的,钉钉并不会修改,比如有多种登录方式的时候,一个登录方法判断登录方式可以进行不同的处理。
- try
- {
- string str_appKey = _configuration["DingDingAuth:appKey"];
- string str_appSecret = _configuration["DingDingAuth:appSecret"];
- if (string.IsNullOrWhiteSpace(str_appKey) || string.IsNullOrWhiteSpace(str_appSecret))
- {
- return Ok(new { status = 0, message = "扫码登录失败" });
- }
- //自己传的code
- if (!jsonElement.TryGetProperty("code", out JsonElement LoginTempCode)) return BadRequest();
- //获取企业内部应用的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 { status = 0, message = "扫码登录失败" });
- }
- 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 Ok(new { status = 0, message = "扫码登录失败" });
- }
- 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 Ok(new { status = 0, message = "扫码登录失败" });
- }
- // 根据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 Ok(new { status = 0, message = "扫码登录失败" });
- }
- var DDbind = v2GetResponse.Result;
- List<DeptOrderDomain> deptOrderDomain_List = new List<DeptOrderDomain>();
- if (DDbind.DeptOrderList != null)
- {
- foreach (var temp in DDbind.DeptOrderList)
- {
- DeptOrderDomain deptOrderDomain = new DeptOrderDomain();
- deptOrderDomain.deptId = temp.DeptId;
- deptOrderDomain.order = temp.Order;
- deptOrderDomain_List.Add(deptOrderDomain);
- }
- }
- List<DeptPositionDomain> deptPositionDomain_List = new List<DeptPositionDomain>();
- if (DDbind.DeptPositionList != null)
- {
- foreach (var temp in DDbind.DeptPositionList)
- {
- DeptPositionDomain deptPositionDomain = new DeptPositionDomain();
- deptPositionDomain.deptId = temp.DeptId;
- deptPositionDomain.isMain = temp.IsMain;
- deptPositionDomain.title = temp.Title;
- deptPositionDomain.workPlace = temp.WorkPlace;
- deptPositionDomain_List.Add(deptPositionDomain);
- }
- }
- List<DeptLeaderDomain> deptLeaderDomain_List = new List<DeptLeaderDomain>();
- if (DDbind.LeaderInDept != null)
- {
- foreach (var temp in DDbind.LeaderInDept)
- {
- DeptLeaderDomain deptLeaderDomain = new DeptLeaderDomain();
- deptLeaderDomain.deptId = temp.DeptId;
- deptLeaderDomain.leader = temp.Leader;
- deptLeaderDomain_List.Add(deptLeaderDomain);
- }
- }
- List<UserRoleDomain> userRoleDomain_list = new List<UserRoleDomain>();
- if (DDbind.RoleList != null)
- {
- foreach (var temp in DDbind.RoleList)
- {
- UserRoleDomain userRoleDomain = new UserRoleDomain();
- userRoleDomain.groupName = temp.GroupName;
- userRoleDomain.id = temp.Id;
- userRoleDomain.name = temp.Name;
- userRoleDomain_list.Add(userRoleDomain);
- }
- }
- UnionEmpExtDomain unionEmpExtDomain = new UnionEmpExtDomain();
- if (DDbind.UnionEmpExt != null)
- {
- unionEmpExtDomain.corpId = DDbind.UnionEmpExt.CorpId;
- List<UnionEmpMapVoDomain> unionEmpMapVoDomain_list = new List<UnionEmpMapVoDomain>();
- if (DDbind.UnionEmpExt.UnionEmpMapList != null)
- {
- foreach (var temp in DDbind.UnionEmpExt.UnionEmpMapList)
- {
- UnionEmpMapVoDomain unionEmpMapVoDomain = new UnionEmpMapVoDomain();
- unionEmpMapVoDomain.corpId = temp.CorpId;
- unionEmpMapVoDomain.userid = temp.Userid;
- unionEmpMapVoDomain_list.Add(unionEmpMapVoDomain);
- }
- }
- unionEmpExtDomain.unionEmpMapList = unionEmpMapVoDomain_list;
- unionEmpExtDomain.userid = DDbind.UnionEmpExt.Userid;
- }
- DingDingbinds dingDingBind = new DingDingbinds
- {
- type = type,
- active = DDbind.Avatar,
- admin = DDbind.Admin,
- avatar = DDbind.Avatar,
- boss = DDbind.Boss,
- deptIdList = DDbind.DeptIdList,
- deptOrderList = deptOrderDomain_List,//DDbind.DeptOrderList?.ToJsonString().ToObject<List<DeptOrderDomain>>(),
- deptPositionList = deptPositionDomain_List, //DDbind.DeptPositionList,
- jobNumber = DDbind.JobNumber,
- leaderInDept = deptLeaderDomain_List,//DDbind.LeaderInDept,
- managerUserid = DDbind.ManagerUserid,
- mobile = DDbind.Mobile,
- roleList = userRoleDomain_list,//DDbind.RoleList,
- senior = DDbind.Senior,
- title = DDbind.Title,
- unionEmpExt = unionEmpExtDomain,//DDbind.UnionEmpExt,
- name = DDbind.Name,
- unionid = DDbind.Unionid,
- userid = DDbind.Userid,
- };
- 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 { status = 1, dingDingBind = dingDingBind });
- }
- else
- {
- var url = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var logintion = _option.Location;
- //隐式登录
- (int code, string content) = await _aoreAPIHttpService.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 { status = 200, teacher = teacher, 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 { status = 1, dingdinginfo = dingDingBind });
- }
- }
- catch (Exception e)
- {
- return Ok(new { status = 1, message = "code失效" });
- }
- }
- /// <summary>
- /// 发送验证码
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("send-sms")]
- public async Task<IActionResult> send_sms(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("country", out JsonElement country)) return BadRequest();
- if (!jsonElement.TryGetProperty("to", out JsonElement to)) return BadRequest();
- if (!jsonElement.TryGetProperty("lang", out JsonElement lang)) return BadRequest();
- if (!jsonElement.TryGetProperty("HasUser", out JsonElement HasUser)) return BadRequest();
- string smsurl = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
- HttpClient httpClient = new HttpClient();
- var content = new StringContent(jsonElement.ToString(), Encoding.UTF8, "application/json");
- HttpResponseMessage responseMessage = await httpClient.PostAsync($"{smsurl}/service/sandsms/pin", content);
- if (responseMessage.StatusCode == HttpStatusCode.OK)
- {
- string str_json = await responseMessage.Content.ReadAsStringAsync();
- if (string.IsNullOrEmpty($"{str_json}"))
- {
- return Ok(new { status = 200, message = "发送成功" });
- }
- else
- {
- JsonElement json = str_json.ToObject<JsonElement>();
- return Ok(json);
- }
- }
- else
- {
- return Ok(new { status = 0, message = "发送失败!" });
- }
- }
- catch (Exception ex)
- {
- return Ok(new { status = 0, message = $"发送失败!{ex.Message}" });
- }
- }
- /// <summary>
- /// 验证码和手机的验证
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("verfiypin")]
- public async Task<IActionResult> VerifiyPIN(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
- if (!jsonElement.TryGetProperty("Authorization_Pin", out JsonElement sms)) return BadRequest();
- string smsurl = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
- HttpClient httpClient = new HttpClient();
- var temp_job = new { Authorization_Pin = sms };
- var content = new StringContent(temp_job.ToJsonString(), Encoding.UTF8, "application/json");
- HttpResponseMessage responseMessage = await httpClient.PostAsync($"{smsurl}/service/verifiy/pin", content);
- if (responseMessage.StatusCode == HttpStatusCode.OK)
- {
- string responseBody = await responseMessage.Content.ReadAsStringAsync();
- var json = responseBody.ToObject<JsonElement>();
- json.TryGetProperty("resule", out JsonElement jsone);
- if (!string.IsNullOrEmpty($"{jsone}"))
- {
- string[] mobules = $"{jsone}".Split("-");
- string temp_mobile = mobules.Length >= 2 ? mobules[1] : mobules[0];
- if (mobile.ToString().Equals(temp_mobile))
- {
- return Ok(new { status = 200, message = "手机号和验证码验证都过了" });
- }
- else
- {
- return Ok(new { status = 5, message = "手机号码不正确" });
- }
- }
- else
- {
- return Ok(json);
- }
- }
- else
- {
- return Ok(new { status = 0, message = "发送状态错误" });
- }
- }
- catch (Exception ex)
- {
- return Ok(new { status = 0, message = $"发送状态错误{ex.Message}" });
- }
- }
- /// <summary>
- /// 钉钉绑定醍摩豆信息
- /// </summary>
- /// <param name="ddbindparam"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("bind")]
- [AllowAnonymous]
- public async Task<IActionResult> Bind(JsonElement jsonElement)
- {
- try
- {
- jsonElement.TryGetProperty("mobile", out JsonElement mobile);
- jsonElement.TryGetProperty("idToken", out JsonElement idToken);
- if (!jsonElement.TryGetProperty("param", out JsonElement param)) return BadRequest();
- HttpClient httpClient = new HttpClient();
- Teacher teacher = new Teacher();
- DingDingbinds ddbinds = param.ToObject<DingDingbinds>(); //将json数据转换为实体类
- TmdidImplicit implicit_token = new TmdidImplicit();
- if (!string.IsNullOrEmpty($"{mobile}"))
- {
- List<JsonElement> mbs = new List<JsonElement>() { mobile };
- string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
- var content = new StringContent(mbs.ToJsonString(), Encoding.UTF8, "application/json");
- HttpResponseMessage responseMessage = await httpClient.PostAsync(url, content);
- if (responseMessage.StatusCode == HttpStatusCode.OK)
- {
- string responseBody = await responseMessage.Content.ReadAsStringAsync();
- List<JsonElement> json_id = responseBody.ToObject<List<JsonElement>>();
- string temp_id = null;
- if (json_id.IsNotEmpty())
- {
- temp_id = json_id[0].GetProperty("id").ToString();
- }
- var client = _azureCosmos.GetCosmosClient();
- teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(temp_id, new PartitionKey("Base"));
- string sql = $"SELECT distinct value(c) FROM c join A1 in c.ddbinds where A1.userid='{ddbinds.userid}' and A1.unionid='{ddbinds.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)
- {
- if (teacher.id.Equals(temp_id))
- {
- var infourl = _configuration.GetValue<string>("HaBookAuth:CoreAPI");
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var location = _option.Location;
- (int code, string temp_content) = await _aoreAPIHttpService.Implicit(clientID, clientSecret, location, $"{infourl}/oauth2/implicit", new Dictionary<string, string>()
- {
- { "grant_type", "implicit" },
- { "client_id",clientID },
- { "account",teacher.id },
- { "nonce",Guid.NewGuid().ToString()}
- });
- if (!string.IsNullOrEmpty(temp_content) && code == 200)
- {
- implicit_token = temp_content.ToObject<TmdidImplicit>();
- var ddbind = teacher.ddbinds.Find(x => x.userid.Equals($"{ddbinds.userid}") && x.unionid.Equals($"{ddbinds.unionid}"));
- if (ddbind == null)
- {
- teacher.ddbinds = new List<Teacher.DingDingBind> { new Teacher.DingDingBind { type = $"{type}", active = ddbinds.active, admin = ddbinds.admin, avatar = ddbinds.avatar, boss = ddbinds.boss, deptIdList = ddbinds.deptIdList, deptOrderList = ddbinds.deptOrderList, deptPositionList = ddbinds.deptPositionList, jobNumber = ddbinds.jobNumber, leaderInDept = ddbinds.leaderInDept, managerUserid = ddbinds.managerUserid, mobile = ddbinds.mobile, roleList = ddbinds.roleList, senior = ddbinds.senior, title = ddbinds.title, unionEmpExt = ddbinds.unionEmpExt, name = ddbinds.name, unionid = ddbinds.unionid, userid = ddbinds.userid } };
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
- }
- }
- else
- {
- if (teacher.ddbinds.IsNotEmpty())
- {
- teacher.ddbinds.RemoveAll(x => x.userid.Equals(ddbinds.userid) && x.unionid.Equals(ddbinds.unionid));
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
- }
- return Ok(new { status = 1, message = "绑定失败" });
- }
- }
- else
- {
- return Ok(new
- {
- location = _option.Location,
- //账号已被别的醍摩豆id绑定
- status = 2,
- tmdid = teacher.id,
- name = teacher.name,
- ddid = ddbinds.userid,
- ddname = ddbinds.name
- });
- }
- }
- else
- {
- teacher = new Teacher
- {
- id = temp_id,
- pk = "Base",
- code = "Base",
- name = temp_id,
- //创建账号并第一次登录IES5则默认赠送1G
- size = 1,
- defaultSchool = null,
- schools = new List<Teacher.TeacherSchool>(),
- ddbinds = new List<Teacher.DingDingBind> { new Teacher.DingDingBind { type = $"{type}", active = ddbinds.active, admin = ddbinds.admin, avatar = ddbinds.avatar, boss = ddbinds.boss, deptIdList = ddbinds.deptIdList, deptOrderList = ddbinds.deptOrderList, deptPositionList = ddbinds.deptPositionList, jobNumber = ddbinds.jobNumber, leaderInDept = ddbinds.leaderInDept, managerUserid = ddbinds.managerUserid, mobile = ddbinds.mobile, roleList = ddbinds.roleList, senior = ddbinds.senior, title = ddbinds.title, unionEmpExt = ddbinds.unionEmpExt, name = ddbinds.name, unionid = ddbinds.unionid, userid = ddbinds.userid } },
- };
- var container = _azureStorage.GetBlobContainerClient(temp_id);
- await container.CreateIfNotExistsAsync(PublicAccessType.None); //尝试创建Teacher私有容器,如存在则不做任何事,保障容器一定存在
- teacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
- }
- }
- else
- {
- return Ok(new { status = 3, message = "通过手机号查询用户信息异常" });
- }
- }
- if (!string.IsNullOrEmpty($"{idToken}"))
- {
- var jwt = new JwtSecurityToken($"{idToken}");
- if (!jwt.Payload.Iss.Equals("account.teammodel", StringComparison.OrdinalIgnoreCase)) return BadRequest();
- var id = jwt.Payload.Sub;
- jwt.Payload.TryGetValue("name", out object name);
- jwt.Payload.TryGetValue("picture", out object picture);
- //检查是否有绑定信息
- var client = _azureCosmos.GetCosmosClient();
- teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>(id, new PartitionKey("Base"));
- string sql = $"select distinct value(c) from c join A1 in c.ddbinds where A1.userid='{ddbinds.userid}' AND A1.unionid ='{ddbinds.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)
- {
- if (teacher.id.Equals(id))
- {
- var ddbind = teacher.ddbinds.Find(x => x.userid.Equals($"{ddbinds.userid}") && x.unionid.Equals($"{ddbinds.unionid}"));
- if (ddbind == null)
- {
- teacher.ddbinds = new List<Teacher.DingDingBind> { new Teacher.DingDingBind { type = $"{type}", active = ddbinds.active, admin = ddbinds.admin, avatar = ddbinds.avatar, boss = ddbinds.boss, deptIdList = ddbinds.deptIdList, deptOrderList = ddbinds.deptOrderList, deptPositionList = ddbinds.deptPositionList, jobNumber = ddbinds.jobNumber, leaderInDept = ddbinds.leaderInDept, managerUserid = ddbinds.managerUserid, mobile = ddbinds.mobile, roleList = ddbinds.roleList, senior = ddbinds.senior, title = ddbinds.title, unionEmpExt = ddbinds.unionEmpExt, name = ddbinds.name, unionid = ddbinds.unionid, userid = ddbinds.userid } };
- await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").ReplaceItemAsync<Teacher>(teacher, teacher.id, new PartitionKey(teacher.code));
- }
- return Ok(new
- {
- status = 200,
- idToken = idToken,
- teacher = teacher,
- location = _option.Location,
- });
- }
- else
- {
- return Ok(new
- {
- location = _option.Location,
- //账号已被别的醍摩豆id绑定
- status = 2,
- tmdid = teacher.id,
- name = teacher.name,
- userid = ddbinds.userid,
- ddname = ddbinds.name
- });
- }
- }
- else
- {
- teacher = new Teacher
- {
- id = id,
- pk = "Base",
- code = "Base",
- name = name?.ToString(),
- picture = picture?.ToString(),
- //创建账号并第一次登录IES5则默认赠送1G
- size = 1,
- defaultSchool = null,
- schools = new List<Teacher.TeacherSchool>(),
- ddbinds = new List<Teacher.DingDingBind> { new Teacher.DingDingBind { type = $"{type}", active = ddbinds.active, admin = ddbinds.admin, avatar = ddbinds.avatar, boss = ddbinds.boss, deptIdList = ddbinds.deptIdList, deptOrderList = ddbinds.deptOrderList, deptPositionList = ddbinds.deptPositionList, jobNumber = ddbinds.jobNumber, leaderInDept = ddbinds.leaderInDept, managerUserid = ddbinds.managerUserid, mobile = ddbinds.mobile, roleList = ddbinds.roleList, senior = ddbinds.senior, title = ddbinds.title, unionEmpExt = ddbinds.unionEmpExt, name = ddbinds.name, unionid = ddbinds.unionid, userid = ddbinds.userid } }
- };
- var container = _azureStorage.GetBlobContainerClient(id);
- await container.CreateIfNotExistsAsync(PublicAccessType.None); //尝试创建Teacher私有容器,如存在则不做任何事,保障容器一定存在
- teacher = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "Teacher").CreateItemAsync<Teacher>(teacher, new PartitionKey("Base"));
- return Ok(new
- {
- status = 200,
- idToken = id,
- teacher = teacher,
- location = _option.Location,
- });
- }
- }
- string temp_idToken = string.IsNullOrEmpty($"{idToken}") ? implicit_token.id_token : idToken.ToString();
- return Ok(new
- {
- status = 200,
- idToken = temp_idToken,
- teacher = teacher,
- location = _option.Location,
- });
- }
- catch (Exception)
- {
- return Ok(new
- {
- status = 1,
- location = _option.Location
- });
- }
- }
- public record DingDingbinds
- {
- public string type { get; set; }
- /// <summary>
- /// 是否激活
- /// </summary>
- public string active { get; set; }
- /// <summary>
- /// 是否管理员
- /// </summary>
- public bool admin { get; set; }
- /// <summary>
- /// 头像
- /// </summary>
- public string avatar { get; set; }
- /// <summary>
- /// 是否老板
- /// </summary>
- public bool boss { get; set; }
- /// <summary>
- /// 所属部门id列表
- /// </summary>
- public List<long> deptIdList { get; set; }
- /// <summary>
- /// 员工在对应的部门中的排序
- /// </summary>
- public List<DeptOrderDomain> deptOrderList { get; set; }
- /// <summary>
- /// 任职信息
- /// </summary>
- public List<DeptPositionDomain> deptPositionList { get; set; }
- /// <summary>
- /// 员工工号
- /// </summary>
- public string jobNumber { get; set; }
- /// <summary>
- /// 员工在对应的部门中是否领导。
- /// </summary>
- public List<DeptLeaderDomain> leaderInDept { get; set; }
- /// <summary>
- /// 主管的ID,仅限企业内部开发调用
- /// </summary>
- public string managerUserid { get; set; }
- /// <summary>
- /// 手机号
- /// </summary>
- public string mobile { get; set; }
- /// <summary>
- /// 角色列表
- /// </summary>
- public List<UserRoleDomain> roleList { get; set; }
- /// <summary>
- /// 是否高管
- /// </summary>
- public bool senior { get; set; }
- /// <summary>
- /// 职位名称
- /// </summary>
- public string title { get; set; }
- /// <summary>
- /// 关联信息
- /// </summary>
- public UnionEmpExtDomain unionEmpExt { get; set; }
- /// <summary>
- /// 钉钉用户名
- /// </summary>
- public string name { get; set; }
- /// <summary>
- /// 钉钉unionid
- /// </summary>
- public string unionid { get; set; }
- /// <summary>
- /// 钉钉ID
- /// </summary>
- public string userid { get; set; }
- }
- /// <summary>
- /// 员工在对应的部门中的排序的数据结构
- /// </summary>
- //public record DeptOrderDomain
- //{
- // /// <summary>
- // /// 部门id
- // /// </summary>
- // public long deptId { get; set; }
- // /// <summary>
- // /// 员工在部门中的排序。
- // /// </summary>
- // public long order { get; set; }
- //}
- ///// <summary>
- ///// 任职信息数据结构
- ///// </summary>
- //public record DeptPositionDomain
- //{
- // /// <summary>
- // /// 部门ID
- // /// </summary>
- // public long deptId { get; set; }
- // /// <summary>
- // /// 是否是主任职
- // /// </summary>
- // public bool isMain { get; set; }
- // /// <summary>
- // /// 部门内职位
- // /// </summary>
- // public string title { get; set; }
- // /// <summary>
- // /// 部门内工作地
- // /// </summary>
- // public string workPlace { get; set; }
- //}
- ///// <summary>
- ///// 员工在对应的部门中是否领导 数据结构
- ///// </summary>
- //public record DeptLeaderDomain
- //{
- // /// <summary>
- // /// 部门id
- // /// </summary>
- // public long deptId { get; set; }
- // /// <summary>
- // /// 是否领导
- // /// </summary>
- // public bool leader { get; set; }
- //}
- ///// <summary>
- ///// 角色列表 数据结构
- ///// </summary>
- //public record UserRoleDomain
- //{
- // /// <summary>
- // /// 角色组名称
- // /// </summary>
- // public string groupName { get; set; }
- // /// <summary>
- // /// 角色id
- // /// </summary>
- // public long id { get; set; }
- // /// <summary>
- // /// 角色名称
- // /// </summary>
- // public string name { get; set; }
- //}
- ///// <summary>
- ///// 关联信息 数据结构
- ///// </summary>
- //public record UnionEmpExtDomain
- //{
- // /// <summary>
- // /// 企业ID
- // /// </summary>
- // public string corpId { get; set; }
- // /// <summary>
- // /// 关联映射关系
- // /// </summary>
- // public List<UnionEmpMapVoDomain> unionEmpMapList { get; set; }
- // /// <summary>
- // /// 员工id
- // /// </summary>
- // public string userid { get; set; }
- //}
- ///// <summary>
- ///// 关联映射关系
- ///// </summary>
- //public record UnionEmpMapVoDomain
- //{
- // /// <summary>
- // /// 企业id
- // /// </summary>
- // public string corpId { get; set; }
- // /// <summary>
- // /// 用户id
- // /// </summary>
- // public string userid { get; set; }
- //}
- public record TmdidImplicit
- {
- public string id_token { get; set; }
- public string access_token { get; set; }
- public string expires_in { get; set; }
- public string token_type { get; set; }
- }
- }
- }
|