Files
jinko.yikatong/Src/Dlhis.ScheduledTask/Jobs/UpdateUserPasswordJob.cs

112 lines
4.2 KiB
C#

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;
/// <summary>
/// 用户创建
/// </summary>
[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<string>() { "admin", "WB-0741", "WB-1091", "0123456" };
var users = await identityDbContext.Queryable<UserEntity>()
.Where(x => !whitelist.Contains(x.UserName))
.ToListAsync();
var gainfos = await DbContext.Queryable<GainfoEntity>().Where(x => !whitelist.Contains(x.Code)).ToListAsync();
var hasher = new PasswordHasher<UserEntity>();
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<UserTenantEntity>().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<UserClaimEntity>().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);
}
}
}