Implement a `UserWithProfileManager` to automatically create a default user profile upon user registration. This ensures that each user has an associated profile with default values (e.g., `UserName`, `IsAdmin`, `IsDeleted`). Updates the database schema to reflect the change from UserId to UserProfileId in the UserProfileCompanyTableStat and UserProfileProductTableStat entities.
52 lines
No EOL
1.6 KiB
C#
52 lines
No EOL
1.6 KiB
C#
using DrinkRateAPI.Contexts;
|
|
using Microsoft.AspNetCore.Identity;
|
|
using Microsoft.Extensions.Options;
|
|
|
|
namespace DrinkRateAPI.DbEntities;
|
|
|
|
public class DbApplicationUser : IdentityUser<Guid>
|
|
{
|
|
public virtual DbUserProfile UserProfile { get; set; }
|
|
}
|
|
|
|
public class UserWithProfileManager : UserManager<DbApplicationUser>
|
|
{
|
|
private readonly ApplicationDbContext _context;
|
|
|
|
public UserWithProfileManager(
|
|
IUserStore<DbApplicationUser> store,
|
|
IOptions<IdentityOptions> optionsAccessor,
|
|
IPasswordHasher<DbApplicationUser> passwordHasher,
|
|
IEnumerable<IUserValidator<DbApplicationUser>> userValidators,
|
|
IEnumerable<IPasswordValidator<DbApplicationUser>> passwordValidators,
|
|
ILookupNormalizer keyNormalizer,
|
|
IdentityErrorDescriber errors,
|
|
IServiceProvider services,
|
|
ILogger<UserManager<DbApplicationUser>> logger,
|
|
ApplicationDbContext context)
|
|
: base(store, optionsAccessor, passwordHasher, userValidators,
|
|
passwordValidators, keyNormalizer, errors, services, logger)
|
|
{
|
|
_context = context;
|
|
}
|
|
|
|
public override async Task<IdentityResult> CreateAsync(DbApplicationUser user, string password)
|
|
{
|
|
var result = await base.CreateAsync(user, password);
|
|
if (!result.Succeeded)
|
|
return result;
|
|
|
|
var newProfile = new DbUserProfile
|
|
{
|
|
ApplicationUser = user,
|
|
UserName = $"User_{user.Id}",
|
|
IsAdmin = false,
|
|
IsDeleted = false
|
|
};
|
|
|
|
await _context.UserProfiles.AddAsync(newProfile);
|
|
await _context.SaveChangesAsync();
|
|
|
|
return result;
|
|
}
|
|
} |