MembershipCreateUserException: The username is already in use - c#

I've created the simple membership tables myself so that I have the ability to update the username field(can't do this if you just let it autocreate it for you).
var confirmationToken = WebSecurity.CreateUserAndAccount(model.UserName, Request["Password"], new { NameFirst = model.NameFirst, NameLast = model.NameLast, ContactId = newContact.ContactId },true);
When I run this line of code I keep getting the error message that the Username already exists. What is weird is that there is no username in the table with the same name and it does it for every registration. It has something to do with me creating the tables myself probably but I can't see where it's having this problem.
It does add it to my UserProfile table (called it UserSecurity) but doesn't include the user in the membership table.
Edit: The line above is using the webpages_Membership table. I need it to use my UserMembership table instead.

Edit: The line above is using the webpages_Membership table. I need it to use my UserMembership table instead.
If you want Simple Membership Provider to use a different table than the default one you need to change the table that WebSecurity.InitializeDatabaseConnection points to.
In solution explorer, go to Filters -> InitializeSimpleMembershipAttribute.cs and use this instead:
WebSecurity.InitializeDatabaseConnection("MyContext", "TableToPointTo",
"UserIdColumn", "UserNameColumn", autoCreateTables: true);

Related

Assign user based on another table in asp.net mvc4

I'm not even sure how to search for this question, so forgive me if I'm asking a duplicate question and would be grateful for any redirection needed.
I have data (Account Number, Password, Internal Y/N) that is being submitted to an Account Table from Navision. I want to use this data to automatically create a user in the UserProfile table (Username = Account Number, Password = Password) and assign that user to the Admin role if Internal = Y and DealerAdmin if Internal = N.
The data will continue to be maintained for Account numbers in Navision, but the DealerAdmin can add additional users from the website. Is this possible? If so, please provide any pointers to tutorials as to where to start? I presume it's a simple SQL statement. Where do I add this code in MVC so that it gets updated every time there's new data in the Account Table?
If you are using SQL why not use a trigger to create a new record in your User UserProfile when your conditions are met?
If this does not work for you can take a look at the post below and call your proc to move the data over if needed.
ASP.NET MVC 4 intercept all incoming requests

Get all roles of any user (yes, not currently logged one)

In an MVC app, administrator has a CRUD controller for managing users. Now, the functionality of the edit part needs to be extended and it involves adding a number role dependent tabs. They depend on the role of the viewed user, rather than on roles of the administrator who is viewing them. The easiest way for achieving this, would be getting all roles of that user as a array of strings (or similar), but how do I actually go about obtain those.
Is there a preferred method of getting all roles of a single user in SimpleMembership (based on his UserId) or do I just have to patch up a stored function in the database and pull those through it?
Writing the function is not a big deal, but this problem doesn't sound like something I should have to make workarounds for.
Use the Roles.GetRolesForUser() method https://msdn.microsoft.com/en-us/library/8h930x07(v=vs.110).aspx
string[] rolesArray = Roles.GetRolesForUser("username");
With the string being the User Name of the user as contained in the aspnetdb.
If you want to find by using a guid, you could try the following:
Guid userId; // ID of user - you can populate this somehow
MembershipUser memUser = Membership.GetUser(userId);
string[] roles = Roles.GetRolesForUser(memUser.UserName);
Here is the stored procedure I mentioned in the question:
CREATE FUNCTION GetUserRoles
(
#UserId int
)
RETURNS TABLE
AS
RETURN
(
SELECT
r.RoleName
FROM
dbo.webpages_UsersInRoles uir
JOIN dbo.webpages_Roles r ON (r.RoleId = uir.RoleId)
WHERE
uir.UserId = #UserId
)
GO
The only reason to go with this instead than the answer by user1666620, would be if you wanted to skip one unnecessary query to the DB. The preferred method to use this solution would be to add this function to your dbml (or it's EF equivalent). Obviously this first needs to be added in the database.

Populating SecurityStamp for legacy users in database in ASP.NET Identity

I have a legacy database that I am using with ASP.NET Identity. In order to use the Identity functions a SecurityStamp value is required in the database for each user.
Some have mentioned in other questions relating to this that the value can be 'any random value, EG a random int' but that doesn't sound right to me!?
I created a new user in the database using this code:
IdentityResult result = await UserManager.CreateAsync(user, model.Password);
and it populated it with the following value: cea9a659-e965-4e76-8203-ed1c79491fa7
That seems like a more 'secure' value to me than a random int, especially when it's called the SecurityStamp, it seems like it should be populated in the same manner for all users in my database.
How can I populate the SecurityStamp values for my Users database, properly?
Security Stamp by default is GUID and I have not seen any way to modify it. So you if you want to populate that value for all existing users just run sql:
update AspNetUsers
set SecurityStamp = NEWID()
where SecurityStamp is null
So the security stamp can be any string you like, its just used to as a comparison point, so you are free to seed all of these to whatever value you want initially (even a constant empty string would work fine), by default the UserManger will generate a new guid for the stamp automatically during these methods:
Create
RemovePassword
ChangePassword
AddPassword
RemoveLogin
SetEmail
SetPhoneNumber
ChangePhoneNumber
SetTwoFactorEnabled
And you can always call UpdateSecurityStamp directly.
Finally if you are using the Identity.EF implementation, you can always just directly set the field as well:
user.SecurityStamp = generateAString();
await userManager.UpdateAsyc(user);

Editing data from database in razor view

I'm writing code in ASP.NET but it's not a language related question. Every time when I write a web application and I display some data from database using razor view I have this problem. For example I have simple table with Id and Name in my database. I want to display a table with Names using EditorFor fields. User can edit all the data and save it. So I use row Id as EditorFor Id, read input values in javascript method, use WebMethod to pass them to Controller and save changes to database. But in this case I can change EditorFor Id in Firebug and pass changes with wrong ids. What's the way to edit data in that case? I don't want to click edit link and redirect user to edit page when he can edit one row. I have 5 rows in database with Names and I want to edit all of them at once.
That's some kind of security, and you must add security method in this situation.
One way is to use RBAC method for your security structure. For example:
Create a table and name it user_groups, then create table of users that has and foreign key to user_groups
Then also add the foreign key to your " simple table "(that has id and name) to user_groups, that represent witch user_groups can update the row,
I this that's clear. When someone want to edit a row, you check if that user has permission to change the row or not?
You can search term "Role Base Access Control" in asp mvc,
Also something useful here:
http://www.webdevbros.net/2009/12/16/role-based-access-control-in-asp-net-mvc/
[HttpPost]
public ActionResult EditEmailTemplate(EmailTemplate_Mst emailTemplate_Mst, string Command, int id = 0)
{
try
{
EmailTemplate_Mst et = _repository.GetEmailById(id);
if (Command == "Update")
{
et.Title = emailTemplate_Mst.Title;
et.EmailTemplate_Content = emailTemplate_Mst.EmailTemplate_Content;
et.EmailTemplate_LastModifyBy = Convert.ToInt64(Session["UserId"].ToString());
et.EmailTemplate_LastModifyDate = DateTime.Now;
_repository.UpdateEmail(et);
return RedirectToAction("ViewEmailTemplate");
}
}
catch (Exception)
{
ModelState.AddModelError("", "Unable to save changes. Try again, and if the problem persists see your system administrator.");
}
return View(new { id = emailTemplate_Mst.EmailTemplate_Id });
}
http://www.c-sharpcorner.com/UploadFile/4d9083/creating-insert-update-and-delete-application-in-mvc-4-using/

How to lock/unlock a user in MVC SimpleMembership

In SimpleMembership there isn't any column in the database for a user to be locked/unlocked.
I basically need my administrator to enable or disable any user in my application.
Is there any alternatives to that?
I find it easiest to use Roles to do this. Have a ActiveUser role and tag your controllers or actions with a Authorize attribute.
[Authorize(Roles = "ActiveUser")]
Then some simple admin to add or remove users from the role to unlock and lock their access to everything protected with that roles attribute.
Roles.AddUserToRole(user.Username, "ActiveUser");
Roles.RemoveUserFromRole(user.Username, "ActiveUser");
Probably not the "approved" way of doing things, but this is how I do it.
There is a field within the webpages_Membership table called IsConfirmed. Typically, this is for when you want a 2-stage registeration process: sign-up then activate via a link within an email. By nature though, this field has the same affect as IsApproved within the former aspnet_Membership table: if set to true, a user can login; if false they can't. So I just use plain old SQL to set to true or false:
// If using EntityFramework
// 1. Setup my params
var params = new List<SqlParameter>() {
new SqlParameter("#UserID", 1),
new SqlParameter("#Activate", true) // or false
};
SqlParameter[] paramArray = params.ToArray();
// 2. Update the database
myDbContext.Database.ExecuteSqlCommand("UPDATE webpages_Membership SET IsConfirmed = #Activate WHERE UserId = #UserID", paramArray);
I haven't tried simplemembership yet, but this sound great for some of the small projects I am working on. Here are some options:
Option 1: Add a custom field to the table like shown here - http://www.dwdmbi.com/2012/10/adding-custom-fields-to-vs2012-mvc4.html
Option 2 Create a new table with a foreign key back to User. Do an additional check on this value.
Either way your are going to something extra for the check. You can customize the 'Authorize' attribute to include your check (instructions here - Override Authorize Attribute in ASP.NET MVC).
try this approach. It uses IsApproved rather than the IsLockedOut. If your implementation does not already use IsAproved, this would be a good solution.
MembershipUser user = Membership.GetUser(username);
user.IsApproved = false;
Membership.UpdateUser(user);
This is not exactly locking the user. Technically this call is taking approved status from the user and leaving them unable to log-in.
I dont know the technology you are using but either you have to give column in the table with lock unlock as you specified or siply add one table in the database(Say tlbDisable) where you can delete the entries in original table and insert it in new table(tlbDisable).
When you again want to enable that user then simple delete the entry from tlbDisable and insert it into original user table.

Categories

Resources