using Dlhis.Entity.Basic.Entity; using Dlhis.Entity.Sys.Entities; using Kurisu.AspNetCore.Utils.Extensions; using Kurisu.Core.DataAccess.Entity; using Kurisu.SqlSugar.Services; using Microsoft.AspNetCore.Identity; namespace Dlhis.ScheduledTask.CommonJobs; public class UpdateUserPasswordJob { private readonly IDbContext _dbContext; private readonly ILogger _logger; public UpdateUserPasswordJob( IDbContext dbContext, ILogger logger) { _dbContext = dbContext; _logger = logger; } public async Task RunAsync() { _dbContext.Client.QueryFilter.ClearAndBackup(); try { var identityDbContext = _dbContext.ChangeDb("identity"); var whitelist = new List() { "admin", "WB-0741", "WB-1091", "0123456" }; var users = await identityDbContext.Queryable() .Where(x => !whitelist.Contains(x.UserName)) .ToListAsync(); var gainfos = await _dbContext.Queryable().Where(x => !whitelist.Contains(x.Code)).ToListAsync(); var hasher = new PasswordHasher(); foreach (var gainfo in gainfos) { if (gainfo.IdNo.IsPresent()) { try { var password = gainfo.IdNo.TakeLast(6).Join(""); var user = users.FirstOrDefault(x => x.UserName == gainfo.Code); if (user == null) { user = new UserEntity { UserName = gainfo.Code, NormalizedUserName = gainfo.Code.ToUpper(), ConcurrencyStamp = Guid.NewGuid().ToString(), SecurityStamp = Guid.NewGuid().ToString(), }; password = hasher.HashPassword(user, password); user.PasswordHash = password; var id = (int)await identityDbContext.InsertReturnIdentityAsync(user); await AddUserClaim(identityDbContext, id, "jinko-code", gainfo.Code); await AddUserClaim(identityDbContext, id, "name", gainfo.Name); if (!string.IsNullOrEmpty(gainfo.Factory)) { var userTenant = await identityDbContext.Queryable().Where(x => x.UserId == user.Id).FirstAsync(); if (userTenant == null) { userTenant = new UserTenantEntity { UserId = user.Id, TenantCode = gainfo.Factory }; await identityDbContext.InsertAsync(userTenant); } else { userTenant.TenantCode = gainfo.Factory; await identityDbContext.UpdateAsync(userTenant); } } } else { password = hasher.HashPassword(user, password); user.PasswordHash = password; await identityDbContext.UpdateAsync(user); } } catch (Exception) { } } } } catch (Exception ex) { _logger.LogError(ex, "密码修改失败:{message}", ex.Message); } finally { _dbContext.Client.QueryFilter.Restore(); } } private async Task AddUserClaim(IDbContext dbContext, int userId, string type, string value) { var claim = await dbContext.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); } } }