3

I want to assigned new registered users automatically the role of Member in Database.

Filburt
  • 17,626
  • 12
  • 64
  • 115

2 Answers2

1

WebMatrix sample Starter Site app - Account\Register.cshtml

Tested and it works.

// Check if user already exists
var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email) = LOWER(@0)", email);
if (user == null) {
// Insert email into the profile table
db.Execute("INSERT INTO UserProfile (Email) VALUES (@0)", email);

//Roles have already been added to webpages_Roles table
//Logic to determine role for e-mail (user) being added for the first time
if (email == "John@gmail.com") {
    var userName=email;
    var roleName="Administrator";
    Roles.AddUserToRole(userName, roleName);
} 
else if (email == "Greg@gmail.com") {
    var userName=email;
    var roleName="Guest";
    Roles.AddUserToRole(userName, roleName);
}
else {
    //All others are assigned the role of Member
    var username=email;
    var roleName="Member";
    Roles.AddUserToRole(userName, roleName);
}
Skillet
  • 21
  • 3
0

In your register code, which in the sample WebMatrix app is found in the file Account\Register.cshtml, there's if statements that first determine that the information being submitted is valid and then that the email doesn't exist in your database. Within those if statements, if the user is successfully created, then you can add code like:

// boy, is this a hack, Member = RoleID 8
db.Execute("INSERT INTO webpages_UsersInRoles (UserId, RoleID) VALUES( @0, 8 )", UserID);

Now I used 8 as an example. Look in your webpages_Roles table. This has a list of RoleNames and their RoleID. If you've already created the Member role, it will be in this table. Use the corresponding RoleID instead of the 8 that I used.

Knox
  • 2,909
  • 11
  • 37
  • 65