Created
August 23, 2012 06:11
-
-
Save jongalloway/3433270 to your computer and use it in GitHub Desktop.
I wanted to create an administrative user in an MVC 4 tutorial using a drop in code file (just throw in App_Start folder and it'll create the user on first run). Normally I'd use WebActivator for PostApplicationStart, but I wanted to make this just a simp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using Mvc4SampleApplication.Filters; | |
using System.Web; | |
using System.Web.Security; | |
using WebMatrix.WebData; | |
[assembly: PreApplicationStartMethod(typeof(PreApplicationTasks), "Initializer")] | |
public static class PreApplicationTasks | |
{ | |
public static void Initializer() | |
{ | |
Microsoft.Web.Infrastructure.DynamicModuleHelper.DynamicModuleUtility | |
.RegisterModule(typeof(UserInitializationModule)); | |
} | |
} | |
public class UserInitializationModule : IHttpModule | |
{ | |
private static bool initialized; | |
private static object lockObject = new object(); | |
private const string _username = "Owner"; | |
private const string _password = "p@ssword123"; | |
private const string _role = "Administrator"; | |
void IHttpModule.Init(HttpApplication context) | |
{ | |
lock (lockObject) | |
{ | |
if (!initialized) | |
{ | |
new InitializeSimpleMembershipAttribute().OnActionExecuting(null); | |
if (!WebSecurity.UserExists(_username)) | |
WebSecurity.CreateUserAndAccount(_username, _password); | |
if (!Roles.RoleExists(_role)) | |
Roles.CreateRole(_role); | |
if (!Roles.IsUserInRole(_username, _role)) | |
Roles.AddUserToRole(_username, _role); | |
} | |
initialized = true; | |
} | |
} | |
void IHttpModule.Dispose() { } | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment