using Dlhis.Entity.Basic.Entity; using Dlhis.Entity.Sys.Entities; using Kurisu.AspNetCore.Utils.Extensions; using Kurisu.Scheduled; using Kurisu.Scheduled.Attributes; using Kurisu.SqlSugar.Services; using Microsoft.AspNetCore.Identity; namespace Dlhis.ScheduledTask.Jobs; /// /// 用户创建 /// [RecurringJob(nameof(UpdateUserPasswordJob), "0 0 6 * * ?", Name = "用户创建")] public class UpdateUserPasswordJob : BaseJob { public UpdateUserPasswordJob(IServiceProvider serviceProvider) : base(serviceProvider) { } public override async Task RunAsync(IServiceProvider serviceProvider) { 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) { } } } } 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); } } }