123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420 |
- 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 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 _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></returns>
- [ProducesDefaultResponseType]
- [HttpPost("get-ddscancode")]
- public async Task<IActionResult> GetDingDingScanCode(JsonElement jsonElement)
- {
- try
- {
- string appKey = _configuration["DingDingAuth:appKey"];
- string appSecret = _configuration["DingDingAuth:appSecret"];
- string divide = _configuration["CustomParam:SiteScope"];
- 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() { 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, 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() { Unionid = unionid };
- OapiUserGetbyunionidResponse byunionidResponse = client2.Execute(byunionidRequest, access_token);
- if (byunionidResponse.IsError || byunionidResponse.Errcode == 60121)
- {
- return Ok(new { state = 0, message = 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, message = "扫码登录失败" });
- }
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
- List<DingDingUserInfo> ddusers = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object>() { { "RowKey", $"{v2GetResponse.Result.Userid}" }, { "unionId", $"{v2GetResponse.Result.Unionid}" } });
- if (ddusers.Count > 0)
- {
- List<DingDingUserInfo> ddUserInfos = new List<DingDingUserInfo>();
- var id_token = "";
- string osblob_uri = null, osblob_sas = null;
- List<string> roles = new();//角色列表
- List<string> permissions = new List<string>();//权限列表
- foreach (var item in ddusers)
- {
- ddUserInfos.Add(item);
- }
- foreach (var item in ddUserInfos)
- {
- if (!string.IsNullOrEmpty(item.tmdId))
- {
- 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>();
- ///在IES5 添加
- //id_token = JwtAuthExtension.CreateAuthToken(_option.HostName, item.tmdId?.ToString(), item.tmdName?.ToString(), item.picture?.ToString(), _option.JwtSecretKey, Website: "BI", scope: $"assist", roles: roles?.ToArray(), permissions: permissions?.ToArray(), ddsub: item.RowKey?.ToString());
- //自己写的
- id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, item.tmdId?.ToString(), item.tmdName?.ToString(), item.picture?.ToString(), item.RowKey?.ToString(), item.name?.ToString(), item.avatar?.ToString(), _option.JwtSecretKey, scope: "assist", Website: "BI", roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
- (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);
- }
- else
- {
- return Ok(new { state = 201, ddUserInfos });
- }
- }
- return Ok(new { state = 200, ddUserInfos, id_token, roles, permissions, osblob_uri, osblob_sas });
- }
- else
- {
- DingDingUserInfo dingDingUserInfo = new()
- {
- 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 table.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("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);
- HttpClient httpClient = _http.CreateClient();
- string url = _configuration.GetValue<string>("HaBookAuth:CoreId:userinfo");
- var table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
- var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{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}"))
- {
- 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.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext);
- id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), itemUser.RowKey?.ToString(), itemUser.name?.ToString(), itemUser.avatar?.ToString(), _option.JwtSecretKey, scope: "assist", Website: "BI", roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
- }
- }
- ddUserInfos = await table.UpdateAll(ddUserInfos);
- //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}{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 table = _azureStorage.GetCloudTableClient().GetTableReference("BIDDUserInfo");
- var tempUser = await table.FindListByDict<DingDingUserInfo>(new Dictionary<string, object> { { "PartitionKey", $"{partitionKey}" }, { "RowKey", $"{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
- {
- 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.RowKey}】钉钉账户绑定成功", _dingDing, httpContext: HttpContext);
- }
- else return Ok(new { state = 400, message = "该手机没有注册醍摩豆账号信息" });
- }
- else return Ok(new { state = responseMessage.StatusCode });
- }
- ////在IES5 的基础上增加参数
- //id_token = JwtAuthExtension.CreateAuthToken(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), _option.JwtSecretKey,Website: "BI", scope: $"assist", roles: roles?.ToArray(), permissions: permissions?.ToArray(), ddsub: itemUser.RowKey?.ToString());
- //自己写的
- id_token = JwtAuth.CreateAuthTokenBI(_option.HostName, itemUser.tmdId?.ToString(), itemUser.tmdName?.ToString(), itemUser.picture?.ToString(), itemUser.RowKey?.ToString(), itemUser.name?.ToString(), itemUser.avatar?.ToString(), _option.JwtSecretKey, scope: "assist", Website: "BI", roles: roles?.ToArray(), permissions: permissions?.ToArray(), expire: 3);
- }
- 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; }
- }
- }
- }
|