123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629 |
- 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 TEAMModelOS.SDK.Context.Constant;
- using TEAMModelBI.Models;
- using TEAMModelOS.SDK.Context.BI;
- using TEAMModelOS.SDK.Models.Cosmos.BI.BINormal;
- //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 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>();
- roles = roles.Where(w => !string.IsNullOrEmpty(w)).ToList();
- 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 = "依据钉钉手机号未找到醍摩豆账号!" });
- }
- 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 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>();
- roles = roles.Where(w => !string.IsNullOrEmpty(w)).ToList();
- 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 = "手机号未找到醍摩豆账户" });
- }
- 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>();
- roles = roles.Where(w => !string.IsNullOrEmpty(w)).ToList();
- //保存操作记录
- 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 = "该手机没有注册醍摩豆账号信息" });
- }
- //自己写的
- 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>
- /// 登录 第三方用户数据在CosmosDB
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-bizuser")]
- public async Task<IActionResult> GetBizUserLogin(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("mobile", out JsonElement mobile);
- jsonElement.TryGetProperty("mail", out JsonElement mail);
- if (!jsonElement.TryGetProperty("pwd", out JsonElement password)) return BadRequest();
- jsonElement.TryGetProperty("site", out JsonElement site);
- 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);
- }
-
- string loginSql = null;
- if (!string.IsNullOrEmpty($"{mobile}"))
- loginSql = $"select value(c) from c where c.mobile ={mobile}";
- else if (!string.IsNullOrEmpty($"{mail}"))
- loginSql = $"select value(c) from c where c.mail ={mail}";
- else return Ok(new { state = RespondCode.ParamsError, msg = "手机号/和邮箱为空" });
- List<BusinessUsers> bizUsers = new();
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BusinessUsers>(queryText:loginSql,requestOptions:new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
- {
- bizUsers.Add(item);
- }
- BusinessUsers businessUsers = new(); string openid_token = null;
- if (bizUsers.Count > 0)
- {
- foreach (var item in bizUsers)
- {
- var hashedPw = Utils.HashedPassword(password.ToString(), item.salt.ToString());
- if (hashedPw.Equals(item.pwd))
- {
- businessUsers = item;
- //string id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, bizUser.RowKey?.ToString(), bizUser.name?.ToString(), bizUser.picture?.ToString(), _option.JwtSecretKey, scope: "company", webSite: Website, expire: 3);
- openid_token = JwtAuthExtension.CreateBizLoginAuthToken(_option.HostName, businessUsers.id?.ToString(), businessUsers.name?.ToString(), businessUsers.picture?.ToString(), $"{_option.Location}-Open", _option.JwtSecretKey, expire: 3);
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "tabledd-update", $"{businessUsers.name}【{businessUsers.id}】登录开放平台", _dingDing, tid: businessUsers.id, tname: businessUsers.name, twebsite: "Open", httpContext: HttpContext);
- }
- }
- }
- else return Ok(new { state = RespondCode.NotFound, msg = "未找到该用户!" });
- if (businessUsers.id != null)
- return Ok(new { state = RespondCode.Ok, openid_token, businessUsers });
- else
- return Ok(new { state = RespondCode.ForbiddenPwd, msg = "密码错误" });
- }
- /// <summary>
- /// 注册 第三方用户数据在CosmosDB
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("set-bizuser")]
- public async Task<IActionResult> SetBizUserLogin(JsonElement jsonElement)
- {
- jsonElement.TryGetProperty("name", out JsonElement name);
- if (!jsonElement.TryGetProperty("mobile", out JsonElement mobile)) return BadRequest();
- jsonElement.TryGetProperty("mail", out JsonElement mail);
- jsonElement.TryGetProperty("pwd", out JsonElement pwd);
- jsonElement.TryGetProperty("site", out JsonElement site);
- 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);
- }
- string loginSql = null;
- if (!string.IsNullOrEmpty($"{mobile}"))
- loginSql = $"select value(c) from c where c.mobile ={mobile}";
- else if (!string.IsNullOrEmpty($"{mail}"))
- loginSql = $"select value(c) from c where c.mail ={mail}";
- else return Ok(new { state = RespondCode.ParamsError, msg = "手机号/和邮箱为空" });
- List<BizUsers> tempBizUsers = new();
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIterator<BizUsers>(queryText: loginSql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
- {
- tempBizUsers.Add(item);
- }
- if (tempBizUsers.Count > 0)
- return Ok(new { state = RespondCode.Conflict, msg = "已存在" });
- else
- {
- string salt = Utils.CreatSaltString(8);
- BizUsers bizUsers = new()
- {
- id = Guid.NewGuid().ToString(),
- code = "BizUsers",
- name = string.IsNullOrEmpty($"{name}") ? $"{mobile}" : $"{name}",
- mobile = mobile.GetInt64(),
- salt = salt,
- pwd = string.IsNullOrEmpty($"{pwd}") ? Utils.HashedPassword($"{mobile}", salt) : Utils.HashedPassword($"{pwd}", salt),
- };
- bizUsers = await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<BizUsers>(bizUsers, new PartitionKey("BizUsers"));
- string log = $"{bizUsers.name}【{bizUsers.id}】注册第三方用户信息基础信息。";
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, "login-login", log, _dingDing, httpContext: HttpContext);
- var openid_token = JwtAuthExtension.CreateBizLoginAuthToken(_option.HostName, bizUsers.id?.ToString(), bizUsers.name?.ToString(), bizUsers.picture?.ToString(), $"{_option.Location}-Open", _option.JwtSecretKey, expire: 3);
- return Ok(new { state = RespondCode.Ok, openid_token, bizUsers });
- }
- }
- }
- }
|