using Dlhis.Constants; using Dlhis.Entity.Sys.Entities; using Kurisu.AspNetCore.DataAccess.SqlSugar.Services; using Kurisu.AspNetCore.Utils.Extensions; using Microsoft.AspNetCore.Identity; namespace Dlhis.Basic.Organization.Services.Implements; public class IdentityUserSyncService : IIdentityUserSyncService { private readonly IDbContext _identityDbContext; public IdentityUserSyncService(IDbContext dbContext) { _identityDbContext = dbContext.ChangeDb("identity"); } /// public async Task SyncAccountAsync(string userName, string name, string idNo, string tenant) { if (tenant.IsEmpty()) return; try { var password = idNo.TakeLast(6).Join(""); var user = await _identityDbContext.Queryable().SingleAsync(x => x.UserName == userName); if (user == null) { var hasher = new PasswordHasher(); user = new UserEntity { UserName = userName, NormalizedUserName = userName.ToUpper(), ConcurrencyStamp = Guid.NewGuid().ToString(), SecurityStamp = Guid.NewGuid().ToString(), LockoutEnabled = true }; password = hasher.HashPassword(user, password); user.PasswordHash = password; var id = (int)await _identityDbContext.InsertReturnIdentityAsync(user); user.Id = id; await AddUserClaim(_identityDbContext, id, UserClaimConstants.JinkoCode, userName); await AddUserClaim(_identityDbContext, id, "name", name); } user.LockoutEnd = null; //todo 考虑角色? var userTenants = await _identityDbContext.Queryable().Where(x => x.UserId == user.Id).ToListAsync(); if (userTenants.Count is 0 or 1) { var userTenant = userTenants.FirstOrDefault(); if (userTenant == null) { userTenant = new UserTenantEntity { UserId = user.Id, TenantCode = tenant }; await _identityDbContext.InsertAsync(userTenant); } else { userTenant.TenantCode = tenant; await _identityDbContext.UpdateAsync(userTenant); } } } catch (Exception) { //ignore } } /// public async Task LockAccountAsync(string userName) { var user = await _identityDbContext.Queryable().Where(x => x.UserName == userName).SingleAsync(); if (user != null) { user.LockoutEnabled = true; user.LockoutEnd = new DateTime(2099, 12, 31); await _identityDbContext.UpdateAsync(user); } } //************************************************************************** help method ************************************************************************************** private async Task AddUserClaim(IDbContext dbContext, int userId, string type, string value) { var claim = await _identityDbContext.Queryable().Where(x => x.UserId == userId).FirstAsync(x => x.ClaimType == type); if (claim == null) { claim = new UserClaimEntity() { UserId = userId, ClaimType = type, ClaimValue = value }; await dbContext.InsertAsync(claim); } else { claim.ClaimValue = value; await dbContext.UpdateAsync(claim); } } }