Base solution for your next web application
Open Closed

Create user from backend - assign to default role not working #10754


User avatar
0
pliaspzero created

Prerequisites

Please answer the following questions before submitting an issue. YOU MAY DELETE THE PREREQUISITES SECTION.

  • What is your product version?
  • What is your product type (Angular or MVC)? Angular
  • What is product framework type (.net framework or .net core)? .net core

If issue related with ABP Framework

  • What is ABP Framework version?

If issue is about UI

  • Which theme are you using?
  • What are the theme settings?

I try to create user from backend with code automatically - and assign to default role.

Is this correkt like this?

Thanks for a hint - currently it seems not working. ( result = await _userManager.SetRolesAsync(user, role);)

                        //get Employee role value for existing & create new if not existing
                        IQueryable<Role> query = _roleManager.Roles;
                        Role roleExists = GetRole(query);
                        string roleName="";

                        if (roleExists != null)
                        {
                            try
                            { 
                            roleName = query.ToList().FirstOrDefault(x => x.IsDefault == true).Name;
                            Logger.Info("roleName = query.ToList().FirstOrDefault(x => x.IsDefault == true).Name");
                            }
                            catch(Exception ex)
                            {
                                Logger.Error(ex.Message.ToString());
                            }
                        }
                        else
                        {
                            Role newRole = new Role(tenantId, "Employee") { IsDefault = false, Name = "Employee" };
                            CheckErrors(await _roleManager.CreateAsync(newRole));
                            await CurrentUnitOfWork.SaveChangesAsync();
                            roleExists = GetRole(query);
                            roleName = roleExists.Name;
                            Logger.Info("Role newRole = new Role(tenantId");
                        }

                        string[] role = new string[] { roleName };
                        result = await _userManager.SetRolesAsync(user, role);
                        Logger.Info("await _userManager.SetRolesAsync(user, role)");

                        if (!result.Succeeded)
                        {
                            throw new UserFriendlyException(L("UserRollNotAssigned"));
                        }

4 Answer(s)
  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @pliaspzero

    Your approach seems fine. Could you share the entire class ? We can try to reproduce this on our side.

    Thanks,

  • User Avatar
    0
    pliaspzero created

    Maybe it searches in host - not in Tenant?

    But here the whole code:

                // Find user in our database 
                using (CurrentUnitOfWork.DisableFilter(AbpDataFilters.MayHaveTenant))
                {
                    Logger.Info("CurrentUnitOfWork.SetTenantId(tenantId) - Success: TenantId = " + tenantId.ToString());
    
                    // Step 1: FindByEmailAsync
                    user = await _userManager.FindByEmailAsync(userSSO);
                    if (user != null)
                    {
                        Logger.Info("Find user in our database successful (FindByEmailAsync): " + user.UserName);
                    }
    
                    // Step 2: FindByNameAsync
                    if (user == null)
                    {
                        user = await _userManager.FindByNameAsync(userSSO);
                        if (user != null)
                        {
                            Logger.Info("Find user in our database successful (FindByNameAsync): " + user.UserName);
                        }
                    }
                    // }
                    using (CurrentUnitOfWork.SetTenantId(tenantId))
                    {
                        if (user == null)
                        {
    
                            Logger.Info("user == null");
    
                            string fName;
                            string lName;
    
                            if (ssoResult.UserID.Contains("@"))
                            {
                                int indexOf = ssoResult.UserID.IndexOf("@");
                                fName = ssoResult.UserID.Substring(0, indexOf);
                                lName = ssoResult.UserID.Substring(indexOf + 1);
                                Logger.Info("ssoResult.UserID.Contains @");
                            }
                            // LDAP User
                            else if (ssoResult.UserID.Contains("\\"))
                            {
                                int indexOf = ssoResult.UserID.IndexOf("\\");
                                fName = ssoResult.UserID.Substring(0, indexOf);
                                lName = ssoResult.UserID.Substring(indexOf + 1);
                                Logger.Info("ssoResult.UserID.Contains \\");
                            }
                            else
                            {
                                fName = ssoResult.UserID;
                                lName = ssoResult.UserID;
                                Logger.Info("ssoResult - else");
                            }
    
    
                            string newPassword = _passwordHasher.HashPassword(user, _appConfiguration["PLI_SsoSettings:SSOUserPassword"]);
                            user = new User
                            {
                                EmailAddress = userNameOrEmail,
                                IsEmailConfirmed = true,
                                Name = fName,
                                Surname = lName,
                                UserName = userSSO,
                                Password = newPassword, //hashPassword
                                TenantId = tenantId
                            };
    
                            // If the user doesn't exist locally then create the user.
                            IdentityResult result = await _userManager.CreateAsync(user);
    
                            if (!result.Succeeded)
                            {
                                Logger.Info("IdentityResult result = await _userManager.CreateAsync(user) = UserNotCreated");
                                throw new UserFriendlyException(L("UserNotCreated"));
                            }
                            else
                            {
                                Logger.Info("user = new User created - UserName: " + userSSO + " TenantId: " + tenantId.ToString());
                            }
    
                            //get Employee role value for existing & create new if not existing
                            IQueryable<Role> query = _roleManager.Roles;
                            Role roleExists = GetRole(query);
                            string roleName="";
    
                            if (roleExists != null)
                            {
                                try
                                { 
                                roleName = query.ToList().FirstOrDefault(x => x.IsDefault == true).Name;
                                Logger.Info("roleName = query.ToList().FirstOrDefault(x => x.IsDefault == true).Name");
                                }
                                catch(Exception ex)
                                {
                                    Logger.Error(ex.Message.ToString());
                                }
                            }
                            else
                            {
                                Role newRole = new Role(tenantId, "Employee") { IsDefault = false, Name = "Employee" };
                                CheckErrors(await _roleManager.CreateAsync(newRole));
                                await CurrentUnitOfWork.SaveChangesAsync();
                                roleExists = GetRole(query);
                                roleName = roleExists.Name;
                                Logger.Info("Role newRole = new Role(tenantId");
                            }
    
                            string[] role = new string[] { roleName };
                            result = await _userManager.SetRolesAsync(user, role);
                            Logger.Info("await _userManager.SetRolesAsync(user, role)");
    
                            if (!result.Succeeded)
                            {
                                throw new UserFriendlyException(L("UserRollNotAssigned"));
                            }
                        }
                        //}
    
                        else
                        {
                            await _userManager.ChangePasswordAsync(user, _appConfiguration["PLI_SsoSettings:SSOUserPassword"]);
                        }
    
                        // OM: ASYNC would be good
                        CallPRSUserAPI(tenantId, userSSO, userSSOOriginal);
    
                        string allowedURLList = _appConfiguration["PLI_SsoSettings:AllowedURLList"];
    
                        //  var list = .Spli    t(",");
                        var allowedURL = allowedURLList.Split(',').ToList();
    
                        //this line create a arraylist using array elements.
                        //  var fileList = new List(stringArray);
                        var str = allowedURL.Any(url => (ssoResult.RelayState).Contains(url));
                        // Add new SP-Providers here 
                        if (str)
                        {
                            Dictionary<string, string> queryParams = new Dictionary<string, string>()
                                                    {
                                                        {"tenantId", tenantId.ToString()},
                                                        {"isSSORequest", "true"},
                                                        {"userEmailId", userNameOrEmail },
                                                        {"returnUrl", ssoResult.RelayState }
                                                    };
                            Logger.Info("Redirect starts to: " + ssoResult.RelayState);
    
                            return Redirect(QueryHelpers.AddQueryString(ssoResult.RelayState, queryParams));
                        }
                        else
                        {
                            Logger.Info("Redirect starts to (else Block): " + ssoResult.RelayState);
                            return Redirect(ssoResult.RelayState);
                        }
                    }
                }
    
  • User Avatar
    0
    pliaspzero created

    Maybe it searches in host - not in Tenant? We use this search user by email implemantion which you documented in one of your docs

  • User Avatar
    0
    ismcagdas created
    Support Team

    Hi @pliaspzero

    The document you mentioned explains how to find a user in entire database. If you are finding a user using that approach, the user might belong to Host for sure. You can compare user.TenantId with tenantIdand see if the found user belongs to tenantId you are using.

    Thanks,