This commit is contained in:
2023-05-31 10:19:05 +08:00
parent 1b65a7a9e5
commit 9c621c75cd
238 changed files with 9905 additions and 4034 deletions

View File

@@ -1,7 +1,9 @@
using JNPF.Common.Configuration;
using Aop.Api.Domain;
using JNPF.Common.Configuration;
using JNPF.Common.Const;
using JNPF.Common.Core.Manager;
using JNPF.Common.Core.Manager.Files;
using JNPF.Common.Dtos.OAuth;
using JNPF.Common.Enums;
using JNPF.Common.Extension;
using JNPF.Common.Filter;
@@ -9,27 +11,42 @@ using JNPF.Common.Helper;
using JNPF.Common.Manager;
using JNPF.Common.Models.NPOI;
using JNPF.Common.Models.User;
using JNPF.Common.Options;
using JNPF.Common.Security;
using JNPF.DatabaseAccessor;
using JNPF.DataEncryption;
using JNPF.DependencyInjection;
using JNPF.DynamicApiController;
using JNPF.Extras.DatabaseAccessor.SqlSugar.Models;
using JNPF.FriendlyException;
using JNPF.RemoteRequest.Extensions;
using JNPF.Systems.Entitys.Dto.Organize;
using JNPF.Systems.Entitys.Dto.Role;
using JNPF.Systems.Entitys.Dto.SysConfig;
using JNPF.Systems.Entitys.Dto.User;
using JNPF.Systems.Entitys.Dto.UserRelation;
using JNPF.Systems.Entitys.Enum;
using JNPF.Systems.Entitys.Model.Permission.User;
using JNPF.Systems.Entitys.Permission;
using JNPF.Systems.Entitys.System;
using JNPF.Systems.Interfaces.Permission;
using JNPF.Systems.Interfaces.System;
using Mapster;
using Microsoft.AspNetCore.Authentication.OAuth;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.CodeAnalysis;
using Microsoft.Extensions.Options;
using NPOI.SS.Formula.Eval;
using NPOI.SS.Formula.Functions;
using Org.BouncyCastle.Ocsp;
using Qiniu.Util;
using Senparc.NeuChar.App.AppStore;
using SqlSugar;
using System;
using System.Linq.Expressions;
using System.Security.Principal;
using System.Text.Json.Nodes;
namespace JNPF.Systems;
@@ -40,6 +57,11 @@ namespace JNPF.Systems;
[Route("api/permission/[controller]")]
public class UsersService : IUsersService, IDynamicApiController, ITransient
{
/// <summary>
/// 配置文档.
/// </summary>
private readonly OauthOptions _oauthOptions = App.GetConfig<OauthOptions>("OAuth", true);
/// <summary>
/// 服务基础仓储.
/// </summary>
@@ -80,6 +102,16 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
/// </summary>
private readonly IUserManager _userManager;
/// <summary>
/// SqlSugarClient客户端.
/// </summary>
private SqlSugarScope _sqlSugarClient;
/// <summary>
/// 多租户配置选项.
/// </summary>
private readonly TenantOptions _tenant;
/// <summary>
/// 初始化一个<see cref="UsersService"/>类型的新实例.
/// </summary>
@@ -91,6 +123,8 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
ISynThirdInfoService synThirdInfoService,
ICacheManager cacheManager,
IFileManager fileService,
ISqlSugarClient sqlSugarClient,
IOptions<TenantOptions> tenantOptions,
IUserManager userManager)
{
_repository = userRepository;
@@ -101,6 +135,8 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
_cacheManager = cacheManager;
_synThirdInfoService = synThirdInfoService;
_fileManager = fileService;
_tenant = tenantOptions.Value;
_sqlSugarClient = (SqlSugarScope)sqlSugarClient;
}
#region GET
@@ -140,70 +176,26 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
ErrorStrategy configLockType = (ErrorStrategy)Enum.Parse(typeof(ErrorStrategy), config?.Value);
SqlSugarPagedList<UserListOutput>? data = new SqlSugarPagedList<UserListOutput>();
if (childOrgIds.Any())
{
// 拼接查询
List<ISugarQueryable<UserListOutput>>? listQuery = new List<ISugarQueryable<UserListOutput>>();
foreach (string item in childOrgIds)
{
var quer = _repository.AsSugarClient().Queryable<UserRelationEntity, UserEntity>((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.UserId))
.Where((a, b) => item == a.ObjectId)
.WhereIF(!pageInput.keyword.IsNullOrEmpty(), (a, b) => b.Account.Contains(pageInput.keyword) || b.RealName.Contains(pageInput.keyword))
.WhereIF(!_userManager.IsAdministrator, a => dataScope.Contains(a.ObjectId))
.Where((a, b) => b.DeleteMark == null && !b.Id.Equals("admin"))
.Select((a, b) => new UserListOutput
{
id = b.Id,
account = b.Account,
realName = b.RealName,
headIcon = b.HeadIcon,
creatorTime = b.CreatorTime,
gender = b.Gender,
mobilePhone = b.MobilePhone,
sortCode = b.SortCode,
unLockTime = b.UnLockTime,
enabledMark = b.EnabledMark
});
listQuery.Add(quer);
}
data = await _repository.AsSugarClient().UnionAll(listQuery)
.GroupBy(a => new { a.id, a.account, a.realName, a.creatorTime, a.gender, a.mobilePhone, a.sortCode, a.enabledMark, a.unLockTime })
.Select(a => new UserListOutput
{
id = a.id,
account = a.account,
realName = a.realName,
creatorTime = a.creatorTime,
gender = a.gender,
mobilePhone = a.mobilePhone,
sortCode = a.sortCode,
enabledMark = SqlFunc.IIF(configLockType == ErrorStrategy.Delay && a.enabledMark == 2 && a.unLockTime < DateTime.Now, 1, a.enabledMark)
}).ToPagedListAsync(input.currentPage, input.pageSize);
var userHeadIcon = await _repository.AsQueryable().Where(x => data.list.Select(xx => xx.id).Contains(x.Id)).Select(x => new { Id = x.Id, headIcon = x.HeadIcon }).ToListAsync();
foreach (var item in data.list) item.headIcon = "/api/File/Image/userAvatar/" + userHeadIcon.Find(x => x.Id.Equals(item.id)).headIcon;
}
else
{
data = await _repository.AsSugarClient().Queryable<UserRelationEntity, UserEntity>((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.UserId))
.Where((a, b) => b.DeleteMark == null && !b.Id.Equals("admin"))
.WhereIF(!pageInput.keyword.IsNullOrEmpty(), (a, b) => b.Account.Contains(pageInput.keyword) || b.RealName.Contains(pageInput.keyword))
.WhereIF(!_userManager.IsAdministrator, (a, b) => dataScope.Contains(a.ObjectId))
.OrderBy((a, b) => b.SortCode).OrderBy((a, b) => b.CreatorTime, OrderByType.Desc).OrderBy((a, b) => b.LastModifyTime, OrderByType.Desc)
.GroupBy((a, b) => new { b.Id, b.Account, b.RealName, b.CreatorTime, b.LastModifyTime, b.Gender, b.MobilePhone, b.SortCode, b.EnabledMark, b.UnLockTime })
.Select((a, b) => new UserListOutput
{
id = b.Id,
account = b.Account,
realName = b.RealName,
headIcon = SqlFunc.Subqueryable<UserEntity>().Where(e => e.Id == b.Id).Select(u => SqlFunc.MergeString("/api/File/Image/userAvatar/", u.HeadIcon)),
creatorTime = b.CreatorTime,
gender = b.Gender,
mobilePhone = b.MobilePhone,
sortCode = b.SortCode,
enabledMark = SqlFunc.IIF(configLockType == ErrorStrategy.Delay && b.EnabledMark == 2 && b.UnLockTime < DateTime.Now, 1, b.EnabledMark)
}).ToPagedListAsync(input.currentPage, input.pageSize);
}
data = await _repository.AsSugarClient().Queryable<UserRelationEntity, UserEntity>((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.UserId))
.Where((a, b) => b.DeleteMark == null && !b.Account.Equals("admin"))
.WhereIF(childOrgIds.Any(), (a, b) => childOrgIds.Contains(a.ObjectId))
.WhereIF(!pageInput.keyword.IsNullOrEmpty(), (a, b) => b.Account.Contains(pageInput.keyword) || b.RealName.Contains(pageInput.keyword))
.WhereIF(!_userManager.IsAdministrator, (a, b) => dataScope.Contains(a.ObjectId))
.OrderBy((a, b) => b.SortCode).OrderBy((a, b) => b.CreatorTime, OrderByType.Desc).OrderBy((a, b) => b.LastModifyTime, OrderByType.Desc)
.GroupBy((a, b) => new { b.Id, b.Account, b.RealName, b.CreatorTime, b.LastModifyTime, b.Gender, b.MobilePhone, b.SortCode, b.EnabledMark, b.UnLockTime })
.Select((a, b) => new UserListOutput
{
id = b.Id,
account = b.Account,
realName = b.RealName,
headIcon = SqlFunc.Subqueryable<UserEntity>().Where(e => e.Id == b.Id).Select(u => SqlFunc.MergeString("/api/File/Image/userAvatar/", u.HeadIcon)),
creatorTime = b.CreatorTime,
gender = b.Gender,
mobilePhone = b.MobilePhone,
sortCode = b.SortCode,
enabledMark = SqlFunc.IIF(configLockType == ErrorStrategy.Delay && b.EnabledMark == 2 && b.UnLockTime < DateTime.Now, 1, b.EnabledMark)
}).ToPagedListAsync(input.currentPage, input.pageSize);
#region
@@ -214,11 +206,8 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
// 获取用户组织集合
item.organizeList = orgUserIdAll.Where(x => x.UserId == item.id).Select(x => x.ObjectId).ToList();
item.organize = string.Join(" ; ", orgTreeNameList.Where(x => item.organizeList.Contains(x.Id)).Select(x => x.Description));
item.sortCode = 999;
if (item.organizeList.Contains(input.organizeId)) item.sortCode = 0;
}
data.list = data.list.OrderBy(x => x.sortCode).ToList();
#endregion
return PageResult<UserListOutput>.SqlSugarPageResult(data);
@@ -323,8 +312,7 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
.Where((a, b) => b.ObjectType == "Organize" && orgList.Contains(b.ObjectId)).Where((a, b) => a.EnabledMark == 1 && a.DeleteMark == null)
.Where((a, b) => a.RealName.Contains(input.keyword) || a.Account.Contains(input.keyword))
.GroupBy((a, b) => new { a.Id, a.RealName, a.Account, a.EnabledMark })
.Select((a, b) => new
{
.Select((a, b) => new {
id = a.Id,
fullName = SqlFunc.MergeString(a.RealName, "/", a.Account),
enabledMark = a.EnabledMark,
@@ -369,8 +357,7 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
var res = await _repository.AsSugarClient().Queryable<UserEntity, UserRelationEntity>((a, b) => new JoinQueryInfos(JoinType.Left, b.UserId == a.Id))
.Where((a, b) => b.ObjectType == "Organize" && b.ObjectId == input.organizeId).Where((a, b) => a.EnabledMark == 1 && a.DeleteMark == null)
.GroupBy((a, b) => new { a.Id, a.RealName, a.Account, a.EnabledMark })
.Select((a, b) => new
{
.Select((a, b) => new {
id = a.Id,
fullName = SqlFunc.MergeString(a.RealName, "/", a.Account),
enabledMark = a.EnabledMark,
@@ -527,6 +514,24 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
#region POST
/// <summary>
/// 根据用户Id List 获取当前用户Id.
/// </summary>
/// <returns></returns>
[HttpPost("getDefaultCurrentValueUserId")]
public async Task<dynamic> GetDefaultCurrentValueUserId([FromBody] GetDefaultCurrentValueInput input)
{
if ((input.UserIds == null || !input.UserIds.Any()) && (input.DepartIds == null || !input.DepartIds.Any()) && (input.PositionIds == null || !input.PositionIds.Any())
&& (input.RoleIds == null || !input.RoleIds.Any()) && (input.GroupIds == null || !input.GroupIds.Any())) return new { userId = _userManager.UserId };
var userRelationList = _repository.AsSugarClient().Queryable<UserRelationEntity>().Select(x => new UserRelationEntity() { UserId = x.UserId, ObjectId = x.ObjectId }).ToList();
var userIdList = userRelationList.Where(x => input.UserIds.Contains(x.UserId) || input.DepartIds.Contains(x.ObjectId)
|| input.PositionIds.Contains(x.ObjectId) || input.RoleIds.Contains(x.ObjectId) || input.GroupIds.Contains(x.ObjectId)).Select(x => x.UserId).ToList();
if (userIdList.Contains(_userManager.UserId)) return new { userId = _userManager.UserId };
else return new { userId = string.Empty };
}
/// <summary>
/// 获取.
/// </summary>
@@ -534,16 +539,14 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
[HttpPost("GetUserList")]
public async Task<dynamic> GetUserList([FromBody] UserRelationInput input)
{
var data = await _repository.AsSugarClient().Queryable<UserEntity, OrganizeEntity>((u, org) => new JoinQueryInfos(JoinType.Inner, u.OrganizeId == org.Id))
.Where((u, org) => u.EnabledMark > 0 && u.DeleteMark == null)
.Where((u, org) => input.userId.Contains(u.Id))
.Select((u, org) => new OrganizeMemberListOutput()
var data = await _repository.AsQueryable().Where(it => it.EnabledMark > 0 && it.DeleteMark == null)
.Where(it => input.userId.Contains(it.Id))
.Select(it => new OrganizeMemberListOutput()
{
id = u.Id,
fullName = SqlFunc.MergeString(u.RealName, "/", u.Account),
headIcon = SqlFunc.MergeString("/api/File/Image/userAvatar/", u.HeadIcon),
enabledMark = u.EnabledMark,
type = org.FullName,
id = it.Id,
fullName = SqlFunc.MergeString(it.RealName, "/", it.Account),
headIcon = SqlFunc.MergeString("/api/File/Image/userAvatar/", it.HeadIcon),
enabledMark = it.EnabledMark,
}).ToListAsync();
data = data.OrderBy(x => input.userId.IndexOf(x.id)).ToList();
@@ -561,6 +564,7 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
var oids = userList.Where(x => x.UserId.Equals(item.id)).Select(x => x.ObjectId).ToList();
var oTree = orgList.Where(x => oids.Contains(x.Id)).Select(x => x.Description).ToList();
item.organize = string.Join(",", oTree);
//item.type = org.fullName;
});
}
@@ -804,15 +808,12 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
if (input.roleIds != null) input.departIds.AddRange(input.roleIds);
if (input.groupIds != null) input.departIds.AddRange(input.groupIds);
if (!input.departIds.Any()) return PageResult<UserListOutput>.SqlSugarPageResult(data);
data = await _repository.AsSugarClient().Queryable<UserRelationEntity, UserEntity>((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.UserId))
var ids = await _repository.AsSugarClient().Queryable<UserRelationEntity, UserEntity>((a, b) => new JoinQueryInfos(JoinType.Left, b.Id == a.UserId))
.Where((a, b) => b.DeleteMark == null)
.WhereIF(input.departIds.Any() || input.userIds.Any(), (a, b) => input.departIds.Contains(a.ObjectId) || input.userIds.Contains(b.Id))
.WhereIF(input.pagination.keyword.IsNotEmptyOrNull(), (a, b) => b.Account.Contains(input.pagination.keyword) || b.RealName.Contains(input.pagination.keyword))
.Select((a, b) => new UserListOutput()
{
id = b.Id
}).Distinct().ToPagedListAsync(input.pagination.currentPage, input.pagination.pageSize);
data = await _repository.AsQueryable().Where(x => data.list.Select(xx => xx.id).Contains(x.Id)).Select(x => new UserListOutput()
.Select((a, b) => b.Id).Distinct().ToListAsync();
data = await _repository.AsQueryable().Where(x => ids.Contains(x.Id)).Select(x => new UserListOutput()
{
id = x.Id,
organizeId = x.OrganizeId,
@@ -821,8 +822,7 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
headIcon = SqlFunc.MergeString("/api/File/Image/userAvatar/", x.HeadIcon),
gender = x.Gender,
mobilePhone = x.MobilePhone
}).ToPagedListAsync(1, input.pagination.pageSize);
}).ToPagedListAsync(input.pagination.currentPage, input.pagination.pageSize);
if (data.list.Any())
{
var orgList = _organizeService.GetOrgListTreeName();
@@ -1075,6 +1075,9 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
}
#endregion
// 单点登录同步
await syncUserInfo(entity, "create", _userManager.TenantId);
}
catch (Exception)
{
@@ -1130,6 +1133,9 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
}
#endregion
// 单点登录同步
await syncUserInfo(entity, "delete", _userManager.TenantId);
}
/// <summary>
@@ -1142,6 +1148,7 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
public async Task Update(string id, [FromBody] UserUpInput input)
{
UserEntity? oldUserEntity = await _repository.GetFirstAsync(it => it.Id == id);
input.roleId = input.roleId == null ? string.Empty : input.roleId;
// 超级管理员 只有 admin 账号才有变更权限
if (_userManager.UserId != oldUserEntity.Id && oldUserEntity.IsAdministrator == 1 && _userManager.Account != "admin")
@@ -1233,8 +1240,7 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
try
{
// 更新用户记录
int newEntity = await _repository.AsUpdateable(entity).UpdateColumns(it => new
{
int newEntity = await _repository.AsUpdateable(entity).UpdateColumns(it => new {
it.Account,
it.RealName,
it.QuickQuery,
@@ -1315,6 +1321,9 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
}
#endregion
// 单点登录同步
await syncUserInfo(entity, "update", _userManager.TenantId);
}
/// <summary>
@@ -1372,7 +1381,9 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
if (!(isOk > 0)) throw Oops.Oh(ErrorCode.D5005);
// 强制将用户提掉线
// 单点登录同步
entity.Password = input.userPassword;
await syncUserInfo(entity, "modifyPassword", _userManager.TenantId);
}
/// <summary>
@@ -1794,6 +1805,8 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
#endregion
#region PrivateMethod
/// <summary>
/// 获取集合中的组织 树,根据上级ID.
/// </summary>
@@ -2256,5 +2269,244 @@ public class UsersService : IUsersService, IDynamicApiController, ITransient
return output;
}
#endregion
#region
/// <summary>
/// 同步数据导maxkey.
/// </summary>
/// <param name="userEntity"></param>
/// <param name="method"></param>
/// <param name="tenantId"></param>
public async Task syncUserInfo(UserEntity userEntity, string method, string tenantId)
{
try
{
if (_oauthOptions.Enabled)
{
var userName = string.Format("{0}:{1}", _oauthOptions.Pull.UserName, _oauthOptions.Pull.Password).ToBase64String();
// http调用结果
HttpResponse execute = null;
var map = parse(userEntity);
tenantId = tenantId != null && tenantId.Length > 0 ? tenantId : "1";
if (tenantId.Equals("default")) tenantId = "1";
map.Add("instId", tenantId);
// 得到userId
// String username = userEntity.get("id") != null && userEntity.get("id").toString().length() > 0 ? userEntity.get("id").toString() : null;
Dictionary<string, object> jsonObject = null;
var resString = string.Empty;
var headers = new Dictionary<string, object>();
headers.Add("Authorization", _oauthOptions.Pull.CredentialType + " " + userName);
if (method.Equals("create"))
{
resString = await (_oauthOptions.Pull.CreateRestAddress + "?appId=" + _oauthOptions.Pull.UserName).SetHeaders(headers).SetBody(map).PostAsStringAsync();
}
else if (method.Equals("update"))
{
resString = await (_oauthOptions.Pull.ReplaceRestAddress + "?appId=" + _oauthOptions.Pull.UserName).SetHeaders(headers).SetBody(map).PutAsStringAsync();
}
else if (method.Equals("delete"))
{
resString = await (_oauthOptions.Pull.DeleteRestAddress + "?appId=" + _oauthOptions.Pull.UserName).SetHeaders(headers).SetBody(map).DeleteAsStringAsync();
}
else if (method.Equals("modifyPassword"))
{
resString = await (_oauthOptions.Pull.ChangePasswordRestAddress + "?appId=" + _oauthOptions.Pull.UserName).SetHeaders(headers).SetBody(map).PostAsStringAsync();
}
// else if (method.Equals("modifyPassword")) {
// jsonObject = HttpUtil.httpRequest(_oauthOptions.Pull.getGetRestAddress() + username
// , "GET"
// , null, _oauthOptions.Pull.getCredentialType() + " " + _oauthOptions.Pull.getUserName() + "Og==" + _oauthOptions.Pull.getPassword()
// , null);
// }
}
}
catch (Exception e)
{
}
}
private Dictionary<string, object> parse(UserEntity userEntity)
{
var map = new Dictionary<string, object>();
// map.Add("id", userEntity.get("id"));
map.Add("username", userEntity.Account);
map.Add("password", userEntity.Password);
map.Add("mobile", userEntity.MobilePhone);
map.Add("email", userEntity.Email);
map.Add("gender", (int)userEntity.Gender == 1 ? 2 : 1);
map.Add("createdBy", userEntity.CreatorUserId);
map.Add("createdDate", userEntity.CreatorTime);
map.Add("modifiedBy", userEntity.LastModifyUserId);
map.Add("modifiedDate", userEntity.LastModifyTime);
map.Add("displayName", userEntity.RealName);
// map.Add("managerId", userEntity.get("managerId"));
// map.Add("departmentId", userEntity.get("organizeId"));
map.Add("loginCount", userEntity.LogSuccessCount);
map.Add("badPasswordCount", userEntity.LogErrorCount);
map.Add("lastLoginIp", userEntity.LastLogIP);
map.Add("lastLoginTime", userEntity.LastLogTime);
map.Add("status", userEntity.EnabledMark != null ? (userEntity.EnabledMark == 1 ? 1 : 4) : 4);
return map;
}
/// <summary>
/// 根据单点服务端消息 同步用户信息到数据库.
/// </summary>
/// <param name="message"></param>
[NonAction]
public async Task<bool> Receive(string message)
{
bool isSuccess;
var map = new Dictionary<string, object>();
try
{
var mqMessage = message.ToObject<MqMessage>();
// 转成用户实体类
var userInfo = mqMessage.content.ToObject<UserInfo>();
var userEntity = new UserEntity();
userEntity.Id = userInfo.id;
userEntity.Account = userInfo.username;
userEntity.MobilePhone = userInfo.mobile;
userEntity.Email = userInfo.email;
userEntity.Gender = userInfo.gender;
userEntity.CreatorTime = userInfo.createdDate.IsNullOrWhiteSpace() ? null : userInfo.createdDate?.ParseToLong().TimeStampToDateTime();
userEntity.CreatorUserId = userInfo.createdBy;
userEntity.LastModifyUserId = userInfo.modifiedBy;
userEntity.LastModifyTime = userInfo.modifiedDate.IsNullOrWhiteSpace() ? null : userInfo.modifiedDate?.ParseToLong().TimeStampToDateTime();
userEntity.RealName = userInfo.displayName;
userEntity.LogSuccessCount = userInfo.loginCount;
userEntity.LogErrorCount = userInfo.badPasswordCount;
userEntity.LastLogIP = userInfo.lastLoginIp;
userEntity.LastLogTime = userInfo.lastLoginTime.IsNullOrWhiteSpace() ? null : userInfo.lastLoginTime?.ParseToLong().TimeStampToDateTime();
userEntity.EnabledMark = userInfo.status == 1 ? 1 : 0;
userEntity.HeadIcon = "001.png";
if (_tenant.MultiTenancy)
{
ConnectionConfigOptions options = new ConnectionConfigOptions();
var interFace = string.Format("{0}{1}", _tenant.MultiTenancyDBInterFace, userInfo.instId);
var response = interFace.GetAsStringAsync().Result;
var result = response.ToObject<UnifyResult.RESTfulResult<TenantInterFaceOutput>>();
if (result.code != 200)
{
throw Oops.Oh(result.msg);
}
else if (result.data.dotnet == null && result.data.linkList == null)
{
throw Oops.Oh(ErrorCode.D1025);
}
else
{
if (result.data.linkList == null || result.data.linkList?.Count == 0)
{
options = JNPFTenantExtensions.GetLinkToOrdinary(userInfo.instId, result.data.dotnet);
}
else if (result.data.dotnet == null)
{
options = JNPFTenantExtensions.GetLinkToCustom(userInfo.instId, result.data.linkList);
}
}
if (!"default".Equals(userInfo.instId) && _tenant.MultiTenancyType.Equals("COLUMN"))
{
_sqlSugarClient.QueryFilter.AddTableFilter<ITenantFilter>(it => it.TenantId == userInfo.instId);
}
else
{
_sqlSugarClient.AddConnection(JNPFTenantExtensions.GetConfig(options));
_sqlSugarClient.ChangeDatabase(userInfo.instId);
}
}
isSuccess = await process(userEntity, mqMessage.actionType, userInfo.instId);
}
catch (Exception e)
{
// _logger.error("同步用户失败", e);
isSuccess = false;
}
if (!isSuccess)
{
// _logger.info("消息消费失败:" + message);
}
else
{
// _logger.debug("同步用户信息, {}", JSONObject.toJSONString(map));
}
return isSuccess;
}
/// <summary>
/// 保存到数据库处理逻辑.
/// </summary>
/// <param name="actionType"></param>
/// <param name="instId"></param>
/// <returns></returns>
private async Task<bool> process(UserEntity entity, string actionType, string instId)
{
if (actionType.Equals("CREATE_ACTION"))
{
if (_sqlSugarClient.Queryable<UserEntity>().Any(x => x.Account.Equals(entity.Account) && x.DeleteMark == null)) return true;
entity.Secretkey = Guid.NewGuid().ToString();
entity.Password = MD5Encryption.Encrypt(MD5Encryption.Encrypt(CommonConst.DEFAULTPASSWORD) + entity.Secretkey);
UserRelationEntity? entityRelation = new UserRelationEntity();
entityRelation.Id = SnowflakeIdHelper.NextId();
entityRelation.ObjectType = "Organize";
entityRelation.ObjectId = _sqlSugarClient.Queryable<OrganizeEntity>().First(x => x.ParentId.Equals("-1")).Id;
entityRelation.SortCode = 0;
entityRelation.UserId = entity.Id;
entityRelation.CreatorTime = DateTime.Now;
entityRelation.CreatorUserId = entity.CreatorUserId;
_sqlSugarClient.Insertable(entityRelation).ExecuteCommand(); // 批量新增用户关系
// 新增用户记录
return await _sqlSugarClient.Insertable(entity).CallEntityMethod(m => m.Create()).IgnoreColumns(ignoreNullColumn: true).ExecuteCommandAsync() > 0;
}
else if (actionType.Equals("UPDATE_ACTION"))
{
var oldEntity = await _sqlSugarClient.Queryable<UserEntity>().FirstAsync(x => x.Account.Equals(entity.Account) && x.DeleteMark == null);
entity.Id = oldEntity.Id;
return await _sqlSugarClient.Updateable(entity).CallEntityMethod(m => m.LastModify()).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync() > 0;
}
else if (actionType.Equals("DELETE_ACTION"))
{
var oldEntity = await _sqlSugarClient.Queryable<UserEntity>().FirstAsync(x => x.Account.Equals(entity.Account) && x.DeleteMark == null);
oldEntity.EnabledMark = 0;
// 同步删除用户 只能 该状态为 禁用
return await _sqlSugarClient.Updateable(oldEntity).CallEntityMethod(m => m.LastModify()).IgnoreColumns(ignoreAllNullColumns: true).ExecuteCommandAsync() > 0;
}
else if (actionType.Equals("PASSWORD_ACTION"))
{
return await _sqlSugarClient.Updateable<UserEntity>().SetColumns(it => new UserEntity()
{
Password = entity.Password,
ChangePasswordDate = SqlFunc.GetDate(),
LastModifyUserId = _userManager.UserId,
LastModifyTime = SqlFunc.GetDate()
}).Where(it => it.Id == entity.Id).ExecuteCommandAsync() > 0;
}
else
{
//_logger.info("Other Action , will sikp it ...");
}
return true;
}
#endregion
}