1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117 |
- 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 TEAMModelOS.SDK.Models.Cosmos.BI;
- using Azure.Storage.Sas;
- using System.Net.Http.Json;
- //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;
- private readonly IHttpClientFactory _http;
- string type = "ddteammodel";
- public LoginController(IConfiguration configuration, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, CoreAPIHttpService aoreAPIHttpService, IHttpClientFactory http)
- {
- _configuration = configuration;
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _dingDing = dingDing;
- _option = option?.Value;
- _aoreAPIHttpService = aoreAPIHttpService;
- _http = http;
- }
- /// <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 { state = 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 { state = 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 { state = 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 { state = 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 { state = 0, message = "扫码登录失败" });
- }
- var DDbind = v2GetResponse.Result;
- DingDingbinds dingDingBind = new DingDingbinds
- {
- type = type,
- deptIdList = DDbind.DeptIdList,
- title = DDbind.Title,
- 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 { state = 1, dingDingBind = dingDingBind });
- }
- else
- {
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var location = _option.Location;
- TmdidImplicit implicit_token = await _aoreAPIHttpService.Implicit(
- new Dictionary<string, string>()
- {
- { "grant_type", "implicit" },
- { "client_id",clientID },
- { "account",teacher.id },
- { "nonce",Guid.NewGuid().ToString()}
- }, location, _configuration);
- Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", "authority-bi" } };//设置只访问BI的权限
- List<Authority> authorityBIList = await _azureStorage.FindListByDict<Authority>(dic); //获取权限列表
- if (implicit_token!=null)
- {
- var ddbind = teacher.ddbinds.Find(x => x.userid.Equals($"{dingDingBind.userid}") && x.unionid.Equals($"{dingDingBind.unionid}"));
- if (ddbind != null)
- {
- List<string> roles = new List<string>();//角色列表
- List<string> permissions = new List<string>();//权限列表
- List<string> depts = new List<string>(); //部门id
- School school_base = new School();
- string school_code = null;
- if (teacher.defaultSchool != null)
- {
- var schoolRoles = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(teacher.id, new PartitionKey($"Teacher-{teacher.defaultSchool}"));
- if (schoolRoles.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(schoolRoles.ContentStream);
- if (json.RootElement.TryGetProperty("roles", out JsonElement _roles) && _roles.ValueKind != JsonValueKind.Null)
- {
- foreach (var obj in _roles.EnumerateArray())
- {
- if (obj.GetString().Equals("assist"))
- {
- roles.Add(obj.GetString());
- }
- }
- }
- if (json.RootElement.TryGetProperty("permissions", out JsonElement _permissions) && _permissions.ValueKind != JsonValueKind.Null)
- {
- foreach (var obj in _permissions.EnumerateArray())
- {
- foreach (var item in authorityBIList)
- {
- if (item.RowKey.Equals(obj.GetString()))
- {
- permissions.Add(obj.GetString());
- }
- }
- }
- }
- }
- school_base = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{teacher.defaultSchool}", new PartitionKey("Base"));
- //foreach (var period in school_base.period)
- //{
- // try
- // {
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<ItemCond>($"{period.id}", new PartitionKey($"ItemCond-{teacher.defaultSchool}"));
- // }
- // catch (CosmosException)
- // {
- // ItemCond itemCond = new ItemCond
- // {
- // id = period.id,
- // pk = "ItemCond",
- // code = $"ItemCond-{teacher.defaultSchool}",
- // ttl = -1,
- // };
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<ItemCond>(itemCond, new PartitionKey($"ItemCond-{teacher.defaultSchool}"));
- // }
- //}
- school_code = teacher.defaultSchool;
- }
- foreach (var temp in ddbind.deptIdList)
- {
- depts.Add(temp.ToString());
- }
- var auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, teacher.id,teacher.name?.ToString(),teacher.picture?.ToString(),_option.JwtSecretKey, scope: Constant.ScopeTeacher, schoolID: school_code?.ToString(), standard: school_base.standard, roles:roles.ToArray(),permissions:permissions.ToArray(),ddDepts: depts.ToArray(),ddsub:ddbind.userid);
- return Ok(new { state = 200, auth_token = auth_token, 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 { state = 1, dingdinginfo = dingDingBind });
- }
- }
- catch (Exception e)
- {
- return Ok(new { state = 1, message = "code失效" });
- }
- }
- /// <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 = _http.CreateClient();
- Teacher teacher = new Teacher();
- DingDingbinds ddbinds = param.ToObject<DingDingbinds>(); //将json数据转换为实体类
- TmdidImplicit implicit_token = new TmdidImplicit();
- Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", "authority-bi" } };//设置只访问BI的权限
- List<Authority> authorityBIList = await _azureStorage.FindListByDict<Authority>(dic); //获取权限列表
- List<string> roles = new List<string>();//角色列表
- List<string> permissions = new List<string>();//权限列表
- List<string> depts = new List<string>(); //部门id
- School school_base = new School();
- string school_code = null;
- var auth_token = "";
- string blobOrTable = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
- OperateLog operateLog = new OperateLog();//操作记录
- operateLog.PartitionKey = "OperateLog-BI";
- operateLog.RowKey = blobOrTable;
- operateLog.recordID = blobOrTable;
- operateLog.platformSource = "BI";
- operateLog.tmdId = $"{teacher.id}";
- operateLog.tmdName = $"{teacher.name}";
- operateLog.visitApi = "common/login/bind";
- operateLog.operateTime = DateTime.Now;
- StringBuilder strBuilder = new StringBuilder();
- if (!string.IsNullOrEmpty($"{mobile}"))
- {
- List<JsonElement> mbs = new List<JsonElement>() { mobile };
- string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
- HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mbs);
- 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 clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var location = _option.Location;
- implicit_token = await _aoreAPIHttpService.Implicit(
- new Dictionary<string, string>()
- {
- { "grant_type", "implicit" },
- { "client_id",clientID },
- { "account",teacher.id },
- { "nonce",Guid.NewGuid().ToString()}
- }, location, _configuration);
- if (implicit_token!=null)
- {
- 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}", deptIdList = ddbinds.deptIdList, title = ddbinds.title, 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));
- if (teacher.defaultSchool != null)
- {
- var schoolRoles = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(teacher.id, new PartitionKey($"Teacher-{teacher.defaultSchool}"));
- if (schoolRoles.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(schoolRoles.ContentStream);
- if (json.RootElement.TryGetProperty("roles", out JsonElement _roles) && _roles.ValueKind != JsonValueKind.Null)
- {
- foreach (var obj in _roles.EnumerateArray())
- {
- //初始定义顾问的assistant 更改为assist
- if (obj.GetString().Equals($"assist"))
- {
- roles.Add(obj.GetString());
- }
- }
- }
- if (json.RootElement.TryGetProperty("permissions", out JsonElement _permissions) && _permissions.ValueKind != JsonValueKind.Null)
- {
- foreach (var obj in _permissions.EnumerateArray())
- {
- //限制只显示BI权限
- foreach (var aut in authorityBIList)
- {
- if (aut.RowKey.Equals(obj.GetString()))
- {
- permissions.Add(obj.GetString());
- }
- }
- }
- }
- }
- school_base = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{teacher.defaultSchool}", new PartitionKey("Base"));
- //foreach (var period in school_base.period)
- //{
- // try
- // {
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<ItemCond>($"{period.id}", new PartitionKey($"ItemCond-{teacher.defaultSchool}"));
- // }
- // catch (CosmosException)
- // {
- // ItemCond itemCond = new ItemCond
- // {
- // id = period.id,
- // pk = "ItemCond",
- // code = $"ItemCond-{teacher.defaultSchool}",
- // ttl = -1,
- // };
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<ItemCond>(itemCond, new PartitionKey($"ItemCond-{teacher.defaultSchool}"));
- // }
- //}
- school_code = teacher.defaultSchool;
- }
- foreach (var tempdept in ddbinds.deptIdList)
- {
- depts.Add(tempdept.ToString());
- }
- strBuilder.Append($"醍摩豆账户{teacher.id}【{teacher.name}】和钉钉账户{ddbinds.userid}【{ddbinds.name}】进行绑定,绑定成功");
- }
- }
- 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));
- }
- strBuilder.Append($"醍摩豆账户{teacher.id}【{teacher.name}】和钉钉账户{ddbinds.userid}【{ddbinds.name}】进行绑定,绑定失败");
- operateLog.operateDescribe = strBuilder.ToString();
- await _azureStorage.Save<OperateLog>(operateLog);
- return Ok(new { state = 1, message = "绑定失败" });
- }
- }
- else
- {
- operateLog.operateDescribe = $"醍摩豆账户{teacher.id}【{teacher.name}】和钉钉账户{ddbinds.userid}【{ddbinds.name}】进行绑定,账号已被别的醍摩豆id绑定";
- await _azureStorage.Save<OperateLog>(operateLog);
- return Ok(new
- {
- location = _option.Location,
- //账号已被别的醍摩豆id绑定
- state = 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}", deptIdList = ddbinds.deptIdList, title = ddbinds.title, 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"));
- foreach (var tempdept in ddbinds.deptIdList)
- {
- depts.Add(tempdept.ToString());
- }
- auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, teacher.id, teacher.name?.ToString(), teacher.picture?.ToString(), _option.JwtSecretKey, scope: Constant.ScopeTeacher, schoolID: school_code?.ToString(), standard: school_base.standard, roles: roles.ToArray(), permissions: permissions.ToArray(), ddDepts: depts.ToArray(), ddsub: ddbinds.userid);
- strBuilder.Append($"醍摩豆账户{teacher.id}【{teacher.name}】和钉钉账户{ddbinds.userid}【{ddbinds.name}】进行绑定,新建的账户绑定成功");
-
- }
- }
- else
- {
- return Ok(new { state = 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}", deptIdList = ddbinds.deptIdList, title = ddbinds.title, 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));
-
- //添加
- if (teacher.defaultSchool != null)
- {
- var schoolRoles = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(teacher.id, new PartitionKey($"Teacher-{teacher.defaultSchool}"));
- if (schoolRoles.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(schoolRoles.ContentStream);
- if (json.RootElement.TryGetProperty("roles", out JsonElement _roles) && _roles.ValueKind != JsonValueKind.Null)
- {
- foreach (var obj in _roles.EnumerateArray())
- {
- //初始定义顾问的assistant 更改为assist
- if (obj.GetString().Equals($"assist"))
- {
- roles.Add(obj.GetString());
- }
- }
- }
- if (json.RootElement.TryGetProperty("permissions", out JsonElement _permissions) && _permissions.ValueKind != JsonValueKind.Null)
- {
- foreach (var obj in _permissions.EnumerateArray())
- {
- //限制只显示BI权限
- foreach (var aut in authorityBIList)
- {
- if (aut.RowKey.Equals(obj.GetString()))
- {
- permissions.Add(obj.GetString());
- }
- }
- }
- }
- }
- school_base = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{teacher.defaultSchool}", new PartitionKey("Base"));
- //foreach (var period in school_base.period)
- //{
- // try
- // {
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<ItemCond>($"{period.id}", new PartitionKey($"ItemCond-{teacher.defaultSchool}"));
- // }
- // catch (CosmosException)
- // {
- // ItemCond itemCond = new ItemCond
- // {
- // id = period.id,
- // pk = "ItemCond",
- // code = $"ItemCond-{teacher.defaultSchool}",
- // ttl = -1,
- // };
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<ItemCond>(itemCond, new PartitionKey($"ItemCond-{teacher.defaultSchool}"));
- // }
- //}
- school_code = teacher.defaultSchool;
- }
- foreach (var tempdept in ddbinds.deptIdList)
- {
- depts.Add(tempdept.ToString());
- }
- }
- auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, teacher.id, teacher.name?.ToString(), teacher.picture?.ToString(), _option.JwtSecretKey, scope: Constant.ScopeTeacher, schoolID: school_code?.ToString(), standard: school_base.standard, roles: roles.ToArray(), permissions: permissions.ToArray(), ddDepts: depts.ToArray(), ddsub: ddbinds.userid);
- operateLog.operateDescribe = $"新建的账户的醍摩豆账户{teacher.id}【{teacher.name}】和钉钉账户{ddbinds.userid}【{ddbinds.name}】进行绑定,绑定成功";
- await _azureStorage.Save<OperateLog>(operateLog);
- return Ok(new
- {
- state = 200,
- auth_token = auth_token,
- idToken = idToken,
- teacher = teacher,
- location = _option.Location,
- });
- }
- else
- {
- operateLog.operateDescribe = $"醍摩豆账户{teacher.id}【{teacher.name}】和钉钉账户{ddbinds.userid}【{ddbinds.name}】进行绑定,账号已被别的醍摩豆id绑定";
- await _azureStorage.Save<OperateLog>(operateLog);
- return Ok(new
- {
- location = _option.Location,
- //账号已被别的醍摩豆id绑定
- state = 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}", deptIdList = ddbinds.deptIdList, title = ddbinds.title, 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"));
- foreach (var tempdept in ddbinds.deptIdList)
- {
- depts.Add(tempdept.ToString());
- }
- auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, teacher.id, teacher.name?.ToString(), teacher.picture?.ToString(), _option.JwtSecretKey, scope: Constant.ScopeTeacher, schoolID: school_code?.ToString(), standard: school_base.standard, roles: roles.ToArray(), permissions: permissions.ToArray(), ddDepts: depts.ToArray(), ddsub: ddbinds.userid);
- strBuilder.Append($"醍摩豆账户{teacher.id}【{teacher.name}】和钉钉账户{ddbinds.userid}【{ddbinds.name}】进行绑定,新建的账户绑定成功");
- await _azureStorage.Save<OperateLog>(operateLog);
- return Ok(new
- {
- state = 200,
- auth_token = auth_token,
- idToken = id,
- //teacher = teacher,
- location = _option.Location,
- });
- }
- }
- auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, teacher.id, teacher.name?.ToString(), teacher.picture?.ToString(), _option.JwtSecretKey, scope: Constant.ScopeTeacher, schoolID: school_code.ToString(), standard: school_base.standard, roles: roles.ToArray(), permissions: permissions.ToArray(), ddDepts: depts.ToArray(), ddsub: ddbinds.userid);
- string temp_idToken = string.IsNullOrEmpty($"{idToken}") ? implicit_token.id_token : idToken.ToString();
- operateLog.operateDescribe = strBuilder.ToString();
- return Ok(new
- {
- state = 200,
- auth_token = auth_token,
- idToken = temp_idToken,
- teacher = teacher,
- location = _option.Location,
- });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} common/login/bind \n {ex.Message}{ex.StackTrace} ", GroupNames.成都开发測試群組);
- return Ok(new
- {
- state = 1,
- location = _option.Location
- });
- }
- }
- /// <summary>
- /// 依据id_Ttoken获取教师信息
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-teacherinfo")]
- public async Task<IActionResult> GetTeacherInfo(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("id_token", out JsonElement id_token)) return BadRequest();
- var jwt = new JwtSecurityToken(id_token.GetString());
- //TODO 此驗證IdToken先簡單檢查,後面需向Core ID新API,驗證Token
- //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);
- Teacher teacher = null;
- //检查是否有绑定信息
- var client = _azureCosmos.GetCosmosClient();
- teacher = await client.GetContainer(Constant.TEAMModelOS, "Teacher").ReadItemAsync<Teacher>($"{id}", new PartitionKey("Base"));
- var auth_token = "";
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var location = _option.Location;
- TmdidImplicit implicit_token = await _aoreAPIHttpService.Implicit(
- new Dictionary<string, string>()
- {
- { "grant_type", "implicit" },
- { "client_id",clientID },
- { "account",teacher.id },
- { "nonce",Guid.NewGuid().ToString()}
- }, location, _configuration);
- Dictionary<string, object> dic = new Dictionary<string, object> { { "PartitionKey", "authority-bi" } };//设置只访问BI的权限
- List<Authority> authorityBIList = await _azureStorage.FindListByDict<Authority>(dic); //获取权限列表
- List<string> roles = new List<string>();//角色列表
- List<string> permissions = new List<string>();//权限列表
- List<string> depts = new List<string>(); //部门id
- School school_base = new School();
- string school_code = null;
- if (implicit_token!=null)
- {
- if (teacher.defaultSchool != null)
- {
- var schoolRoles = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemStreamAsync(teacher.id, new PartitionKey($"Teacher-{teacher.defaultSchool}"));
- if (schoolRoles.Status == 200)
- {
- using var json = await JsonDocument.ParseAsync(schoolRoles.ContentStream);
- if (json.RootElement.TryGetProperty("roles", out JsonElement _roles) && _roles.ValueKind != JsonValueKind.Null)
- {
- foreach (var obj in _roles.EnumerateArray())
- {
- //初始定义顾问的assistant 更改为assist
- if (obj.GetString().Equals($"assist"))
- {
- roles.Add(obj.GetString());
- }
- }
- }
- if (json.RootElement.TryGetProperty("permissions", out JsonElement _permissions) && _permissions.ValueKind != JsonValueKind.Null)
- {
- foreach (var obj in _permissions.EnumerateArray())
- {
- //限制只显示BI权限
- foreach (var aut in authorityBIList)
- {
- if (aut.RowKey.Equals(obj.GetString()))
- {
- permissions.Add(obj.GetString());
- }
- }
- }
- }
- }
- school_base = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<School>($"{teacher.defaultSchool}", new PartitionKey("Base"));
- //foreach (var period in school_base.period)
- //{
- // try
- // {
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").ReadItemAsync<ItemCond>($"{period.id}", new PartitionKey($"ItemCond-{teacher.defaultSchool}"));
- // }
- // catch (CosmosException)
- // {
- // ItemCond itemCond = new ItemCond
- // {
- // id = period.id,
- // pk = "ItemCond",
- // code = $"ItemCond-{teacher.defaultSchool}",
- // ttl = -1,
- // };
- // await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, "School").CreateItemAsync<ItemCond>(itemCond, new PartitionKey($"ItemCond-{teacher.defaultSchool}"));
- // }
- //}
- school_code = teacher.defaultSchool;
- }
- List<Teacher.DingDingBind> ddbinds = teacher.ddbinds;
- Teacher.DingDingBind ddbind = new Teacher.DingDingBind();
- if (teacher.ddbinds.Count > 0)
- {
- if (ddbinds != null)
- {
- foreach (var temp in ddbinds)
- {
- ddbind.userid = temp.userid;
- ddbind.deptIdList = temp.deptIdList;
- }
- }
- foreach (var temp in ddbind.deptIdList)
- {
- depts.Add(temp.ToString());
- }
- }
- else return Ok(new { state = 1, message = "该账户未绑定钉钉信息!请扫码绑定信息!" });
- auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, teacher.id, teacher.name?.ToString(), teacher.picture?.ToString(), _option.JwtSecretKey, scope: Constant.ScopeTeacher, schoolID: school_code.ToString(), standard: school_base.standard, roles: roles.ToArray(), permissions: permissions.ToArray(), ddDepts: depts.ToArray(), ddsub: ddbind.userid);
- }
- var (osblob_uri, osblob_sas) = roles.Contains("area") ? _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete) : _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List);
- return Ok(new { state = 200, auth_token = auth_token, 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, osblob_uri, osblob_sas });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location}, /common/login/get-teacherinfo \n{ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 钉钉扫码登录获取扫码信息
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-ddscancode")]
- public async Task<IActionResult> GetDingDingScanCode(JsonElement jsonElement)
- {
- try
- {
- string appKey = _configuration["DingDingAuth:appKey"];
- string appSecret = _configuration["DingDingAuth:appSecret"];
- if (string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appSecret))
- {
- return Ok(new { state = 0, message = "请检查配置钉钉的信息" });
- }
- //自己传的code
- if (!jsonElement.TryGetProperty("code", out JsonElement LoginTempCode)) return BadRequest();
- //获取access_token
- IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest tokenRequest = new OapiGettokenRequest() { Appkey = appKey, Appsecret = appSecret };
- tokenRequest.SetHttpMethod("Get");
- OapiGettokenResponse tokenRespone = tokenClient.Execute(tokenRequest);
- if (tokenRespone.IsError)
- {
- return BadRequest();
- }
- string access_token = tokenRespone.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, appKey, appSecret);
- if (response.Errcode.Equals(40078))
- {
- return Ok(new { state = 0, message = $"state:{response.Errcode};Err{response.Errmsg}/临时授权码过期请重新扫码" });
- }
- 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 { state = 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 { state = 0, message = "扫码登录失败" });
- }
- List<DingDingUserInfo> ddusers = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object>() { { "RowKey", $"{v2GetResponse.Result.Userid}" }, { "unionId", $"{v2GetResponse.Result.Unionid}" } });
- if (ddusers.Count > 0)
- {
- DingDingUserInfo ddUserInfo = new DingDingUserInfo();
- foreach (var item in ddusers)
- {
- ddUserInfo = item;
- }
- return Ok(new { state = 200, ddUserId = ddUserInfo });
- }
- else
- {
- string divide = appKey.Equals("dingrucgsnt8p13rfbgd") ? "continent" : "international";
- DingDingUserInfo dingDingUserInfo = new DingDingUserInfo()
- {
- PartitionKey = divide,
- RowKey = v2GetResponse.Result.Userid,
- unionId = v2GetResponse.Result.Unionid,
- name = v2GetResponse.Result.Name,
- title = v2GetResponse.Result.Title,
- mobile = v2GetResponse.Result.Mobile,
- jobNumber = v2GetResponse.Result.JobNumber,
- pid = 0,
- deptId = 0,
- deptName = null,
- depts = string.Join(",", v2GetResponse.Result.DeptIdList.ToArray()),
- avatar = v2GetResponse.Result.Avatar,
- isAdmin = v2GetResponse.Result.Admin,
- tmdId = "",
- tmdName = "",
- tmdMobile = "",
- mail = "",
- picture = "",
- roles = "",
- permissions = "",
- };
- await _azureStorage.Save<DingDingUserInfo>(dingDingUserInfo);
- return Ok(new { state = 400, ddUserId = dingDingUserInfo });
- }
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/get-ddscancode \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 钉钉绑定醍摩豆
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("binguser")]
- public async Task<IActionResult> BindUser(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("mobile", out JsonElement moile)) return BadRequest();
- if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
- if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
- //操作记录
- OperateLog operateLog = new OperateLog();
- string blobOrTable = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
- operateLog.PartitionKey = "OperateLog-BI";
- operateLog.RowKey = blobOrTable;
- operateLog.recordID = blobOrTable;
- operateLog.platformSource = "BI";
- operateLog.visitApi = "/common/login/set-ddinductionuser";
- operateLog.operateTime = DateTime.Now;
- HttpClient httpClient = _http.CreateClient();
- string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
- HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, moile);
- if (responseMessage.StatusCode == HttpStatusCode.OK)
- {
- var temp = await responseMessage.Content.ReadAsStringAsync();
- if (temp.Length > 0)
- {
- List<DingDingUserInfo> ddUserInfos = new();
- List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
- var tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
- foreach (var item in itemjson)
- {
- foreach (var itemUser in tempUser)
- {
- var tmdId = item.GetProperty("id").ToString();
- var tmdName = item.GetProperty("name").ToString();
- itemUser.tmdId = tmdId;
- itemUser.tmdName = tmdName;
- itemUser.tmdMobile = item.GetProperty("mobile").ToString();
- itemUser.picture = item.GetProperty("picture").ToString();
- itemUser.mail = item.GetProperty("mail").ToString();
- operateLog.operateType = "修改";
- operateLog.funModule = "钉钉绑定";
- operateLog.tmdId = item.GetProperty("id").ToString();
- operateLog.tmdName = item.GetProperty("name").ToString();
- operateLog.operateDescribe = $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功";
- ddUserInfos.Add(itemUser);
- }
- }
- var dingDingUserInfos = await _azureStorage.UpdateAll<DingDingUserInfo>(ddUserInfos);
- await _azureStorage.Save<OperateLog>(operateLog); //保存操作记录
- return Ok(new { state = 200, ddUsers = dingDingUserInfos });
- }
- else return Ok(new { state = 400, message = "该手机没有注册提莫信息" });
- }
- else return Ok(new { state = responseMessage.StatusCode });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/binguser \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 获取钉钉信息详情绑定醍摩豆和钉钉信息 二合一
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-ddinfo")]
- public async Task<IActionResult> GetDingDingInfo(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("mobile", out JsonElement moile)) return BadRequest();
- if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
- if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
- var tempUser = await _azureStorage.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{userId}" } });
- List<string> roles = new();//角色列表
- List<string> permissions = new List<string>();//权限列表
- List<DingDingUserInfo> ddUserInfos = new();
- var id_token = "";
- foreach (var itemUser in tempUser)
- {
- if (!string.IsNullOrEmpty($"{itemUser.tmdId}") && !string.IsNullOrEmpty($"{itemUser.tmdName}"))
- {
- //roles = new List<string>(itemUser.roles.Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries));
- roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
- permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
- ddUserInfos.Add(itemUser);
- }
- else
- {
- //操作记录
- OperateLog operateLog = new OperateLog();
- string blobOrTable = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString();
- operateLog.PartitionKey = "OperateLog-BI";
- operateLog.RowKey = blobOrTable;
- operateLog.recordID = blobOrTable;
- operateLog.platformSource = "BI";
- operateLog.visitApi = "/common/login/get-ddinfo";
- operateLog.operateTime = DateTime.Now;
- HttpClient httpClient = _http.CreateClient();
- string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
- HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, moile);
- if (responseMessage.StatusCode == HttpStatusCode.OK)
- {
- var temp = await responseMessage.Content.ReadAsStringAsync();
- if (temp.Length > 0)
- {
- List<JsonElement> itemjson = temp.ToObject<List<JsonElement>>();
- foreach (var item in itemjson)
- {
- var tmdId = item.GetProperty("id").ToString();
- var tmdName = item.GetProperty("name").ToString();
- itemUser.tmdId = tmdId;
- itemUser.tmdName = tmdName;
- itemUser.tmdMobile = item.GetProperty("mobile").ToString();
- itemUser.picture = item.GetProperty("picture").ToString();
- itemUser.mail = item.GetProperty("mail").ToString();
- roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
- permissions = !string.IsNullOrEmpty($"{itemUser.permissions}") ? new List<string>(itemUser.permissions.Split(",")) : new List<string>();
- operateLog.operateType = "修改";
- operateLog.funModule = "钉钉绑定";
- operateLog.tmdId = item.GetProperty("id").ToString();
- operateLog.tmdName = item.GetProperty("name").ToString();
- operateLog.operateDescribe = $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.RowKey}】钉钉账户绑定成功";
- ddUserInfos.Add(itemUser);
- }
- ddUserInfos = await _azureStorage.UpdateAll<DingDingUserInfo>(ddUserInfos);
- await _azureStorage.Save<OperateLog>(operateLog); //保存操作记录
- }
- else return Ok(new { state = 400, message = "该手机没有注册醍摩豆账号信息" });
- }
- else return Ok(new { state = responseMessage.StatusCode });
- }
- id_token = JwtAuthExtension.CreateAuthToken(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), _option.JwtSecretKey, scope: $"assist", roles: roles?.ToArray(), permissions: permissions?.ToArray(), ddsub: itemUser.RowKey?.ToString());
- }
- var (osblob_uri, osblob_sas) = roles.Contains("assist") ? _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete) : _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List);
- return Ok(new { state = 200, ddUserInfos, id_token, roles, permissions, osblob_uri, osblob_sas });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI,{_option.Location} /common/login/get-ddinfo \n {ex.Message}{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- public record DingDingbinds
- {
- public string type { get; set; }
- /// <summary>
- /// 所属部门id列表
- /// </summary>
- public List<long> deptIdList { get; set; }
- /// <summary>
- /// 职位名称
- /// </summary>
- public string title { 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; }
- }
-
- }
- }
|