using System.Threading.Tasks; using Microsoft.AspNetCore.Identity; using xCommons.Extensions; using xExceptions.Constants; using xIdentityModels.Descriptors; using xIdentityModels.Extensions; namespace xIds.Providers { public partial class XIdentityManager { // #region Default Identity Preparation Actions ... /// /// Create Default Roles based on Identity Configuration /// /// public async Task CreateIdentityRoles() { // if (Configuration == null || Configuration.IdentityRoles == null || Configuration.IdentityRoles.Count == 0) { return; } // // Check New Users Role exists in IdentityRole or not ... if (!Configuration.NewUsersRole.IsNullOrEmpty()) { // // Ensure NewUsersRole Exists in IdentityRoles ... var isNewUserRoleExistsInIdentityRoles = Configuration .IdentityRoles .Contains(Configuration.NewUsersRole); if (!isNewUserRoleExistsInIdentityRoles) { XException.InvalidArgs.Throw(); } } // // loop through all roles and create them one by one ... foreach (var roleName in Configuration.IdentityRoles) { // var isRoleExists = await RoleManager.RoleExistsAsync(roleName); if (!isRoleExists) { // var result = await RoleManager.CreateAsync(new IdentityRole(roleName)); } } } /// /// Create a user Based on User Descriptor /// /// an instance of XIdentityUserDescriptor /// public async Task CreateUserAsync( XIdentityUserDescriptor user ) { // // Validate Args ... ValidationProvider.NotNull(user); // var isExistsRole = await RoleManager.RoleExistsAsync(user.Role); if (!isExistsRole) { // // Check Assigned role to user exists in app roles ... if (!Configuration .IdentityRoles .Contains(user.Role)) { XException.InvalidArgs.Throw(); } // // Ensure All Roles Created ... await CreateIdentityRoles(); } // // Check User Exists ... var isExistsUser = await IsUserExistsAsync(user.UserName); if (!isExistsUser) { // // Create a DashboardUser instance based on Configuration Data ... var userEntity = user.ToXUser(); // // Try to Create User ... var userCreateResult = await CreateUserAsync( userEntity, user.Password ); if (!userCreateResult.Succeeded) { XException.ActionFailed.Throw(); } // // Assign Admin User to it's Role ... var roleAssignResult = await UserManager.AddToRoleAsync(userEntity, user.Role); if (!roleAssignResult.Succeeded) { XException.ActionFailed.Throw(); } // var claims = await ToJwtClaims( userEntity, checkCanLoginPolicies: true, checkIsBanned: true); // var addClaimsResult = await UserManager.AddClaimsAsync(userEntity, claims); if (!addClaimsResult.Succeeded) { XException.ActionFailed.Throw(); } } } #endregion } }