123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774 |
- 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 TEAMModelBI.Filter;
- using TEAMModelBI.Models.Extension;
- using TEAMModelOS.SDK;
- using Microsoft.AspNetCore.Hosting;
- using TEAMModelBI.Tool;
- using TEAMModelBI.DI.BIAzureStorage;
- using TEAMModelOS.SDK.Models.Table;
- using TEAMModelOS.SDK.Context.Constant;
- using TEAMModelBI.Models;
- using TEAMModelOS.SDK.Context.BI;
- //using static DingTalk.Api.Response.OapiV2UserGetResponse;
- namespace TEAMModelBI.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 _coreAPIHttpService;
- private readonly IHttpClientFactory _http;
- private readonly IWebHostEnvironment _environment; //读取文件
- public LoginController(IConfiguration configuration, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, CoreAPIHttpService coreAPIHttpService, IHttpClientFactory http, IWebHostEnvironment environment)
- {
- _configuration = configuration;
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _dingDing = dingDing;
- _option = option?.Value;
- _coreAPIHttpService = coreAPIHttpService;
- _http = http;
- _environment = environment;
- }
- /// <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"];
- string proDeptId = _configuration["CustomParam:proDeptId"];
- //string divide = _configuration["CustomParam:SiteScope"];
- string divide = _option.Location;
- var cosmosClient = _azureCosmos.GetCosmosClient();
- string Website = "China";
- if (string.IsNullOrWhiteSpace(appKey) || string.IsNullOrWhiteSpace(appSecret))
- {
- return Ok(new { state = 0, msg = "请检查配置钉钉的信息" });
- }
- //自己传的code
- if (!jsonElement.TryGetProperty("code", out JsonElement LoginTempCode)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- Website = BIConst.Global;
- }
- //获取access_token
- IDingTalkClient tokenClient = new DefaultDingTalkClient("https://oapi.dingtalk.com/gettoken");
- OapiGettokenRequest tokenRequest = new() { 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("https://oapi.dingtalk.com/sns/getuserinfo_bycode");
- OapiSnsGetuserinfoBycodeRequest req = new() { TmpAuthCode = $"{LoginTempCode}" }; //通过扫描二维码,跳转到指定的Url后,向Url中追加Code临时授权码
- OapiSnsGetuserinfoBycodeResponse response = clientinfo.Execute(req, appKey, appSecret);
- if (response.Errcode.Equals(40078))
- {
- return Ok(new { state = 0, msg = $"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() { Unionid = unionid };
- OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, access_token);
- if (byunionidResponse.IsError || byunionidResponse.Errcode == 60121)
- {
- return Ok(new { state = 0, msg = byunionidResponse.Errmsg });
- }
- // 根据userId获取用户信息
- string userid = byunionidResponse.Result.Userid;
- IDingTalkClient client3 = new DefaultDingTalkClient("https://oapi.dingtalk.com/topapi/v2/user/get");
- OapiV2UserGetRequest v2GetRequest = new()
- {
- Userid = userid,
- Language = "zh_CN"
- };
- v2GetRequest.SetHttpMethod("POST");
- OapiV2UserGetResponse v2GetResponse = client3.Execute(v2GetRequest, access_token);
- if (v2GetResponse.IsError)
- {
- return Ok(new { state = 0, msg = "扫码登录失败" });
- }
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
- var id_token = "";
- string osblob_uri = null, osblob_sas = null;
- List<string> roles = new();//角色列表
- List<string> permissions = new();//权限列表
- bool isExploit = false;
- List<DingDingUserInfo> ddusers = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object>() { { "PartitionKey", $"{divide}"},{ "userId", $"{v2GetResponse.Result.Userid}" }, { "unionId", $"{v2GetResponse.Result.Unionid}" } });
- if (ddusers.Count > 0)
- {
- List<DingDingUserInfo> saveInfo = new();
- StringBuilder strMsg = new();
- foreach (var item in ddusers)
- {
- if (string.IsNullOrEmpty(item.tmdId))
- {
- var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{item.mobile}" } }, _option.Location, _configuration);
- if (coreUser != null && coreUser.id != null)
- {
- item.tmdId = coreUser.id;
- item.tmdName = coreUser.name;
- item.tmdMobile = coreUser.mobile;
- item.picture = coreUser.picture;
- item.mail = coreUser.mail;
- }
- else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
- //List<string> mobiles = new() { $"{ item.mobile}" };
- //var content = new StringContent(mobiles.ToJsonString(), Encoding.UTF8, "application/json");
- //string json = await _coreAPIHttpService.GetUserInfos(content);
- //if (!string.IsNullOrEmpty(json))
- //{
- // List<JsonElement> json_id = json.ToObject<List<JsonElement>>();
- // foreach (var tmd in json_id)
- // {
- // item.tmdId = tmd.GetProperty("id").ToString();
- // item.tmdName = tmd.GetProperty("name").ToString();
- // item.tmdMobile = tmd.GetProperty("mobile").ToString();
- // item.picture = tmd.GetProperty("picture").ToString();
- // item.mail = tmd.GetProperty("mail").ToString();
- // }
- //}
- //else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
- strMsg.Append($"{item.tmdName}【{item.tmdId}】醍摩豆账号和{item.name}【{item.userId}】钉钉账户绑定成功");
- //保存操作记录
- //await _azureStorage.SaveBILog("tabledd-update", strMsg?.ToString(), _dingDing, httpContext: HttpContext, twebsite: Website, tid: item.tmdId, tname: item.tmdName);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", strMsg?.ToString(), _dingDing, httpContext: HttpContext, twebsite: Website, tid: item.tmdId, tname: item.tmdName);
- saveInfo.Add(item);
- }
- List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, item.tmdId);
- if (schoolIds.Count > 0)
- {
- item.schoolIds = string.Join("|", schoolIds);
- await table.SaveOrUpdate<DingDingUserInfo>(item);
- }
- roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(",")) : new List<string>();
- permissions = !string.IsNullOrEmpty($"{item.permissions}") ? new List<string>(item.permissions.Split(",")) : new List<string>();
- if (item.depts.Contains($"{proDeptId}")) isExploit = true;
- if (item.deptId == long.Parse($"{proDeptId}")) isExploit = true;
- if (item.pid == long.Parse($"{proDeptId}")) isExploit = true;
- //自己写的
- id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, item.tmdId?.ToString(), item.tmdName?.ToString(), item.picture?.ToString(), _option.JwtSecretKey, scope: "assist", webSite: Website, isex: isExploit, item.userId?.ToString(), item.name?.ToString(), item.avatar?.ToString(), roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
- }
- if (saveInfo.Count > 0)
- {
- ddusers = await table.UpdateAll<DingDingUserInfo>(saveInfo);
- }
- }
- else
- {
- DingDingUserInfo ddUserInfo = new()
- {
- PartitionKey = divide,
- RowKey = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds().ToString(),
- userId = 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,
- roles = "assist",
- permissions = "abilitystandard-read,batcharea-read,batchschool-read,orgusers-read"
- };
- if (!string.IsNullOrEmpty($"{ddUserInfo.mobile}"))
- {
- var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{ddUserInfo.mobile}" } }, _option.Location, _configuration);
- if (coreUser != null && coreUser.id != null) {
- ddUserInfo.tmdId = coreUser.id;
- ddUserInfo.tmdName = coreUser.name;
- ddUserInfo.tmdMobile = coreUser.mobile;
- ddUserInfo.picture = coreUser.mobile;
- ddUserInfo.mail = coreUser.mail;
- }
- else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
- //HttpClient httpClient = _http.CreateClient();
- //string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
- //List<string> mobiles = new() { $"{ ddUserInfo.mobile}" };
- //HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
- //if (responseMessage.StatusCode == HttpStatusCode.OK)
- //{
- // string temp = responseMessage.Content.ReadAsStringAsync().Result;
- // List<JsonElement> json_id = temp.ToObject<List<JsonElement>>();
- // if (json_id.Count > 0)
- // {
- // foreach (var tmd in json_id)
- // {
- // ddUserInfo.tmdId = tmd.GetProperty("id").ToString();
- // ddUserInfo.tmdName = tmd.GetProperty("name").ToString();
- // ddUserInfo.tmdMobile = tmd.GetProperty("mobile").ToString();
- // ddUserInfo.picture = tmd.GetProperty("picture").ToString();
- // ddUserInfo.mail = tmd.GetProperty("mail").ToString();
- // }
- // }
- // else return Ok(new { state = 404, msg = "依据钉钉手机号未找到醍摩豆账号!" });
- //}
- }
- else return Ok(new { state = 404, msg = "钉钉手机号为空" });
- List<string> schoolIds = await CommonFind.FindSchoolIds(cosmosClient, ddUserInfo.tmdId);
- if (schoolIds.Count > 0)
- {
- ddUserInfo.schoolIds = string.Join("|", schoolIds);
- }
- ddUserInfo = await table.Save<DingDingUserInfo>(ddUserInfo);
- //保存操作记录
- //await _azureStorage.SaveBILog("tabledd-update", $"{ddUserInfo.tmdName}【{ddUserInfo.tmdId}】醍摩豆账号和{ddUserInfo.name}【{ddUserInfo.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext, tid: ddUserInfo.tmdId, tname: ddUserInfo.tmdName, twebsite: Website);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{ddUserInfo.tmdName}【{ddUserInfo.tmdId}】醍摩豆账号和{ddUserInfo.name}【{ddUserInfo.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext, tid: ddUserInfo.tmdId, tname: ddUserInfo.tmdName, twebsite: Website);
- roles = !string.IsNullOrEmpty($"{ddUserInfo.roles}") ? new List<string>(ddUserInfo.roles.Split(",")) : new List<string>();
- permissions = !string.IsNullOrEmpty($"{ddUserInfo.permissions}") ? new List<string>(ddUserInfo.permissions.Split(",")) : new List<string>();
- if (ddUserInfo.depts.Contains($"{proDeptId}")) isExploit = true;
- if (ddUserInfo.deptId == long.Parse($"{proDeptId}")) isExploit = true;
- if (ddUserInfo.pid == long.Parse($"{proDeptId}")) isExploit = true;
- //自己写的
- id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, ddUserInfo.tmdId?.ToString(), ddUserInfo.tmdName?.ToString(), ddUserInfo.picture?.ToString(), _option.JwtSecretKey, scope: "assist", webSite: Website, isex: isExploit, ddUserInfo.userId?.ToString(), ddUserInfo.name?.ToString(), ddUserInfo.avatar?.ToString(), roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
- }
- if (Website.Equals(BIConst.Global))
- {
- (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete, BIConst.Global);
- }
- else
- {
- (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
- }
- //(osblob_uri, osblob_sas) = roles.Contains("assist") ? _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete) : _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List, BIConst.Global);
- return Ok(new { state = 200, ddUserInfos = ddusers, id_token, roles, permissions, osblob_uri, osblob_sas });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/get-ddscancode \n {ex.Message}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 钉钉绑定醍摩豆
- /// </summary>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("set-bind")]
- public async Task<IActionResult> BindUser(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("partitionKey", out JsonElement partitionKey)) return BadRequest();
- if (!jsonElement.TryGetProperty("rowKey", out JsonElement userId)) return BadRequest();
- jsonElement.TryGetProperty("id_token", out JsonElement idtoken);
- jsonElement.TryGetProperty("mobile", out JsonElement mobile);
- jsonElement.TryGetProperty("site", out JsonElement site);
- string Website = "China";
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- Website = BIConst.Global;
- }
- HttpClient httpClient = _http.CreateClient();
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
- var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "userId", $"{userId}" } });
- var id_token = "";
- var auth_token = "";
- List<DingDingUserInfo> ddUserInfos = new();
- List<string> roles = new();//角色列表
- List<string> permissions = new();//权限列表
- foreach (var itemUser in tempUser)
- {
- if (!string.IsNullOrEmpty($"{idtoken}"))
- {
- JwtSecurityToken jwt = new JwtSecurityToken($"{idtoken}");
- var tmdId = jwt.Payload.Sub;
- jwt.Payload.TryGetValue("name", out object tmdName);
- jwt.Payload.TryGetValue("picture", out object picture);
- itemUser.tmdId = tmdId;
- itemUser.tmdName = $"{tmdName}";
- itemUser.tmdMobile = itemUser.mobile;
- itemUser.picture = $"{picture}";
- }
- if (!string.IsNullOrEmpty($"{mobile}"))
- {
- var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{mobile}" } }, _option.Location, _configuration);
- if (coreUser != null && coreUser.id != null)
- {
- itemUser.tmdId = coreUser.id;
- itemUser.tmdName = coreUser.name;
- itemUser.tmdMobile = coreUser.mobile;
- itemUser.picture = coreUser.mobile;
- itemUser.mail = coreUser.mail;
- }
- else return Ok(new { state = 404, msg = "手机号未找到醍摩豆账户" });
- //string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
- //List<string> mobiles = new() { $"{mobile}" };
- //HttpResponseMessage responseMessage = await httpClient.PostAsJsonAsync(url, mobiles);
- //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)
- // {
- // itemUser.tmdId = item.GetProperty("id").ToString();
- // itemUser.tmdName = item.GetProperty("name").ToString();
- // itemUser.tmdMobile = item.GetProperty("mobile").ToString();
- // itemUser.picture = item.GetProperty("picture").ToString();
- // itemUser.mail = item.GetProperty("mail").ToString();
- // }
- // }
- //}
- //else return Ok(new { state = 404, msg = "手机号未找到醍摩豆账户" });
- }
- if (string.IsNullOrEmpty($"{mobile}") && string.IsNullOrEmpty($"{idtoken}"))
- return Ok(new { state = 400, msg = "mobile、idtoken参数错误" });
- else
- {
- ddUserInfos.Add(itemUser);
- roles = !string.IsNullOrEmpty($"{itemUser.roles}") ? new List<string>(itemUser.roles.Split(",")) : new List<string>();
- //保存操作记录
- //await _azureStorage.SaveBILog("tabledd-update", $"{itemUser.tmdName}【{itemUser.tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.userId}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: Website, httpContext: HttpContext);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{itemUser.tmdName}【{itemUser.tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.userId}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: Website, httpContext: HttpContext);
- id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), _option.JwtSecretKey, scope: "assist", webSite: Website, isex: false, itemUser.userId?.ToString(), itemUser.name?.ToString(), itemUser.avatar?.ToString(), roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
- }
- }
- ddUserInfos = await table.UpdateAll(ddUserInfos);
- string osblob_uri = null, osblob_sas = null;
- if (Website.Equals(BIConst.Global))
- {
- (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete, BIConst.Global);
- }
- else
- {
- (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
- }
- //blob 访问权限
- //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, osblob_uri, osblob_sas });
- }
- catch (Exception ex)
- {
- await _dingDing.SendBotMsg($"BI, {_option.Location} /common/login/set-bind \n {ex.Message}\n{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();
-
- jsonElement.TryGetProperty("site", out JsonElement site);
- string Website = "China";
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- Website = BIConst.Global;
- }
- var table = tableClient.GetTableReference("BIDDUserInfo");
- var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "userId", $"{userId}" } });
- List<string> roles = new();//角色列表
- List<string> permissions = new();//权限列表
- 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
- {
- var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{moile}" } }, _option.Location, _configuration);
- if (coreUser != null && coreUser.id != null)
- {
- itemUser.tmdId = coreUser.id;
- itemUser.tmdName = coreUser.name;
- itemUser.tmdMobile = coreUser.mobile;
- itemUser.picture = coreUser.mobile;
- itemUser.mail = coreUser.mail;
- 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);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{coreUser.name}【{coreUser.id}】醍摩豆账号和{itemUser.name}【{itemUser.userId}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: Website, httpContext: HttpContext);
- }
- else return Ok(new { state = 400, message = "该手机没有注册醍摩豆账号信息" });
- //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>>();
- // string tmdId = null;
- // string tmdName = null;
- // foreach (var item in itemjson)
- // {
- // tmdId = item.GetProperty("id").ToString();
- // tmdName = item.GetProperty("name").ToString();
- // itemUser.tmdId = tmdId?.ToString();
- // itemUser.tmdName = tmdName?.ToString();
- // 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>();
- // ddUserInfos.Add(itemUser);
- // }
- // ddUserInfos = await table.UpdateAll<DingDingUserInfo>(ddUserInfos);
- // //保存操作记录
- // //await _azureStorage.SaveBILog("tabledd-update", $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.userId}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: Website, httpContext: HttpContext);
- // await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{tmdName}【{tmdId}】醍摩豆账号和{itemUser.name}【{itemUser.userId}】钉钉账户绑定成功", _dingDing, tid: itemUser.tmdId, tname: itemUser.name, twebsite: Website, httpContext: HttpContext);
- // }
- // else return Ok(new { state = 400, message = "该手机没有注册醍摩豆账号信息" });
- //}
- //else return Ok(new { state = responseMessage.StatusCode });
- }
- //自己写的
- id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), _option.JwtSecretKey, scope: "assist", webSite: Website, isex: false, itemUser.userId?.ToString(), itemUser.name?.ToString(), itemUser.avatar?.ToString(), roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
- }
-
- await table.SaveOrUpdateAll<DingDingUserInfo>(ddUserInfos);
- string osblob_uri = null, osblob_sas = null;
- if (Website.Equals(BIConst.Global))
- {
- (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete, BIConst.Global);
- }
- else
- {
- (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
- }
- //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}\n{ex.StackTrace}", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 企业登录
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-bizuserlogin")]
- public async Task<IActionResult> GetCommpanyLogin(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("mobile", out JsonElement mobile);
- jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
- jsonElement.TryGetProperty("mail", out JsonElement mail);
- if (!jsonElement.TryGetProperty("pwd", out JsonElement password)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- string Website = "China";
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- Website = BIConst.Global;
- }
- Dictionary<string, object> tableDic = new();
- string tableSql = null;
- if (!string.IsNullOrEmpty($"{mail}"))
- {
- tableSql = $" PartitionKey eq 'BusinessUser' and mail eq '{mail}'";
- tableDic = new Dictionary<string, object>() { { "PartitionKey", "BizRelUser" }, { "mail", $"{mail}" } };
- }
- if (!string.IsNullOrEmpty($"{tmdId}"))
- {
- tableSql = $" PartitionKey eq 'BusinessUser' and tmdId eq '{tmdId}'";
- tableDic = new Dictionary<string, object>() { { "PartitionKey", "BizRelUser" }, { "tmdId", $"{tmdId}" } };
- }
- if (!string.IsNullOrEmpty($"{mobile}"))
- {
- tableSql = $" PartitionKey eq 'BusinessUser' and mobile eq '{mobile}'";
- tableDic = new Dictionary<string, object>() { { "PartitionKey", "BizRelUser" }, { "mobile", $"{mobile}" } };
- }
- if (!string.IsNullOrEmpty(tableSql))
- {
- var table = tableClient.GetTableReference("IESOpenApi");
- List<BusinessUser> findBizUsers = await table.QueryWhereString<BusinessUser>(tableSql);
- //List<BusinessUser> findBizUsers = await table.FindListByDict<BusinessUser>(tableDic);
- if (findBizUsers.Count > 0)
- {
- BusinessUser bizUser = new();
- foreach (var item in findBizUsers)
- {
- bizUser.PartitionKey = item.PartitionKey;
- bizUser.RowKey = item.RowKey;
- bizUser.name = item.name;
- bizUser.picture = item.picture;
- bizUser.tmdId = item.tmdId;
- bizUser.mobile = item.mobile;
- bizUser.mail = item.mail;
- bizUser.salt = item.salt;
- bizUser.pwd = item.pwd;
- }
- List<BizRelUser> bizRelUsers = new();
- List<RelBizInfo> relBizInfos = new();
- if (bizUser != null)
- {
- string tableSqlUser = $"PartitionKey eq 'BizRelUser' and userId eq '{bizUser.RowKey}'";
- bizRelUsers = await table.QueryWhereString<BizRelUser>(tableSqlUser);
- if (bizRelUsers.Count > 0)
- {
- foreach (var item in bizRelUsers)
- {
- BusinessConfig businessConfig = table.Get<BusinessConfig>("BusinessConfig", item.bizId);
- RelBizInfo relBizInfo = new()
- {
- userRowKey = item.userId,
- relId = item.RowKey,
- bizRowKey = item.bizId,
- roles = !string.IsNullOrEmpty($"{item.roles}") ? new List<string>(item.roles.Split(',')) : new List<string>()
- };
- if (businessConfig != null)
- {
- relBizInfo.bizName = businessConfig.name;
- relBizInfo.bizCredit = businessConfig.credit;
- relBizInfo.bizPicture = businessConfig.picture;
- relBizInfos.Add(relBizInfo);
- }
- }
- }
- }
- var hashedPw = Utils.HashedPassword(password.ToString(), bizUser.salt.ToString());
- if (hashedPw.Equals(bizUser.pwd))
- {
- //string id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, bizUser.RowKey?.ToString(), bizUser.name?.ToString(), bizUser.picture?.ToString(), _option.JwtSecretKey, scope: "company", webSite: Website, expire: 3);
- string openid_token = JwtAuth.CreateAuthTokenOpenBI(_option.HostName, bizUser.RowKey?.ToString(), bizUser.name?.ToString(), bizUser.picture?.ToString(),$"{Website}-Open",_option.JwtSecretKey, expire: 3);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{bizUser.name}【{bizUser.RowKey}】登录商务智能开放平台", _dingDing, tid: bizUser.RowKey, tname: bizUser.name, twebsite: Website?.ToString(), httpContext: HttpContext);
- return Ok(new { state = RespondCode.Ok, openid_token, bizUser, relBizInfos });
- }
- else return Ok(new { state = RespondCode.ForbiddenPwd, msg = "密码错误!" });
- }
- else return Ok(new { state = RespondCode.NotFound, msg = "该账户不存在" });
- }
- else return Ok(new { state = RespondCode.ParamsError, msg = "参数错误" });
- }
- /// <summary>
- /// 用户信息注册
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [HttpPost("set-ropen")]
- public async Task<IActionResult> SetRegistered(JsonElement jsonElement)
- {
- if (!jsonElement.TryGetProperty("name", out JsonElement name)) return BadRequest();
- if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
- jsonElement.TryGetProperty("tmdId", out JsonElement tmdId);
- jsonElement.TryGetProperty("mail", out JsonElement mail);
- jsonElement.TryGetProperty("pwd", out JsonElement pwd);
- jsonElement.TryGetProperty("site", out JsonElement site);
- string Website = "China";
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- if ($"{site}".Equals(BIConst.Global))
- {
- cosmosClient = _azureCosmos.GetCosmosClient(name: BIConst.Global);
- tableClient = _azureStorage.GetCloudTableClient(BIConst.Global);
- blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public", BIConst.Global);
- Website = BIConst.Global;
- }
- var table = tableClient.GetTableReference("IESOpenApi");
- string salt = Utils.CreatSaltString(8);
- BusinessUser bizUser = null;
- List<BusinessUser> findBizUsers = await table.QueryWhereString<BusinessUser>($" PartitionKey eq 'BusinessUser' and mobile eq '{mobile}'");
- if (findBizUsers.Count <= 0)
- {
- var coreUser = await _coreAPIHttpService.GetUserInfo(new Dictionary<string, string> { { "key", $"{mobile}" } }, _option.Location, _configuration);
- if (coreUser != null)
- bizUser = new() { RowKey = Guid.NewGuid().ToString(), name = coreUser.name, tmdId = coreUser.id, mobile = coreUser.mobile, mail = coreUser.mail, salt = salt, pwd = string.IsNullOrEmpty($"{pwd}") ? Utils.HashedPassword($"{mobile}", salt) : Utils.HashedPassword($"{pwd}", salt) };
- else
- bizUser = new() { RowKey = Guid.NewGuid().ToString(), name = $"{name}", mobile = $"{mobile}", salt = salt, pwd = string.IsNullOrEmpty($"{pwd}") ? Utils.HashedPassword($"{mobile}", salt) : Utils.HashedPassword($"{pwd}", salt) };
- bizUser = await table.Save<BusinessUser>(bizUser);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "bizUser-update", $"{bizUser.name}【{bizUser.RowKey}】注册开放平台用户", _dingDing, tid: bizUser.RowKey, tname: bizUser.name, twebsite: Website?.ToString(), httpContext: HttpContext);
- return Ok(new { state = RespondCode.Ok, bizUser });
- }
- else return Ok(new { state = RespondCode.Conflict, msg = "该手机号已注册开放平台,请直接登录" });
- }
- 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; }
- }
- }
- }
|