NReed.Dev

Sitecore | Optimizely | .NET

Create an Optimizely Admin User

Recently I was setting up an Optimizely solution and was given a bacpac from Integration. Unfortunately I was not given a username or password to be able to log in to the CMS.

I decided to get around this by creating an Initialization Module that creates one for me.

Here is how I did it.

First we need to create the below class.

C#
using OptimizelyProject;
using EPiServer.Authorization;
using EPiServer.Shell.Security;
using EPiServer.Web;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting; 

namespace OptimizelyProject;

public class DefaultUserInitializationModule : IBlockingFirstRequestInitializer
{
    private readonly UIUserProvider _uIUserProvider;
    private readonly UIRoleProvider _uIRoleProvider;
    private readonly UISignInManager _uISignInManager;
    private readonly IHostEnvironment _hostEnvironment;

    public DefaultUserInitializationModule(UIUserProvider uIUserProvider, UISignInManager uISignInManager, UIRoleProvider uIRoleProvider, IHostEnvironment hostEnvironment)
    {
        _uIUserProvider = uIUserProvider;
        _uISignInManager = uISignInManager;
        _uIRoleProvider = uIRoleProvider;
        _hostEnvironment = hostEnvironment;
    }

    public bool CanRunInParallel => false;

    public async Task InitializeAsync(HttpContext httpContext)
    {
        await CreateUser("admin", "admin@example.com", "<YourPassword>", new[] { Roles.Administrators, Roles.WebAdmins });
    } 

    private async Task CreateUser(string username, string email, string password, IEnumerable<string> roles)
    {
        var result = await _uIUserProvider.CreateUserAsync(username, password, email, null, null, true);

        if (result.Status == UIUserCreateStatus.Success)
        {
            foreach (var role in roles)
            {
                var exists = await _uIRoleProvider.RoleExistsAsync(role);
                if (!exists)
                {
                    await _uIRoleProvider.CreateRoleAsync(role);
                }
            } 

            await _uIRoleProvider.AddUserToRolesAsync(result.User.Username, roles);
            var resFromSignIn = await _uISignInManager.SignInAsync(username, password);
        }
    }
 
    private async Task<bool> IsAnyUserRegistered()
    {
        int res;
        if (_hostEnvironment.IsDevelopment())
        {
            res = await _uIUserProvider.GetAllUsersAsync(0, 1).Where(x => x.Username.Contains("admin")).CountAsync();
            return res > 0;
        }
        res = await _uIUserProvider.GetAllUsersAsync(0, 1).CountAsync();
        return res > 0;
    }
} 

Next we need to add the following line to the Startup.cs.

C#
services.TryAddEnumerable(Microsoft.Extensions.DependencyInjection.ServiceDescriptor.Singleton(typeof(IFirstRequestInitializer), typeof(DefaultUserInitializationModule)));

Run the solution and confirm that you can log in with the username and password you selected!


Leave a Reply

Your email address will not be published. Required fields are marked *