Umbraco External Membership Provider - umbraco

Current Umbraco Version - Umbraco version 7.5.3
We have an Umbraco Project that uses a Custom Membership Provider to authenticate members (front-end) to certain protected page(s). This membership provider has worked fine until we had to upgrade the system that our members are authenticated via. After upgrading the external system our Membership Provider now has a strange issue that I'm struggling to resolve. The issue is as follows:
1 - User attempts to login with their correct details (via Umbraco Login Form) and receives an 'Incorrect Username & Password Error'
2 - User then uses our 'Reset Password' functionality, which sends them a 'PIN' that they enter into an Umbraco Form. If the PIN matches, they're then presented with a Form to enter a new Password.
3 - The user is now able to log via the newly created Username & Password (into Umbraco Protected Areas).
4 - Now, the user goes to our External system and enters their username and password (created via the Umbraco Form). This also logs them in successfully. (This seems to change the password of the user?)
5 - User now tries to re-login to Umbraco Protected Page but again receives an incorrect Username & Password.
6 - However the Username and Password still works on the external system.
After some research we have come to the conclusion that our external system now seems to use a different Encryption method that Umbraco isn't compatible with?
I'm really struggling to figure out how/why this is now happening and what I need to change to ensure that the passwords both match and that the members can access the protected pages.
Here is what I believe is running the Login/Password Reset Logic:
namespace Profile.Controllers
{
[PluginController("Profile")]
public class SecurityController : SurfaceController
{
public string RandomString(int length)
{
var chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
var stringChars = new char[length];
var random = new Random();
for (int i = 0; i < stringChars.Length; i++)
{
stringChars[i] = chars[random.Next(chars.Length)];
}
return new String(stringChars);
}
[ChildActionOnly]
public ActionResult SecurityForm()
{
var model = new SecurityModel();
return PartialView("SecurityForm", model);
}
[HttpPost]
public ActionResult UpdateUsername(SecurityModel viewModel, FormCollection form)
{
iboAdmin.InitializeSystem();
try
{
CContactUser user = CContactUser.LoginByWebLogin(User.Identity.Name);
user.ChangeWebLogin(viewModel.ChangeUsername.NewUsername, viewModel.ChangeUsername.Password);
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
if (ModelState.IsValid)
{
TempData["SuccessMessage"] = "Your username has been changed successfully";
return RedirectToCurrentUmbracoPage();
}
else
{
return CurrentUmbracoPage();
}
}
[HttpPost]
public ActionResult UpdatePassword(SecurityModel viewModel, FormCollection form)
{
bool legacyCode = false;
try
{
if (legacyCode)
{
iboAdmin.InitializeSystem();
CContactUser user = CContactUser.LoginByWebLogin(User.Identity.Name);
user.ChangePassword(viewModel.ChangePassword.CurrentPassword, viewModel.ChangePassword.NewPassword);
}
else
{
if (!iboAdmin.IsSystemInitialized)
{
iboAdmin.InitializeSystem();
}
CContactUser user = CContactUser.LoginByWebLogin(User.Identity.Name);
var contact = new CContact(CStaffUser.GetDefaultStaffUser(), user.ContactId);
contact.UserSecurity.ChangePassword(viewModel.ChangePassword.CurrentPassword, User.Identity.Name, viewModel.ChangePassword.NewPassword);
contact.Save();
if (contact.ErrorsCount > 0)
ModelState.AddModelError("", "An error occured when setting the password: " + contact.Errors.PrimaryErrorMessage);
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
if (ModelState.IsValid)
{
TempData["SuccessMessage"] = "Your password has been changed successfully";
return RedirectToCurrentUmbracoPage();
}
else
{
return CurrentUmbracoPage();
}
}
[HttpPost]
public ActionResult LoginReminder(string Email)
{
iboAdmin.InitializeSystem();
try
{
CContactUser user = CContactUser.LoginByWebLogin("manager");
CContact contact = CContact.GetContacts(user, "", "AND Name.EMAIL = #email", new SqlParameter[] { new SqlParameter("email", Email) }).First();
string ksamHelpline = (ConfigurationManager.AppSettings.AllKeys.Contains("KSAMHelpline") ? ConfigurationManager.AppSettings["KSAMHelpline"] : "01625 664500");
if (contact == null)
{
throw new Exception("There are no users on our system with that e-mail address registered. Please contact the administration office on " + ksamHelpline + " to access your account.");
}
string userName = contact.UserSecurity.WebLoginId;
if(string.IsNullOrEmpty(userName))
{
throw new Exception("A username has not been found for your email address. Please contact the administration office on " + ksamHelpline + ".");
}
else
{
SmtpClient smtpClient = new SmtpClient();
MailMessage mail = new MailMessage();
string messageBody = System.IO.File.ReadAllText(Server.MapPath("~/emails/LoginReminder.html"));
HtmlDocument htmldoc = new HtmlDocument();
htmldoc.LoadHtml(messageBody);
mail.To.Add(new MailAddress(contact.EmailAddress));
mail.Subject = htmldoc.DocumentNode.SelectSingleNode("//head/title").InnerText;
messageBody = messageBody.Replace("[USERNAME]", userName);
mail.Body = messageBody.Replace("[FIRST_NAME]", contact.FirstName);
mail.IsBodyHtml = true;
smtpClient.Send(mail);
TempData["SuccessMessage"] = "A reminder e-mail containing your username has been sent to " + Email;
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
if (ModelState.IsValid)
{
return RedirectToCurrentUmbracoPage();
}
else
{
return CurrentUmbracoPage();
}
}
[HttpPost]
public ActionResult PasswordResetRequest(string username)
{
Session["ResetUser"] = "";
iboAdmin.InitializeSystem();
try
{
CContactUser user = CContactUser.LoginByWebLogin(username);
CContact contact = new CContact(user,user.ContactId);
if (contact.EmailAddress == "")
{
throw new Exception("There is no email address registered to that username. Please contact the administration office to access your account.");
}
Session["PIN"] = RandomString(5);
Session["ResetUser"] = username;
TempData["PINSent"] = true;
SmtpClient smtpClient = new SmtpClient();
MailMessage mail = new MailMessage();
string messageBody = System.IO.File.ReadAllText(Server.MapPath("~/emails/ResetPasswordPin.html"));
HtmlDocument htmldoc = new HtmlDocument();
htmldoc.LoadHtml(messageBody);
mail.To.Add(new MailAddress(contact.EmailAddress));
mail.Subject = htmldoc.DocumentNode.SelectSingleNode("//head/title").InnerText;
mail.Body = messageBody.Replace("[PIN]", Session["PIN"].ToString());
mail.IsBodyHtml = true;
smtpClient.Send(mail);
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
if (ModelState.IsValid)
{
return RedirectToCurrentUmbracoPage();
}
else
{
return CurrentUmbracoPage();
}
}
[HttpPost]
public ActionResult PasswordResetVerify(string PIN)
{
iboAdmin.InitializeSystem();
try
{
if (Session["PIN"].ToString() == PIN)
{
TempData["Verified"] = true;
}
else
{
throw new Exception("Verification codes do not match");
}
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
if (ModelState.IsValid)
{
return RedirectToCurrentUmbracoPage();
}
else
{
return CurrentUmbracoPage();
}
}
[HttpPost]
public ActionResult PasswordReset(string password)
{
iboAdmin.InitializeSystem();
try
{
CContact contact;
bool legacyCode = false, success = false;
if (legacyCode)
{
CContactUser user = CContactUser.LoginByWebLogin(Session["ResetUser"].ToString());
user.ChangePassword(password, "REMOVED", "REMOVED");
contact = new CContact(user, user.ContactId);
}
else
{
// Jeremy suggested code v1.
//
/*if (!iboAdmin.IsSystemInitialized)
{
iboAdmin.InitializeSystem();
}
CContactUser user = CContactUser.LoginByWebLogin(Session["ResetUser"].ToString());
contact = new CContact(user, user.ContactId);
contact.UserSecurity.ChangePassword(password, "REMOVED", "REMOVED");
contact.Save();
if (contact.ErrorsCount > 0)
ModelState.AddModelError("", "An error occured when setting the password: " + contact.Errors.PrimaryErrorMessage);*/
// Jeremy suggested code v2.
//
if (!iboAdmin.IsSystemInitialized)
{
iboAdmin.InitializeSystem();
}
CContactUser user = CContactUser.LoginByWebLogin(Session["ResetUser"].ToString());
contact = new CContact(CStaffUser.GetDefaultStaffUser(), user.ContactId);
var membershipUser = Membership.GetUser(contact.UserSecurity.WebLoginId, false);
string oldPassword = membershipUser.ResetPassword();
success = membershipUser.ChangePassword(oldPassword, password);
}
SmtpClient smtpClient = new SmtpClient();
MailMessage mail = new MailMessage();
string messageBody = System.IO.File.ReadAllText(Server.MapPath("~/emails/ResetPasswordSuccess.html"));
HtmlDocument htmldoc = new HtmlDocument();
htmldoc.LoadHtml(messageBody);
mail.To.Add(new MailAddress(contact.EmailAddress));
mail.Subject = htmldoc.DocumentNode.SelectSingleNode("//head/title").InnerText;
mail.Body = messageBody.Replace("[FIRST_NAME]", contact.FirstName);
mail.IsBodyHtml = true;
smtpClient.Send(mail);
TempData["Success"] = true;
TempData["SuccessMessage"] = "Your password has been reset successfully.";
}
catch (Exception ex)
{
ModelState.AddModelError("", ex.Message);
}
if (ModelState.IsValid)
{
return RedirectToCurrentUmbracoPage();
}
else
{
return CurrentUmbracoPage();
}
}
}
}

Resolved.
Just needed to add:
hashAlgorithmType="SHA256"
Into Web Config.

Related

when I try to make google authorization get Error: invalid_request Error when site is published. Oauth 1.0

I have already finished MVC site which use Oauth 1.0
When I try to make authorize with google account from localhost (from debug mode) I fluently make authorization without any problem, But when I publish my site on server I have some problem, when I click button "google LogIn" I get error. please see screen below.
Developers please help me to fix this problem. tank you
P.S. 192.168.77.155 -it's my internal server IP, But I can't imagine why to show it.
return Information Hare:
internal class ExternalLoginResult : ActionResult
{
public ExternalLoginResult(string provider, string returnUrl)
{
Provider = provider;
ReturnUrl = returnUrl;
}
public string Provider { get; private set; }
public string ReturnUrl { get; private set; }
public override void ExecuteResult(ControllerContext context)
{
OAuthWebSecurity.RequestAuthentication(Provider, ReturnUrl);
}
}
public ActionResult ExternalLoginCallback(string returnUrl)
{
GooglePlusClient.RewriteRequest();
var result = OAuthWebSecurity.VerifyAuthentication();
if (result.IsSuccessful)
{
ProfilePicture helper = new ProfilePicture();
// name of the provider we just used
OauthProvider provider = helper.GetProvider(result.Provider);
if ((int)provider == 0)
{
Logger.Fatal("Unknown Oauth Provider try to SignIn. Check Providers Name (maybe it changeed)");
return null; //todo MessageBox for Unkown Provider, or something wrong
}
// provider's unique ID for the user
var uniqueUserID = result.ProviderUserId;
// since we might use multiple identity providers, then
// our app uniquely identifies the user by combination of
// provider name and provider user id
var uniqueID = provider + "/" + uniqueUserID;
// we then log the user into our application
// we could have done a database lookup for a
// more user-friendly username for our app
FormsAuthentication.SetAuthCookie(uniqueID, false);
string userName;
string nameAndLsatName = string.Empty;
var userDataFromProvider = result.ExtraData;
if (provider.Equals(OauthProvider.Twitter))
{
userName = result.UserName;
}
else
{
userName = userDataFromProvider["username"];
nameAndLsatName = userDataFromProvider["name"];
}
//Check if user already is in Db with Provider
var chekUserName = Uow.Users.Data.Where(x => x.UserName == userName && x.UserGroup.Id == (int)provider).FirstOrDefault();
if (chekUserName == null)
{
MM.Data.Model.User user = new MM.Data.Model.User();
user.UserName = userName;
if (!provider.Equals(OauthProvider.Twitter))
{
user.FirstName = nameAndLsatName.Split(' ')[0];
user.LastName = nameAndLsatName.Split(' ')[1];
}
user.Email = userName; //it'a Email
if (provider.Equals(OauthProvider.Twitter))
{
user.ShowNameAndLastName = false;
}
else
{
user.ShowNameAndLastName = true;
}
user.GroupId = (int)provider;
if (provider.Equals(OauthProvider.Twitter))
{
user.ProfilePicture = helper.GetImageInBytesByProvider(provider, userName);
}
else
{
user.ProfilePicture = helper.GetImageInBytesByProvider(provider, uniqueUserID);
}
Uow.Users.Add(user);
Uow.SaveChanges();
}
//Valid Login
//todo need improvement
var userModel = Uow.Users.GetSingle(x => x.UserName == userName && x.UserGroup.Id == (int)provider);
Session["User"] = new LoggedUserModel
{
Id = userModel.Id,
UserName = userName,
ProfilePicture = userModel.ProfilePicture
};
Session["UserId"] = userModel.Id;
//FormsAuthentication.SetAuthCookie(useruserNamename, false);
if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
&& !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
// return View("", result);
}
return null; //need change
}
in the screenshot that you attached, I see that redirect_uri is your 192.168.77.155 ip. If you correct it, google will redirect back to the correct ip address.

Explicit password and email validation in Microsoft.AspNet.Identity, why needed?

I am big fan of Adam Freeman's books. At his Pro Asp.net mvc 5 platform, in chapter 13, page 325, the following code confused me. Does anyone have the explanation why he used the email and password validation explicitly?
The call this.UserManager.UpdateAsync(user) should return a result with same errors generated by this.UserManager.UserValidator.ValidateAsync(user) and this.UserManager.PasswordValidator.ValidateAsync(password). Is he not doing the same thing twice? Or there is a special purpose?
[HttpPost]
public async Task<ActionResult> Edit(string id, string email, string password)
{
AppUser user = await this.UserManager.FindByIdAsync(id);
if (user != null)
{
user.Email = email;
IdentityResult validEmail = await this.UserManager.UserValidator.ValidateAsync(user);
if (!validEmail.Succeeded)
{
this.AddErrorsFromResult(validEmail);
}
IdentityResult validPass = null;
if (password != string.Empty)
{
validPass = await this.UserManager.PasswordValidator.ValidateAsync(password);
if (validPass.Succeeded)
{
user.PasswordHash = this.UserManager.PasswordHasher.HashPassword(password);
}
else
{
this.AddErrorsFromResult(validPass);
}
}
if ((validEmail.Succeeded && validPass == null)
|| (validEmail.Succeeded && password != string.Empty && validPass.Succeeded))
{
IdentityResult result = await this.UserManager.UpdateAsync(user);
if (result.Succeeded)
{
return this.RedirectToAction("Index");
}
this.AddErrorsFromResult(result);
}
}
else
{
ModelState.AddModelError(string.Empty, "User not found");
}
return this.View(user);
}
private AppUserManager UserManager
{
get
{
return HttpContext.GetOwinContext().GetUserManager<AppUserManager>();
}
}
private void AddErrorsFromResult(IdentityResult result)
{
foreach (string error in result.Errors)
{
ModelState.AddModelError(string.Empty, error);
}
}
in source code of identity UserManager class UpdateAsync method is like this:
public virtual async Task<IdentityResult> UpdateAsync(TUser user)
{
ThrowIfDisposed();
if (user == null)
{
throw new ArgumentNullException("user");
}
var result = await UserValidator.ValidateAsync(user).ConfigureAwait(false);
if (!result.Succeeded)
{
return result;
}
await Store.UpdateAsync(user).ConfigureAwait(false);
return IdentityResult.Success;
}
that calls UserValidator.ValidateAsync(user) method for validating that username is not illegal or user not registered before with a different Owner Id and does not care for validating Email address or password string. if you want to validate passwords and do your custom checks you must create custom validators .
you can find Default UserValidator source code here

Authorize Attribute with Roles

I want to implement my custom authorization, I wonder what is wrong with my code even I got the user credentials correctly it still redirects me to my Login Method, please see the code below
Edit: I have successfully implemented the Authorize Attribute with Roles, for future readers please see code below
Login Controller
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login (AdminViewModels.Login viewModel, string returnURL)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
PasswordHasher passwordVerify = new PasswordHasher();
var query = (from acc in db.accounts.Where(x => x.username == viewModel.Username)
select new { acc.username, acc.password}).FirstOrDefault();
if (query != null)
{
if (ModelState.IsValid)
{
var result = passwordVerify.VerifyHashedPassword(query.password, viewModel.Password);
switch (result)
{
case PasswordVerificationResult.Success:
//set forms ticket to be use in global.asax
SetupFormsAuthTicket(viewModel.Username, viewModel.rememeberMe);
return RedirectToLocal(returnURL);
case PasswordVerificationResult.Failed:
ModelState.AddModelError("", "Wrong Username or Password");
return View(viewModel);
}
}
}
return View(viewModel);
}
Forms Auth Ticket
private account SetupFormsAuthTicket(string userName, bool persistanceFlag)
{
account user = new account();
var userId = user.id;
var userData = userId.ToString(CultureInfo.InvariantCulture);
var authTicket = new FormsAuthenticationTicket(1, //version
userName, // user name
DateTime.Now, //creation
DateTime.Now.AddMinutes(20), //Expiration
persistanceFlag, //Persistent
userData);
var encTicket = FormsAuthentication.Encrypt(authTicket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
return user;
}
Global.asax
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
//take out user name from cookies
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string[] roles = null;
trainingEntities db = new trainingEntities();
//query database to get user roles
var query = (from acc in db.account_roles where acc.account.username == username select acc.role.role_name).ToArray();
roles = query;
//Let us set the Pricipal with our user specific details
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles);
}
catch (Exception)
{
//somehting went wrong
}
}
}
}
Now you can use [Authorize(Roles = "Admin")]
to any action method or on top of controller
I have successfully implemented the Authorize Attribute with Roles, for future readers please see code below.
Login Controller
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult Login (AdminViewModels.Login viewModel, string returnURL)
{
if (!ModelState.IsValid)
{
return View(viewModel);
}
PasswordHasher passwordVerify = new PasswordHasher();
var query = (from acc in db.accounts.Where(x => x.username == viewModel.Username)
select new { acc.username, acc.password}).FirstOrDefault();
if (query != null)
{
if (ModelState.IsValid)
{
var result = passwordVerify.VerifyHashedPassword(query.password, viewModel.Password);
switch (result)
{
case PasswordVerificationResult.Success:
//set forms ticket to be use in global.asax
SetupFormsAuthTicket(viewModel.Username, viewModel.rememeberMe);
return RedirectToLocal(returnURL);
case PasswordVerificationResult.Failed:
ModelState.AddModelError("", "Wrong Username or Password");
return View(viewModel);
}
}
}
return View(viewModel);
}
FormsAuthTicket
private account SetupFormsAuthTicket(string userName, bool persistanceFlag)
{
account user = new account();
var userId = user.id;
var userData = userId.ToString(CultureInfo.InvariantCulture);
var authTicket = new FormsAuthenticationTicket(1, //version
userName, // user name
DateTime.Now, //creation
DateTime.Now.AddMinutes(20), //Expiration
persistanceFlag, //Persistent
userData);
var encTicket = FormsAuthentication.Encrypt(authTicket);
Response.Cookies.Add(new HttpCookie(FormsAuthentication.FormsCookieName, encTicket));
return user;
}
Global.asax
protected void Application_PostAuthenticateRequest(Object sender, EventArgs e)
{
if (FormsAuthentication.CookiesSupported == true)
{
if (Request.Cookies[FormsAuthentication.FormsCookieName] != null)
{
try
{
//take out user name from cookies
string username = FormsAuthentication.Decrypt(Request.Cookies[FormsAuthentication.FormsCookieName].Value).Name;
string[] roles = null;
trainingEntities db = new trainingEntities();
//query database to get user roles
var query = (from acc in db.account_roles where acc.account.username == username select acc.role.role_name).ToArray();
roles = query;
//Let us set the Pricipal with our user specific details
HttpContext.Current.User = new System.Security.Principal.GenericPrincipal(
new System.Security.Principal.GenericIdentity(username, "Forms"), roles);
}
catch (Exception)
{
//somehting went wrong
}
}
}
}
Now you can use [Authorize(Roles = "Admin")]
to any action method or on top of controller
as I see in ControllerLogin attribute it is now being applied in a variable, when it should be applied to a method or a class
[CustomAuthorization(UserRole="Admin")]
// GET: Manage
private trainingEntities db = new trainingEntities();
public ActionResult Index()
{
return View();
}
Private trainingEntities dB = new TrainingEntities();
[CustomAuthorization(UserRole="Admin")]
Public ActionResult Index()
{
//yourcode
}

How can I restrict access until user has confirmed email link

I am finally able to send Email confirmation on my MVC 5 Application
The user now receives an email and the EmailConfirmed field is updated from False to True. However, the user is still able to login without confirming the email.
My question is how can I restrict access until user has confirmed email link
Below is my ConfirmEmail Method.
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string Token, string Email)
{
ApplicationUser user = this.UserManager.FindById(Token);
if (user != null)
{
if (user.Email == Email)
{
user.EmailConfirmed = true;
await UserManager.UpdateAsync(user);
//await SignInAsync(user, isPersistent: false);
return RedirectToAction("Index", "Home", new { ConfirmedEmail = user.Email });
}
else
{
return RedirectToAction("Confirm", "Account", new { Email = user.Email });
}
}
else
{
return RedirectToAction("Confirm", "Account", new { Email = "" });
}
}
[AllowAnonymous]
public ActionResult Confirm(string Email)
{
ViewBag.Email = Email; return View();
}
Thank you everyone for reading.
Ceci
----- UPDATE ------
I added the code below to the /Account/Login Controller
var user = await UserManager.FindByNameAsync(model.UserName);
if(user != null){
if (!await UserManager.IsEmailConfirmedAsync(user.UserName)) {
return View("ErrorNotConfirmed");
}
}
But its returning an error. UserId not Found.
I am posting this code in case someone needs it.
Basically I replaced the code above with this code:
var userid = UserManager.FindByEmail(model.UserName).Id;
if (!UserManager.IsEmailConfirmed(userid))
{
return View("EmailNotConfirmed");
}
It works beautifully now.

Check if user exists in MVC4

I have simple login form without registration, because I create Admin login, who create new users. So admin login, and create new user, which can then login with that specific username and password.
So I create this controller:
public ActionResult CreateNew(Models.Users user)
{
if (ModelState.IsValid)
{
try
{
using (var dataU = new userDbEntities())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(user.Password);
var sysUser = dataU.UsersTables.Create();
sysUser.username = user.Username;
sysUser.password = encrpPass;
sysUser.passwordSalt = crypto.Salt;
sysUser.TimeZoneId = user.TimeZoneName;
sysUser.Customer = user.Customer;
dataU.UsersTables.Add(sysUser);
dataU.SaveChanges();
return RedirectToAction("Registration", "LoginAdmin");
}
}
catch (Exception ex)
{
string error = ex.Message;
}
}
return View(user);
}
Problem is, that I can create users with same username (this is not ok!), so how to check if user with that name exists and returns, this username already exists...
thanks...
count the number of user that has the same username and add the user if the count is 0.
for example
var count = dataU.UsersTables.Count(u=>u.UserName == usernameyouwanttocheck);
if(count==0)
{
//add user
}
else
{
//alert user saying user exists
}
if I were you I would make repository and create a function that checks if the user exists or not and call that function from controller.
By help of Biplov13 I create this, which is working:
public ActionResult CreateNew(Models.Users user)
{
if (ModelState.IsValid)
{
try
{
using (var dataU = new userDbEntities())
{
{
var crypto = new SimpleCrypto.PBKDF2();
var encrpPass = crypto.Compute(user.Password);
var sysUser = dataU.UsersTables.Create();
sysUser.username = user.Username;
sysUser.password = encrpPass;
sysUser.passwordSalt = crypto.Salt;
sysUser.TimeZoneId = user.TimeZoneName;
sysUser.Customer = user.Customer;
var count = dataU.UsersTables.Count(u => u.username == user.Username);
if (count == 0)
{
dataU.UsersTables.Add(sysUser);
dataU.SaveChanges();
return RedirectToAction("Registracija", "LoginAdmin");
}
else
{
// something to do if user exist...
}
}
}
}
catch (Exception ex)
{
string error = ex.Message;
}
}
return View(user);
}

Resources