I have an Asp MVc web project. In order to sell product, the user should register or login to my website. After choosing its product, the user will redirect to bank gateway through PaymentAction method:
public String PaymentAction( TransAction Model )
{
try
{
Payment ob = new Payment();
Model.amount = 100000.ToString();
string result = ob.pay(Model.amount);
//, User.Identity.GetUserId()
/*
the result var is a string that contains the response from pay.ir/send
which contains: status, transId, errorCode, errorMessage and all things that
exist in JsonParameter
*/
JsonParameters Parmeters = JsonConvert.DeserializeObject<JsonParameters>(result);
// in this point the payment was successful and you can add info to your database
if ( Parmeters.status == 1 )
{
Response.Redirect("https://pay.ir/payment/gateway/" + Parmeters.transId);
}
else
{
return "error code : " + Parmeters.errorCode + "<br />" + "message " + Parmeters.errorMessage;
}
return "";
}
catch ( Exception exp )
{
return "error" + exp.Message;
}
}
after payment, the user redirect to my website through the following url:
http://www.mymvcapp.com/HelpMeToBuildMyExtraordinaryYear/VerifyPayment
and here is the VerifyPayment method:
[HttpPost]
[AllowAnonymous]
public ActionResult VerifyPayment( VerifyResult Vresult )
{
try
{
if ( !string.IsNullOrEmpty(Request.Form["transId"]) )
{
Payment ob = new Payment();
string result = ob.verify(Request.Form["transId"].ToString());
JsonParameters Parmeters = JsonConvert.DeserializeObject<JsonParameters>(result);
if ( Parmeters.status == 1 )
{
var userId = User.Identity.GetUserId();
var user = db.Users.Where(u => u.Id == userId).FirstOrDefault();
user.SuccessfullPayment = true;
user.FactorNo = User.Identity.GetUserId();
user.TraceNo = Request.Form["traceNumber"];
user.TransId = int.Parse(Request.Form["transId"]);
user.CardNo = Request.Form["cardNumber"];
user.PurchasedDate = DateTime.Now;
user.State = Parmeters.status;
user.Message = Request.Form["message"];
db.Entry(user).State = System.Data.Entity.EntityState.Modified;
db.SaveChanges();
Vresult.success = true;
Vresult.TransActionID += Request.Form["transId"].ToString();
Vresult.Amount += Parmeters.amount.ToString();
Vresult.SuccessMessage = "successful payment";
return RedirectToAction("Index", "DownloadEbook", new { traceNumber = user.TraceNo , factorNumber = user.FactorNo, purchaseDate =Utils.Funcs.ObtainPersianDate( (DateTime)user.PurchasedDate ) });
}
else
{
Vresult.error = true;
Vresult.ErrorMessage = "error code " + Parmeters.errorCode + "<br />" + "Errr meesafe " + Parmeters.errorMessage;
}
}
}
catch ( Exception ex )
{
Vresult.error = true;
Vresult.ErrorMessage = ex.Source+"\t"+ex.InnerException + "\t" + ex.Message+"ERRR";
}
return View(new AllNeededModels() { VerifyResult = Vresult });
as we can see the user must be logged in in order to complete the sale process. but after redirecting from bank to above url (VerifyPayment), the user is NOT logged in and the code will return a null exception.
the question is how should I keep user logged in after redirecting from bank to my website?
or how can get user from cookie and sign that user in?
the problem is araised in the process of getting user. we should use this code in order to get user:
var user = System.
Web.
HttpContext.
Current.
GetOwinContext().
GetUserManager<ApplicationUserManager>().
FindById(userId);
note that the correct approach is as above. the following code produces the problem. doNOT use it to obtain current user:
var user = db.Users.Where(u => u.Id == userId).FirstOrDefault();
Related
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.
I am trying to add two fields to my UserPofile table in WebMatrix. Everytime I run the code I get this message: Account creation was unsuccessful. Please correct the errors and try again. The username is already in use.
But, when I look in the table I don't see the new fields.
Here is my code:
if (Validation.IsValid()) {
var db = Database.Open("StarterSite");
var user = db.QuerySingle("SELECT Email FROM UserProfile WHERE LOWER(Email) = LOWER(#0)", email);
if (user == null) {
db.Execute("INSERT INTO UserProfile (Email) VALUES (#0)", email);
try {
bool requireEmailConfirmation = !WebMail.SmtpServer.IsEmpty();
<!-- var token = WebSecurity.CreateAccount(email, password, requireEmailConfirmation);-->
var token = WebSecurity.CreateUserAndAccount(email, password, new {UserName = name, UserLocation = location}, requireEmailConfirmation);
if (requireEmailConfirmation) {
var hostUrl = Request.Url.GetComponents(UriComponents.SchemeAndServer, UriFormat.Unescaped);
var confirmationUrl = hostUrl + VirtualPathUtility.ToAbsolute("~/Account/Confirm?confirmationCode=" + HttpUtility.UrlEncode(token));
WebMail.Send(
to: email,
subject: "Please confirm your account",
body: "Your confirmation code is: " + token + ". Visit " + confirmationUrl + " to activate your account."
);
}
if (requireEmailConfirmation) {
Response.Redirect("~/Account/Thanks");
} else {
WebSecurity.Login(email, password);
Response.Redirect("~/");
}
} catch (System.Web.Security.MembershipCreateUserException e) {
ModelState.AddFormError(e.Message);
}
} else {
ModelState.AddFormError("Email address is already in use.");
}
I have a code that sends email to user. In the email, there's a link in there that they should visit with the corresponding ID in order for them to be directed to a certain page.
Here's my code:
public void Notify(int appr_id = 0)
{
var check = db.rms_approval_routing.Where(s => s.appr_id == appr_id && s.appr_isactive == true).FirstOrDefault();
try
{
if (check != null)
{
check.status_id = 8;
db.Entry(check).State = EntityState.Modified;
db.SaveChanges();
var getinfo = db.rms_approval_route_vw.Where(s => s.appr_id == appr_id && s.appr_isactive == true).FirstOrDefault();
var getpayment = db.rms_payment.Where(s => s.appr_id == appr_id).FirstOrDefault();
if (getinfo != null && getpayment != null)
{
var ref_email = getinfo.ref_email;
var cc_email = getinfo.user_email;
var pay = getpayment.p_amount;
var body = "";
body = "Good day!<br><br>Please be informed that you have successfully referred <u>" + getinfo.Fullname + "</u> and you are entitled to receive <u>P " + pay + "</u> which will be credited on the next payout for your successful referral.<br>Kindly visit the link to acknowledge the payment: http://localhost:8119/ReferralLetter/Acknowledge/" + appr_id + " <br>Thanks!";
SendEmailController email = new SendEmailController();
email.SendReferrer(ref_email, cc_email, body);
}
}
}
catch (Exception)
{
throw;
}
}
public ActionResult Acknowledge(int appr_id = 0)
{
var check = db.rms_emails.Where(s => s.appr_id == appr_id && s.email_date_ack == null && s.email_isactive == true).FirstOrDefault();
if (check != null) {
ViewBag.email_id = check.email_id;
ViewBag.appr_id = appr_id;
return PartialView();
}
return RedirectToAction("Denied");
}
In this line: http://localhost:8119/ReferralLetter/Acknowledge/" + appr_id
The appr_id value is 0 when I tried to breakpoint the Acknowledge function. When I received the email, it showed there this line: http://localhost:8119/ReferralLetter/Acknowledge/23
Meaning there's an ID in there but why in the Acknowledge function the ID was 0?
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);
}
I am trying to insert datas to Appointment table of my database. I did registration part of my project which works well. There are 2 tables, Patient and Appointment. After Login patients can make an appointment. Patient number comes like this
MyUser.PatientNo = Guid.NewGuid().GetHashCode();
For appointment date and description comes from textbox. And I want to insert PatientNo from Patient table to Appointment table. For me it looks done but when I choose date and write description but I got error on this line app.PatientNo = patient.PatientNo;
An exception of type 'System.NullReferenceException' occurred in DentAppSys.dll but was not handled in user code
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Make(Models.AppModel User)
{
if (Session["UserEmail"] != null)
{
using (var db = new MaindbModelDataContext())
{
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
var app = new Appointment();
app.Date = User.Date;
app.Description = User.Description;
app.Status = "true";
app.PatientNo = patient.PatientNo;
db.Appointments.InsertOnSubmit(app);
db.SubmitChanges();
return RedirectToAction("Make", "Appointment");
}
}
else
{
return RedirectToAction("Index", "User");
}
}
}
}
and this is registration part which is working well
public ActionResult RegAndLogin(Models.RegAndLog User)
{
if (User.RegisterModel != null)
{
if (ModelState.IsValid)
{
using (var db = new MaindbModelDataContext())
{
var Person = db.Patients.FirstOrDefault(u => u.Email == User.RegisterModel.Email);
if (Person == null)
{
string Hash = BCrypt.Net.BCrypt.HashPassword(User.RegisterModel.Password);
var MyUser = new Patient();
MyUser.Name = User.RegisterModel.Firstname;
MyUser.Surname = User.RegisterModel.Lastname;
MyUser.Birthday = User.RegisterModel.Birthday;
MyUser.Email = User.RegisterModel.Email;
MyUser.Password = Hash;
MyUser.PatientNo = Guid.NewGuid().GetHashCode();
db.Patients.InsertOnSubmit(MyUser);
db.SubmitChanges();
Session["UserEmail"] = User.RegisterModel.Email;
return RedirectToAction("Index", "Patient", User.RegisterModel);
}
else
{
ModelState.AddModelError("", "There is a user with this Email. Please enter another Email !!!");
return View();
}
}
}
else
{
ModelState.AddModelError("", "Data is incorrect !!!");
}
}
else
{
if (ModelState.IsValid && IsValid(User.LoginModel.Email, User.LoginModel.Password))
{
var TempUser = new Models.RegisterModel();
Session["UserEmail"] = User.LoginModel.Email;
using (var db = new MaindbModelDataContext())
{
var person = db.Patients.FirstOrDefault(u => u.Email == User.LoginModel.Email);
TempUser.Firstname = person.Name;
TempUser.Lastname = person.Surname;
//TempUser.RegisterModel.Birthday = (DateTime)person.BirthDate;
TempUser.Email = person.Email;
}
return RedirectToAction("Index", "Patient", TempUser);
}
else
{
ModelState.AddModelError("", "Check your E-mail or Password then try again !!!");
}
}
return View();
If you're getting a null exception on the line
app.PatientNo = patient.PatientNo;
It will be because either app or patient are null at when it's executed. I would suspect patient.
Check that patient is found correctly at the line
var patient = db.Patients.FirstOrDefault(u => u.Email == (String)Session["UserEmail"]);
if it isn't found patient will be null.