public async Task CreateRequiredRolesAndAdminUser(
            SiteSettings site,
            string adminEmail,
            string adminLoginName,
            string adminDisplayName,
            string adminPassword
            )
        {
            // New admin user for a tenant site should belong to the parent site,
            // if this related sites mode is used
            if (_multiTenantOptions.UseRelatedSitesMode && _multiTenantOptions.RelatedSiteId != Guid.Empty)
            {
                site.Id = _multiTenantOptions.RelatedSiteId;
            }

            await EnsureRequiredRoles(site);

            var adminRole = await _userQueries.FetchRole(site.Id, "Administrators", CancellationToken);

            if (adminRole == null)
            {
                throw new InvalidOperationException("Administrators role could nto be found so cannot create admin user");
            }

            var adminUser = new SiteUser
            {
                Id     = Guid.NewGuid(),
                SiteId = site.Id,
                Email  = adminEmail
            };

            adminUser.NormalizedEmail    = adminUser.Email.ToUpperInvariant();
            adminUser.DisplayName        = adminDisplayName;
            adminUser.UserName           = adminLoginName;
            adminUser.NormalizedUserName = adminUser.UserName.ToUpperInvariant();
            adminUser.EmailConfirmed     = true;
            adminUser.AccountApproved    = true;

            // clear text password will be hashed upon login
            adminUser.PasswordHash  = adminPassword + "||0"; //pwd/salt/format
            adminUser.MustChangePwd = true;                  // TODO: implement logic to enforce this

            await _userCommands.Create(adminUser, CancellationToken.None);

            await _userCommands.AddUserToRole(
                site.Id,
                adminRole.Id,
                adminUser.Id,
                CancellationToken.None);
        }
Exemple #2
0
        public async Task <IdentityResult> RemoveUserFromRole(Guid siteId, Guid userId, string roleName)
        {
            var errors = new List <IdentityError>();
            var role   = await _queries.FetchRole(siteId, roleName);

            if (role == null)
            {
                var er = new IdentityError
                {
                    Description = "role not found"
                };
                errors.Add(er);
                return(IdentityResult.Failed(errors.ToArray()));
            }
            var user = await _queries.Fetch(siteId, userId);

            if (user == null)
            {
                var er = new IdentityError
                {
                    Description = "user not found"
                };
                errors.Add(er);
                return(IdentityResult.Failed(errors.ToArray()));
            }

            await _commands.RemoveUserFromRole(role.SiteId, role.Id, user.Id);

            user.RolesChanged = true;
            await _commands.Update(user);


            return(IdentityResult.Success);
        }
Exemple #3
0
        public async Task <TRole> FindByIdAsync(string roleId, CancellationToken cancellationToken)
        {
            cancellationToken.ThrowIfCancellationRequested();
            ThrowIfDisposed();
            if (string.IsNullOrWhiteSpace(roleId))
            {
                throw new ArgumentException("invalid roleid");
            }
            if (roleId.Length != 36)
            {
                throw new ArgumentException("invalid roleid");
            }
            var roleGuid = new Guid(roleId);
            var role     = await queries.FetchRole(GetSiteId(), roleGuid, cancellationToken);

            return((TRole)role);
        }
Exemple #4
0
        private async Task AddUserToDefaultRoles(ISiteUser siteUser, CancellationToken cancellationToken)
        {
            ThrowIfDisposed();
            cancellationToken.ThrowIfCancellationRequested();
            ISiteRole role;

            string defaultRoles = multiTenantOptions.DefaultNewUserRoles;

            if (defaultRoles.Length > 0)
            {
                if (defaultRoles.IndexOf(";") == -1)
                {
                    role = await queries.FetchRole(siteUser.SiteId, defaultRoles, cancellationToken);

                    if ((role != null) && (role.Id != Guid.Empty))
                    {
                        await commands.AddUserToRole(role.SiteId, role.Id, siteUser.Id, cancellationToken);
                    }
                }
                else
                {
                    string[] roleArray = defaultRoles.Split(';');
                    foreach (string roleName in roleArray)
                    {
                        if (!string.IsNullOrWhiteSpace(roleName))
                        {
                            role = await queries.FetchRole(siteUser.SiteId, roleName, cancellationToken);

                            if ((role != null) && (role.Id != Guid.Empty))
                            {
                                await commands.AddUserToRole(role.SiteId, role.Id, siteUser.Id, cancellationToken);
                            }
                        }
                    }
                }
            }
        }
        public async Task <IdentityResult> RemoveUserFromRole(Guid siteId, Guid userId, string roleName)
        {
            var errors = new List <IdentityError>();
            var role   = await _queries.FetchRole(siteId, roleName);

            if (role == null)
            {
                var er = new IdentityError
                {
                    Description = "role not found"
                };
                errors.Add(er);
                return(IdentityResult.Failed(errors.ToArray()));
            }
            var user = await _queries.Fetch(siteId, userId);

            if (user == null)
            {
                var er = new IdentityError
                {
                    Description = "user not found"
                };
                errors.Add(er);
                return(IdentityResult.Failed(errors.ToArray()));
            }

            await _commands.RemoveUserFromRole(role.SiteId, role.Id, user.Id);

            user.RolesChanged = true;
            await _commands.Update(user);

            foreach (var handler in _userRemovedFromRoleHandlers)
            {
                try
                {
                    await handler.Handle(user, role);
                }
                catch (Exception ex)
                {
                    _log.LogError($"{ex.Message}-{ex.StackTrace}");
                }
            }


            return(IdentityResult.Success);
        }
Exemple #6
0
        public async Task CreateAdminUser(ISiteSettings site)
        {
            var adminRole = await userQueries.FetchRole(site.Id, "Administrators", CancellationToken);

            if (adminRole == null)
            {
                throw new InvalidOperationException("Administrators role could nto be found so cannot create admin user");
            }


            // if using related sites mode there is a problem if we already have user [email protected]
            // and we create another one in the child site with the same email and login so we need to make it different
            // we could just skip creating this user since in related sites mode all users come from the first site
            // but then if the config were changed to not related sites mode there would be no admin user
            // so in related sites mode we create one only as a backup in case settings are changed later
            var countOfSites = await queries.GetCount(CancellationToken);

            var siteDifferentiator = string.Empty;

            if (
                (countOfSites >= 1) &&
                (multiTenantOptions.UseRelatedSitesMode)
                )
            {
                //TODO: do we need to replace this logic now that we don't have an integer id?
                //if (site.SiteId > 1)
                //{
                //    siteDifferentiator = site.SiteId.ToInvariantString();
                //}
            }


            var adminUser = InitialData.BuildInitialAdmin();

            adminUser.SiteId          = site.Id;
            adminUser.Email           = "admin" + siteDifferentiator + "@admin.com";
            adminUser.NormalizedEmail = adminUser.Email.ToUpperInvariant();
            adminUser.UserName        = "******" + siteDifferentiator;

            await userCommands.Create(adminUser, CancellationToken.None);

            await userCommands.AddUserToRole(
                adminRole.Id,
                adminUser.Id,
                CancellationToken.None);
        }
        private static async Task EnsureData(
            ISiteQueries siteQueries,
            ISiteCommands siteCommands,
            IUserQueries userQueries,
            IUserCommands userCommands,
            IGeoQueries geoQueries,
            IGeoCommands geoCommands,
            IBasicQueries<SiteRole> roleQueries,
            IBasicQueries<SiteUser> userBasic
            
            )
        {
            
            int count = await geoQueries.GetCountryCount();
            if (count == 0)
            {
                foreach (GeoCountry c in InitialData.BuildCountryList())
                {
                    await geoCommands.Add(c);
                }

                foreach (GeoZone c in InitialData.BuildStateList())
                {
                    await geoCommands.Add(c);
                }
            }
            
            count = await siteQueries.GetCount();
            SiteSettings newSite = null;
            
            Guid siteId = Guid.Empty;
            if (count == 0)
            {
                // create first site
                newSite = InitialData.BuildInitialSite();
                await siteCommands.Create(newSite);
                siteId = newSite.Id;
                
            }
            else if(count == 1)
            {
                var allSites = await siteQueries.GetList().ConfigureAwait(false);
                var site = allSites[0];
                if (site != null) siteId = site.Id;
            }
            else
            {
                return;
            }

            // ensure roles
            //var projectId = await projectResolver.ResolveProjectId();
            var projectId = siteId.ToString(); ;


            count = await roleQueries.GetCountAsync(projectId);
            if (count == 0)
            {
                var adminRole = InitialData.BuildAdminRole();
                adminRole.SiteId = siteId;
                await userCommands.CreateRole(adminRole);
                
                var roleAdminRole = InitialData.BuildRoleAdminRole();
                roleAdminRole.SiteId = siteId;
                await userCommands.CreateRole(roleAdminRole);
                
                var contentAdminRole = InitialData.BuildContentAdminsRole();
                contentAdminRole.SiteId = siteId;
                await userCommands.CreateRole(contentAdminRole);

                var authenticatedUserRole = InitialData.BuildAuthenticatedRole();
                authenticatedUserRole.SiteId = siteId;
                await userCommands.CreateRole(authenticatedUserRole);
                
            }

            // ensure admin user
            count = await userBasic.GetCountAsync(projectId);

            if (count == 0)
            {
                var role = await userQueries.FetchRole(newSite.Id, "Administrators");
                
                if (role != null)
                {
                    var adminUser = InitialData.BuildInitialAdmin();
                    adminUser.SiteId = siteId;
                    await userCommands.Create(adminUser);
                    
                    await userCommands.AddUserToRole(siteId, role.Id, adminUser.Id);

                    role = await userQueries.FetchRole(siteId, "Authenticated Users");
                    
                    if (role != null)
                    {
                        await userCommands.AddUserToRole(siteId, role.Id, adminUser.Id);
                    }
                }
                
            }

        }
        private static async Task EnsureData(
            ISiteQueries siteQueries,
            ISiteCommands siteCommands,
            IUserQueries userQueries,
            IUserCommands userCommands,
            IGeoQueries geoQueries,
            IGeoCommands geoCommands,
            IBasicQueries <SiteRole> roleQueries,
            IBasicQueries <SiteUser> userBasic,
            IProjectResolver projectResolver
            )
        {
            int count = await geoQueries.GetCountryCount();

            if (count == 0)
            {
                foreach (GeoCountry c in InitialData.BuildCountryList())
                {
                    await geoCommands.Add(c);
                }

                foreach (GeoZone c in InitialData.BuildStateList())
                {
                    await geoCommands.Add(c);
                }
            }

            //count = await geoQueries.GetLanguageCount();
            //if (count == 0)
            //{
            //    foreach (Language c in InitialData.BuildLanguageList())
            //    {
            //        await geoCommands.Add(c);
            //    }
            //}

            var all = await geoQueries.GetAllCurrencies();

            count = all.Count;
            if (count == 0)
            {
                foreach (Currency c in InitialData.BuildCurrencyList())
                {
                    await geoCommands.Add(c);
                }
            }

            count = await siteQueries.GetCount();

            SiteSettings newSite = null;

            if (count == 0)
            {
                // create first site
                newSite = InitialData.BuildInitialSite();
                await siteCommands.Create(newSite);
            }

            // ensure roles
            var projectId = await projectResolver.ResolveProjectId();

            count = await roleQueries.GetCountAsync(projectId);

            if (count == 0)
            {
                var adminRole = InitialData.BuildAdminRole();
                adminRole.SiteId = newSite.Id;
                await userCommands.CreateRole(adminRole);

                var roleAdminRole = InitialData.BuildRoleAdminRole();
                roleAdminRole.SiteId = newSite.Id;
                await userCommands.CreateRole(roleAdminRole);

                var contentAdminRole = InitialData.BuildContentAdminsRole();
                contentAdminRole.SiteId = newSite.Id;
                await userCommands.CreateRole(contentAdminRole);

                var authenticatedUserRole = InitialData.BuildAuthenticatedRole();
                authenticatedUserRole.SiteId = newSite.Id;
                await userCommands.CreateRole(authenticatedUserRole);
            }

            // ensure admin user
            count = await userBasic.GetCountAsync(projectId);

            if (count == 0)
            {
                var role = await userQueries.FetchRole(newSite.Id, "Administrators");

                if (role != null)
                {
                    var adminUser = InitialData.BuildInitialAdmin();
                    adminUser.SiteId = newSite.Id;
                    await userCommands.Create(adminUser);

                    await userCommands.AddUserToRole(role.Id, adminUser.Id);

                    role = await userQueries.FetchRole(newSite.Id, "Authenticated Users");

                    if (role != null)
                    {
                        await userCommands.AddUserToRole(role.Id, adminUser.Id);
                    }
                }
            }
        }
Exemple #9
0
        private static async Task EnsureData(
            ISiteQueries siteQueries,
            ISiteCommands siteCommands,
            IUserQueries userQueries,
            IUserCommands userCommands,
            IGeoQueries geoQueries,
            IGeoCommands geoCommands,
            IBasicQueries <SiteRole> roleQueries,
            IBasicQueries <SiteUser> userBasic

            )
        {
            int count = await geoQueries.GetCountryCount();

            if (count == 0)
            {
                foreach (GeoCountry c in InitialData.BuildCountryList())
                {
                    await geoCommands.Add(c);
                }

                foreach (GeoZone c in InitialData.BuildStateList())
                {
                    await geoCommands.Add(c);
                }
            }

            count = await siteQueries.GetCount();

            SiteSettings newSite = null;

            Guid siteId = Guid.Empty;

            if (count == 0)
            {
                // create first site
                newSite = InitialData.BuildInitialSite();
                await siteCommands.Create(newSite);

                siteId = newSite.Id;
            }
            else if (count == 1)
            {
                var allSites = await siteQueries.GetList().ConfigureAwait(false);

                var site = allSites[0];
                if (site != null)
                {
                    siteId = site.Id;
                }
            }
            else
            {
                return;
            }

            // ensure roles
            //var projectId = await projectResolver.ResolveProjectId();
            var projectId = siteId.ToString();;


            count = await roleQueries.GetCountAsync(projectId);

            if (count == 0)
            {
                var adminRole = InitialData.BuildAdminRole();
                adminRole.SiteId = siteId;
                await userCommands.CreateRole(adminRole);

                var roleAdminRole = InitialData.BuildRoleAdminRole();
                roleAdminRole.SiteId = siteId;
                await userCommands.CreateRole(roleAdminRole);

                var contentAdminRole = InitialData.BuildContentAdminsRole();
                contentAdminRole.SiteId = siteId;
                await userCommands.CreateRole(contentAdminRole);

                var authenticatedUserRole = InitialData.BuildAuthenticatedRole();
                authenticatedUserRole.SiteId = siteId;
                await userCommands.CreateRole(authenticatedUserRole);
            }

            // ensure admin user
            count = await userBasic.GetCountAsync(projectId);

            if (count == 0)
            {
                var role = await userQueries.FetchRole(newSite.Id, "Administrators");

                if (role != null)
                {
                    var adminUser = InitialData.BuildInitialAdmin();
                    adminUser.SiteId         = siteId;
                    adminUser.CanAutoLockout = false;
                    await userCommands.Create(adminUser);

                    await userCommands.AddUserToRole(siteId, role.Id, adminUser.Id);

                    role = await userQueries.FetchRole(siteId, "Authenticated Users");

                    if (role != null)
                    {
                        await userCommands.AddUserToRole(siteId, role.Id, adminUser.Id);
                    }
                }
            }
        }