123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457 |
- using Microsoft.Azure.Cosmos;
- using Azure.Storage.Sas;
- using Microsoft.AspNetCore.Authorization;
- using Microsoft.AspNetCore.Http;
- using Microsoft.AspNetCore.Mvc;
- using Microsoft.Extensions.Configuration;
- using Microsoft.Extensions.Options;
- using System;
- using System.Collections.Generic;
- using System.Net;
- using System.Net.Http;
- using System.Security.Policy;
- using System.Text;
- using System.Text.Json;
- using System.Threading.Tasks;
- using TEAMModelOS.Filter;
- using TEAMModelOS.Models;
- using TEAMModelOS.SDK;
- using TEAMModelOS.SDK.Context.BI;
- using TEAMModelOS.SDK.Context.Constant;
- using TEAMModelOS.SDK.DI;
- using TEAMModelOS.SDK.Extension;
- using TEAMModelOS.SDK.Models;
- using TEAMModelOS.SDK.Models.Cosmos.BI.BINormal;
- using TEAMModelOS.SDK.Models.Service;
- using TEAMModelOS.SDK.Models.Table;
- namespace TEAMModelOS.Controllers
- {
- [Route("biz")]
- [ApiController]
- public class BizUsersController : 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 _httpClient;
- public BizUsersController(IHttpClientFactory httpClient, IConfiguration configuration, AzureCosmosFactory azureCosmos, AzureStorageFactory azureStorage, DingDing dingDing, IOptionsSnapshot<Option> option, CoreAPIHttpService coreAPIHttpService)
- {
- _configuration = configuration;
- _azureCosmos = azureCosmos;
- _azureStorage = azureStorage;
- _dingDing = dingDing;
- _option = option?.Value;
- _coreAPIHttpService = coreAPIHttpService;
- _httpClient = httpClient;
- }
- /// <summary>
- /// 登录 第三方用户数据在CosmosDB
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-loginuser")]
- public async Task<IActionResult> GetBizUserLogin(JsonElement jsonElement)
- {
- try
- {
- jsonElement.TryGetProperty("mobile", out JsonElement mobile);
- jsonElement.TryGetProperty("mail", out JsonElement mail);
- if (!jsonElement.TryGetProperty("pwd", out JsonElement password)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- 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> bizUsers = new();
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIteratorSql<BizUsers>(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;
- businessUsers = new()
- {
- id = item.id,
- code = item.code,
- name = item.name,
- picture = item.picture,
- mobile = item.mobile,
- mail = item.mail,
- relation = item.relation,
- };
- //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 = "未找到该用户!" });
- int timezone = 8;
- if (HttpContext.Request.Headers.TryGetValue("Time-Zone", out var Time_Zone) && int.TryParse(Time_Zone, out int tz))
- {
- timezone=tz;
- }
-
- if (businessUsers.id != null)
- {
- var auth_token = JwtAuthExtension.CreateAuthToken(_option.HostName, businessUsers.id, businessUsers.name, businessUsers.picture, _option.JwtSecretKey, scope: "business", Website: "IES", timezone: timezone, roles: new[] { "business" }, expire: 1);
- var clientID = _configuration.GetValue<string>("HaBookAuth:CoreService:clientID");
- var clientSecret = _configuration.GetValue<string>("HaBookAuth:CoreService:clientSecret");
- var token = await CoreTokenExtensions.CreateAccessToken(clientID, clientSecret, _option.Location.Replace("-Dep", "").Replace("-Test", ""));
- return Ok(new { state = RespondCode.Ok, openid_token, auth_token, token = new { access_token = token.AccessToken, expires_in = token.ExpiresOn, id_token = auth_token, token_type = token.TokenType }, businessUsers });
- //return Ok(new { state = RespondCode.Ok, openid_token, auth_token, token, businessUsers });
- }
- else
- { return Ok(new { state = RespondCode.ForbiddenPwd, msg = "密码错误" }); }
- }
- catch (Exception ex)
- {
- return Ok(new { state = RespondCode.ForbiddenPwd, msg = $"服务器错误{ex.Message}\n{ex.StackTrace}" });
- }
- }
- /// <summary>
- /// 注册 第三方用户数据在CosmosDB
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [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);
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- string loginSql = null;
- string osblob_uri = null, osblob_sas = 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").GetItemQueryIteratorSql<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 = long.Parse($"{mobile}"),
- 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);
- (osblob_uri, osblob_sas) = _azureStorage.GetBlobContainerSAS("teammodelos", BlobContainerSasPermissions.Write | BlobContainerSasPermissions.Read | BlobContainerSasPermissions.List | BlobContainerSasPermissions.Delete);
- return Ok(new { state = RespondCode.Ok, openid_token, bizUsers, osblob_uri, osblob_sas });
- }
- }
- /// <summary>
- /// 查询企业详细信息
- /// </summary>
- /// <param name="jsonElenent"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-info")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "business")]
- public async Task<IActionResult> GetInfo(JsonElement jsonElenent)
- {
- try
- {
- if (!jsonElenent.TryGetProperty("id", out JsonElement id)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var table = tableClient.GetTableReference("IESOpenApi");
- Dictionary<string, object> keyValue = new() { { "PartitionKey", "BusinessConfig" } };
- if (!string.IsNullOrEmpty($"{id}"))
- {
- keyValue.Add("RowKey", $"{id}");
- }
- Business business = new();
- var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
- if (response.StatusCode == HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- business = json.ToObject<Business>();
- }
- else return Ok(new { state = RespondCode.NotFound, msg = "该企业信息" });
- return Ok(new { state = RespondCode.Ok, business });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"openApi,{_option.Location} , /biz/GetInfo() \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 重置秘钥
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("reset-secretkey")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "business")]
- public async Task<IActionResult> ResetSecretKey(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- BizConfig bizConfig = new();
- var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync($"{id}", new PartitionKey("BizConfig"));
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- bizConfig = json.ToObject<BizConfig>();
- var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, bizConfig.id, _option.JwtSecretKey, bizConfig.isCustomize);
- bizConfig.jti = auth_token.jti;
- bizConfig.token = auth_token.jwt;
- bizConfig = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizConfig>(bizConfig, bizConfig.id, new PartitionKey("BizConfig"));
- }
- return Ok(new { state = RespondCode.Ok, bizConfig });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"openApi,{_option.Location} , /biz/ResetSecretKey() \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 通过企业Id查询用户信息
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-bizid")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "business")]
- public async Task<IActionResult> GetBizIdUsers(JsonElement jsonElement)
- {
- try
- {
- if (!jsonElement.TryGetProperty("id", out JsonElement id)) return BadRequest();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- List<BusinessUsers> businessUsers = new();
- string sql = $"select value(c) from c join s in c.relation where c.code='BizUsers' and s.bizId = '{id}'";
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIteratorSql<BusinessUsers>(queryText: sql, requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
- {
- businessUsers.Add(item);
- }
- return Ok(new { state = RespondCode.Ok, businessUsers });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"openApi,{_option.Location} , /biz/GetBizIdUsers() \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- /// <summary>
- /// 获取企业开放接口列表
- /// </summary>
- /// <param name="jsonElement"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-openapi")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "business")]
- public async Task<IActionResult> GetOpenApi(JsonElement jsonElement)
- {
- var table = _azureStorage.GetCloudTableClient().GetTableReference("IESOpenApi");
- List<OpenApi> apis = await table.FindListByDict<OpenApi>(new Dictionary<string, object>() { { "PartitionKey", "IES5-API-business" } });
- return Ok(new { state = RespondCode.Ok, apis });
- }
- /// <summary>
- /// 修改和新增企业信息
- /// </summary>
- /// <param name="bizConfig"></param>
- /// <returns></returns>
- [ProducesDefaultResponseType]
- [HttpPost("set-info")]
- [Authorize(Roles = "IES")]
- [AuthToken(Roles = "business")]
- public async Task<IActionResult> SetInfo(BizConfig bizConfig)
- {
- try
- {
- StringBuilder strMsg = new();
- var cosmosClient = _azureCosmos.GetCosmosClient();
- var tableClient = _azureStorage.GetCloudTableClient();
- var blobClient = _azureStorage.GetBlobContainerClient(containerName: "0-public");
- string salt = Utils.CreatSaltString(8);
- List<BizUsers> bizUsers = new();
- string type = "";
- //新增企业信息
- if (string.IsNullOrEmpty(bizConfig.id))
- {
- bizConfig.id = Guid.NewGuid().ToString();
- bizConfig.code = "BizConfig";
- bizConfig.pk = "BizConfig";
- bizConfig.createTime = DateTimeOffset.UtcNow.ToUnixTimeMilliseconds();
- var auth_token = JwtAuthExtension.CreateBusinessApiToken(_option.Location, bizConfig.id, _option.JwtSecretKey, bizConfig.isCustomize);
- bizConfig.jti = auth_token.jti;
- bizConfig.token = auth_token.jwt;
- await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<BizConfig>(bizConfig, new PartitionKey("BizConfig"));
- await foreach (var item in cosmosClient.GetContainer("TEAMModelOS", "Normal").GetItemQueryIteratorSql<BizUsers>(queryText: $"select value(c) from c where c.mobile ={bizConfig.mobile}", requestOptions: new QueryRequestOptions() { PartitionKey = new PartitionKey("BizUsers") }))
- {
- bizUsers.Add(item);
- }
- BizRel bizRel = new() { bizId = bizConfig.id, role = new List<string>() { "admin" } };
- if (bizUsers.Count > 0)
- {
- foreach (var item in bizUsers)
- {
- BizRel temp = item.relation.Find(f => f.bizId.Equals(bizConfig.id));
- if (temp == null)
- {
- item.relation.Add(bizRel);
- await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizUsers>(item, item.id, new PartitionKey("BizUsers"));
- }
- }
- }
- else
- {
- BizUsers tBizUsers = new() { id = Guid.NewGuid().ToString(), code = "BizUsers", name = bizConfig.mobile.ToString(), mobile = bizConfig.mobile, salt = salt, pwd = Utils.HashedPassword($"{bizConfig.mobile}", salt), relation = new List<BizRel>() { { bizRel } } };
- await cosmosClient.GetContainer("TEAMModelOS", "Normal").CreateItemAsync<BizUsers>(tBizUsers, new PartitionKey("BizUsers"));
- }
- strMsg.Append($"{bizConfig.name}【{bizConfig.id}】新增企业基础信息。");
- type = "bizconfig-add";
- }
- //修改企业信息
- else
- {
- var response = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReadItemStreamAsync(bizConfig.id, new PartitionKey("BizConfig"));
- if (response.StatusCode==System.Net.HttpStatusCode.OK)
- {
- using var json = await JsonDocument.ParseAsync(response.Content);
- BizConfig tempBizConfig = json.ToObject<BizConfig>();
- bizConfig.pk = "BizConfig";
- bizConfig.code = "BizConfig";
- bizConfig.ttl = -1;
- bizConfig.createTime = tempBizConfig.createTime;
- bizConfig.jti = tempBizConfig.jti;
- bizConfig.token = tempBizConfig.token;
- bizConfig = await cosmosClient.GetContainer("TEAMModelOS", "Normal").ReplaceItemAsync<BizConfig>(bizConfig, bizConfig.id, new PartitionKey("BizConfig"));
- strMsg.Append($"{bizConfig.name}【{bizConfig.id}】修改企业基础信息。");
- type = "bizconfig-update";
- }
- }
- //保存操作记录
- await AzureStorageBlobExtensions.SaveBILog(blobClient, tableClient, type, strMsg.ToString(), _dingDing, httpContext: HttpContext);
- return Ok(new { state = RespondCode.Ok, bizConfig });
- }
- catch (Exception e)
- {
- await _dingDing.SendBotMsg($"openApi,{_option.Location} , /biz/SetInfo() \n {e.Message}\n{e.StackTrace} \n ", GroupNames.成都开发測試群組);
- return BadRequest();
- }
- }
- [ProducesDefaultResponseType]
- [AuthToken(Roles = "business")]
- [HttpPost("check-webhook")]
- [Authorize(Roles = "IES")]
- public async Task<IActionResult> CheckWebhook(JsonElement json ) {
- var (userid, name, picture, _) = HttpContext.GetAuthTokenInfo();
- string bizCode = json.GetProperty("bizCode").GetString();
- //检查是否与bizCode 有关联。
- BizConfig config = await _azureCosmos.GetCosmosClient().GetContainer(Constant.TEAMModelOS, Constant.Normal).ReadItemAsync<BizConfig>(bizCode, new PartitionKey("BizConfig"));
- List<dynamic> results = new List<dynamic>();
- if (!string.IsNullOrWhiteSpace(config?.webhook))
- {
- var urls = config?.webhook.Trim().Split(",");
- foreach (var url in urls)
- {
- HttpStatusCode httpStatus = await WebHookService.Send(new { data= "check-webhook" }, (url,config.webhookHead,config.webhookToken,config), "check-webhook", _httpClient, _dingDing, 2);
- results.Add(new { url = url, status = httpStatus });
- }
- return Ok(results);
- }
- else {
- return BadRequest(new { code=1,msg="未配置Webhook通知回调"});
- }
-
- }
- }
- }
|