Permissions and Roles, Programmatically

You can use the regular ASP.NET membership functions to create and manage users. Look inside N2.Edit.Membership.Edit and you will find that it is as simple as: 

To do this...Use this code...
Add a user to a role
Roles.AddUserToRole(username, rolename); 
Remove a user from a role
Roles.RemoveUserFromRole(username, rolename);
Save changes to a user
System.Web.Security.Membership.UpdateUser(username);
Create a new user 
Delete a user 

How does it work?

If you look in web.config you will see that everything membership-related is actually driven by N2.Security.ContentMembershipProvider by default. 

<providers>
	<add passwordFormat="Hashed" 
		name="ContentMembershipProvider" 
		type="N2.Security.ContentMembershipProvider, N2.Management" />
</providers>

This in turn uses something called ItemBridge to persist the standard .NET Membership objects as regular ContentItems. 

Extending the N2CMS User Profile

First, define class with your custom profile extension, inheriting N2 User.

[PartDefinition("User")]
[RestrictParents(typeof(UserList))]
[Throwable(AllowInTrash.No)]
[Versionable(AllowVersions.No)]
public class UserProfile : N2.Security.Items.User
{
	[EditableTextBox(Title = "Age", SortOrder = 20, Required = false)]
	public virtual string Age { get; set; }
}

Then, tell N2 to use your class in web.config...

<edit>
	<membership userType="YourProj.YouExtensions.Users.UserProfile, YourProj" />

All manipulation with users are done with ItemBridge...

ItemBridge bridge = N2.Context.Current.Resolve<ItemBridge>();

Now you can create new user with custom profile and populate his custom properties...

UserProfile newUser = (UserProfile)bridge.CreateUser("John Doe", "Password", "office@doe.com", "", "", true, null);
newUser.Age = "33";
bridge.Save(newUser);

Or find existing ones and update them...

UserList users = bridge.GetUserContainer(false);
UserProfile user = users.Children.OfType<UserProfile>().Where(u => u.Email == "john@doe.com").FirstOrDefault();
user.Age = "34";
bridge.Save(user);

 

See Also