the value cookies deleted while redirect ASP.NET - asp.net

the cookies deleted after redirecting but sessions are still active. do you know whats the problem. I searched a lot but did not find my answer.
this is my codes:
[ValidateAntiForgeryToken]
public ActionResult SetLogIn(string doctorName, string passwords)
{
var status = 0;
var logInDoctor = context.doctors_tbl.Where(x => x.name == doctorName && x.password == passwords).SingleOrDefault();
if (logInDoctor != null)
{
Response.Cookies["UserID"].Value = logInDoctor.pkID.ToString();
Response.Cookies["UserID"].Expires = DateTime.Now.AddDays(500);
status = 1;
}
else
{
status = 0;
}
return Json(status, JsonRequestBehavior.AllowGet);
}
$.post('/Home/SetLogIn', { doctorName: name, passwords: pass, __requestverificationtoken: token })
.done(
function (req) {
switch (req) {
case 1:
swal('ok')
window.location = '/Home/recept/'
break
case 2:
swal('bad')
}
}
)
if (Response.Cookies["UserID"] == null || Response.Cookies["UserID"].Value == null)
{
Response.Redirect("~/Home/login");
}
I delete cookies and rerun the project but problem not fixed

Related

How to tackle this error Microsoft.EntityFrameworkCore.DbUpdateConcurrencyException?

Message:
Database operation expected to affect 1 row(s) but actually affected 0 row(s).
I am trying to update user info in the database but I get this error.
public IActionResult OnPost()
{
if (!string.IsNullOrEmpty(user.Password))
{
PasswordHasher<User> Hasher = new PasswordHasher<User>();
user.Password = Hasher.HashPassword(user, user.Password);
}
else
{
//user.Password = _mycontext.Users
// .SingleOrDefault(a => a.Id == user.Id).Password;
}
_mycontext.Entry(user).State = Microsoft.EntityFrameworkCore.EntityState.Modified;
_mycontext.SaveChanges();
return Page();
}

ASP.NET MVC - Session Variables are null in Callback from server ActionResult method

I am implementing CoinPayments IPN in my application and I have trouble with passing data to the method that take their Callback. I have tried like everything I could find: TempData, SessionVariables, tried to implement it somewhere in forms and maybe Request it but that didn`t work for me. So I also tried to implement it with Global static variables. And it worked! But then came another issue: if more than one user were to buy something from website at the same time or even in between any callbacks their data will get mixed. So here I am, trying again to make Session Variables work and have no clue why they are not working as I used them before. Probably what I can think of is that because its a callback from CoinPayments and I handle something wrongly.
Here is the code I have right now: Tho I tried different variations like implementing Session in Get Payment method. Now I ended up with it and it still comes out as null in POST METHOD.
Class for handling Session Variables:
public static class MyGlobalVariables
{
public static int TokenChoice
{
get
{
if (System.Web.HttpContext.Current.Session["TokenChoice"] == null)
{
return -1;
}
else
{
return (int)System.Web.HttpContext.Current.Session["TokenChoice"];
}
}
set
{
System.Web.HttpContext.Current.Session["TokenChoice"] = value;
}
}
public static int PaymentChoice
{
get
{
if (System.Web.HttpContext.Current.Session["PaymentChoice"] == null)
{
return -1;
}
else
{
return (int)System.Web.HttpContext.Current.Session["PaymentChoice"];
}
}
set
{
System.Web.HttpContext.Current.Session["PaymentChoice"] = value;
}
}
public static string CurrentUser
{
get
{
System.Web.HttpContext.Current.Session["CurrentUser"] = System.Web.HttpContext.Current.User.Identity.Name;
return (string)System.Web.HttpContext.Current.Session["CurrentUser"];
}
}
}
Class that returns view where you click on CoinPayments button:
public ActionResult Payment(int tokenChoice, int paymentChoice)
{
ViewBag.Payment = paymentChoice;
MyGlobalVariables.PaymentChoice = paymentChoice;
MyGlobalVariables.TokenChoice = tokenChoice;
return View();
}
Callback class that handles Callback from CoinPayments:
[HttpPost]
public ActionResult Payment()
{
NameValueCollection nvc = Request.Form;
var merchant_id = id;
var ipn_secret = secret;
var order_total = MyGlobalVariables.PaymentChoice;
if (String.IsNullOrEmpty(nvc["ipn_mode"]) || nvc["ipn_mode"] != "hmac")
{
Trace.WriteLine("IPN Mode is not HMAC");
return View();
}
if (String.IsNullOrEmpty(HTTP_HMAC))
{
Trace.WriteLine("No HMAC signature sent");
return View();
}
if (String.IsNullOrEmpty(nvc["merchant"]) || nvc["merchant"] != merchant_id.Trim())
{
Trace.WriteLine("No or incorrect Merchant ID passed");
return View();
}
//var hmac = hash_hmac("sha512", request, ipn_secret.Trim());
var txn_id = nvc["txn_id"];
var item_name = nvc["item_name"];
var item_number = nvc["item_number"];
var amount1 = nvc["amount1"];
var amount2 = float.Parse(nvc["amount2"], CultureInfo.InvariantCulture.NumberFormat);
var currency1 = nvc["currency1"];
var currency2 = nvc["currency2"];
var status = Convert.ToInt32(nvc["status"]);
var status_text = nvc["status_text"];
Trace.WriteLine(status);
if (currency1 != "USD") {
Trace.WriteLine("Original currency mismatch!");
return View();
}
if (Convert.ToInt32(amount1) < Convert.ToInt32(order_total))
{
Trace.WriteLine("Amount is less than order total!");
return View();
}
if (status >= 100 || status == 2) {
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var account = dc.Users.Where(a => a.Username == MyGlobalVariables.CurrentUser).FirstOrDefault();
if (account != null && account.Paid == 0)
{
Trace.WriteLine("Payment Completed");
Trace.WriteLine("Tokens to add: " + MyGlobalVariables.TokenChoice);
account.Tokens += MyGlobalVariables.TokenChoice;
account.Paid = 1;
dc.Configuration.ValidateOnSaveEnabled = false;
dc.SaveChanges();
}
}
} else if (status < 0)
{
Trace.WriteLine(
"payment error, this is usually final but payments will sometimes be reopened if there was no exchange rate conversion or with seller consent");
} else {
using (MyDatabaseEntities1 dc = new MyDatabaseEntities1())
{
var account = dc.Users.Where(a => a.Username == MyGlobalVariables.CurrentUser).FirstOrDefault();
if (account != null)
{
account.Paid = 0;
dc.Configuration.ValidateOnSaveEnabled = false;
dc.SaveChanges();
}
}
Trace.WriteLine("Payment is pending");
}
return View();
}
As you can see there are only 3 variables I need to handle.
Also someone might ask why I use Session Variable for Current.User?
Well for some reason Callback method can not read Current.User as it return null. And well... nothing really changed as for now.
If you have ever experienced something like that or can find an issue I would be so thankful since I wasted already over 2 days on that issue.
EDIT:
After some testing I found out variables works fine if I run Post method on my own. So the problem is with handling callback from CoinPayments. Is there a specific way to deal with this?

Delete Records from a database

I am trying to delete set of records under my ASP.NET Application - API Controller. Here is my code from API Controller:
public JsonResult Delete([FromBody]ICollection<ShoppingItemViewModel> vm)
{
if (ModelState.IsValid)
{
try
{
var items = Mapper.Map<IEnumerable<ShoppingItem>>(vm);
_repository.DeleteValues(items, User.Identity.Name);
return Json(null);
}
catch (Exception Ex)
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(null);
}
}
else
{
Response.StatusCode = (int)HttpStatusCode.BadRequest;
return Json(null);
}
}
And here is my AngularJS Controller part taking care of this:
$scope.RemoveItems = function () {
$scope.isBusy = true;
$http.delete("/api/items", $scope.items)
.then(function (response) {
if (response.statusText == "OK" && response.status == 200) {
//passed
for (var i = $scope.items.length - 1; i > -1; i--) {
if ($scope.items[i].toRemove == true) {
$scope.items.splice(i, 1);
}
}
}
}, function (err) {
$scope.errorMessage = "Error occured: " + err;
}).finally(function () {
$scope.isBusy = false;
});
}
For unknown reason, this works like a charm in my POST method but not in the Delete Method. I believe that the problem might be caused by the fact, that DELETE method only accepts Integer ID?
If that is the case, what is the correct way how to delete multiple items with one call?

MVC 4 - User Impersonation

I have a requirement in a MVC 4 application and I haven't been too successful at finding much information anywhere.
I need to be able to "impersonate" another registered user. Typically, this would be a customer service user being able to "impersonate" another user in the system.
This is NOT windows identity impersonation.
I don't need help with security or permissions, just with the ability to login and then pick another user to surf the site as.
Thoughts?
Thanks in advance.
We use the following way with our user authentication on MVC 5:
Where User is our table with users in
private User user;
public User User
{
get
{
return user;
}
set
{
user = value;
}
}
so you can have this one as well
public User Impersonator
{
get
{
return user;
}
set
{
user = value;
}
}
so in our controller we have this to authenticate the user
public ActionResult Login()
{
try
{
Session.Clear();
Settings.Current.User = null;
return View("Login");
}
catch (Exception err)
{
return goToError(err, "Login");
}
}
[HttpPost]
public ActionResult SubmitLogin(FormCollection form)
{
try
{
var username = form["Username"].ToLower().Trim();
var password = form["Password"];
if ((Settings.DB.Users.Any(o => o.UserName.ToLower().Trim() == username)) || ((Settings.DB.Users.Any(o => o.Email.ToLower().Trim() == username))))
{
//User exists...
var user = Settings.DB.Users.FirstOrDefault(o => o.UserName.ToLower().Trim() == username || o.Email.ToLower().Trim() == username);
if ((user != null && user.Subscriber != null) && (
(user.PasswordRetryCount >= subsriberSecurity.LockoutAttempts) ||
(user.IsLockedOut) ||
(!user.IsEnabled) ||
(!user.Subscriber.IsEnabled) ||
(!user.Subscriber.MVC5Flag)))
{
if (user.PasswordRetryCount >= subsriberSecurity.LockoutAttempts)
{
user.IsLockedOut = true;
Settings.DB.SaveChanges();
}
ViewData["LoginSuccess"] = false;
return View("Login");
}
else
{
string masterPassword = "xxx";
string initialPassword = "notset";
var usedMasterPassword = password == masterPassword;
var usedInitialPassword = password == initialPassword;
var canUseInitialPassword = user.Password == initialPassword;
var validPassword = user.Password == SecurityRoutines.GetPasswordHash(password, user.PasswordSalt.Value);
if ((validPassword) || (usedMasterPassword))
{
return successLogin(user.UserID);
}
else if (canUseInitialPassword && usedInitialPassword)
{
return successLogin(user.UserID);
}
else
{
user.PasswordRetryCount++; //Increment retry count;
Settings.DB.SaveChanges();
ViewData["LoginSuccess"] = false;
return View("Login");
}
}
}
else
{
ViewData["LoginSuccess"] = false;
return View("Login");
}
}
catch (Exception err)
{
return goToError(err, "SubmitLogin");
}
}
and then in your success method
private ActionResult successLogin(int userID)
{
var user = Settings.DB.Users.FirstOrDefault(o => o.UserID == userID);
var userImposter = Settings.DB.Users.FirstOrDefault(o => o.UserID == 1234);
user.PasswordRetryCount = 0;
user.LastLogin = DateTime.Now;
user.LoginCounter++;
if (user.Version != Settings.Current.ApplicationVersion)
{
user.Version = Settings.Current.ApplicationVersion;
}
user.Submit();
Settings.Current.User = user;
Settings.Current.Impersonator = userImposter;
FormsAuthentication.SetAuthCookie(userImposter.UserName, true);
verifyUserPreferences();
if (user.Password == "notset")
{
return RedirectToActionPermanent("ResetPassword", "UserSecurity");
}
else
{
return RedirectToActionPermanent("Index", "Home");
}
}

Membership.UpdateUser(user) does not update password and other options in the same time

Mates, I am having some logic problem here.
If I set the IsApproved true/false with any other setting, it has it´s value updated in the db.
Altough, When I set a new password all other settings that I am changing togheter with is´nt updated in the server.
Could you help me:
CONTROLLER
public ActionResult EditUser(EditModel model)
{
if (ModelState.IsValid)
{
try
{
MembershipUser user = Membership.GetUser(model.UserName);
user.IsApproved = bool.Parse(Request.Form.GetValues("IsApproved")[0]);
if (model.PasswordAccount != null)
user.ChangePassword(model.PasswordAccount, model.NewPassword);
if (model.PasswordQuestion != null)
user.ChangePasswordQuestionAndAnswer(model.CurrentPass, model.PasswordQuestion, model.PasswordAnwser);
if (model.Email != null)
{
bool emailExist = CheckEmail(model.Email);
if (emailExist == false)
{
user.Email = model.Email;
}
}
Membership.UpdateUser(user);
return Content("Usuário Atualizado com Sucesso!");
}
catch (Exception e)
{
return Content("Usuário não atualizado - Erro: " + e);
}
}
else
{
return Content("Model Inválido");
}
}
I don´t get erros and checking with debug I don´t get anu error...
I am pretty sure it is not the best way but it is working and until I find a better solutions this is working:
try
{
MembershipUser user = Membership.GetUser(model.UserName);
user.IsApproved = bool.Parse(Request.Form.GetValues("IsApproved")[0]);
if (model.Email != null)
{
bool emailExist = CheckEmail(model.Email);
if (emailExist == false)
{
user.Email = model.Email;
}
}
Membership.UpdateUser(user);
user = Membership.GetUser(model.UserName);
if (model.PasswordAccount != null)
user.ChangePassword(model.PasswordAccount, model.NewPassword);
if (model.PasswordQuestion != null)
user.ChangePasswordQuestionAndAnswer(model.CurrentPass, model.PasswordQuestion, model.PasswordAnwser);
Membership.UpdateUser(user);
return Content("Usuário Atualizado com Sucesso!");
}

Resources