How can I get the user's userID from Login Controller and pass it to the other controllers and views?
LOGIN CONTROLLER
public ActionResult Index(Table_User user)
{
var user1 = repo.Find(x => x.UserMail== user.UserMail);
if (user1 != null)
{
if (SecurityAlgorithms.CheckMD5Hash(user.UserPassword, user1.UserPassword))
{
FormsAuthentication.SetAuthCookie(user1.UserName, false);
Session["user1"] = user.UserName;
return RedirectToAction("Index", "Home", new { area = "" });
}
else
{
ViewBag.ErrorMessage = "Check your password!";
return View("Index", user);
}
}
You can use Tempdata or use return RedirectToAction("Action", "Controller", new { userID= user.userID });
Related
I am trying to create restrictions in my WebApp. I want to create that every registered and logged-in User can see only their own post and can not see, edit or delete other posts.
So far I try to follow some posts here but this post doesn't give me more information.
Solution 1
So only if the user is Register their should be able to see their own posts not another post from other users.
Anyone, how can tell me and guide me what Do I need to do?
P.S: I also look and the [Authorize] attribute is not the solution which I am looking.
Here is my code:
public IActionResult Upsert(int? Id)
{
TicketVM ticketVM = new TicketVM()
{
Ticket = new Ticket(),
TicketTypeList = _unitOfwork.TicketType.GetAll().Select(i => new SelectListItem
{
Text = i.Name,
Value = i.Id.ToString()
}),
ApplicationUser = new ApplicationUser(),
Client = new Client()
};
if (Id == null)
{
return View(ticketVM);
}
ticketVM.Ticket = _unitOfwork.Ticket.Get(Id.GetValueOrDefault());
if (ticketVM.Ticket == null)
{
NotFound();
}
return View(ticketVM);
}
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Upsert(TicketVM ticketVM)
{
var userName = User.FindFirstValue(ClaimTypes.Email);
var user = HttpContext.User.Identity.Name;
if (ModelState.IsValid)
{
if (ticketVM.Ticket.Id == 0)
{
ticketVM.Ticket.ApplicationUser = _db.ApplicationUsers.FirstOrDefault(u => u.Email == userName);
ticketVM.Ticket.Status = TicketStatus.Otvoren.ToString();
_unitOfwork.Ticket.Add(ticketVM.Ticket);
}
else
{
_unitOfwork.Ticket.Update(ticketVM.Ticket);
}
_unitOfwork.Save();
return RedirectToAction(nameof(Index));
}
return View(ticketVM);
}
public IActionResult Details(int? Id)
{
TicketVM ticketVM = new TicketVM()
{
Ticket = _unitOfwork.Ticket.Get(Id.GetValueOrDefault())
};
if (Id == null)
{
return NotFound();
}
var ticketType = _unitOfwork.Ticket.GetAll(includeProperties: "TicketType,ApplicationUser");
if (ticketVM.Ticket == null)
{
return NotFound();
}
return View(ticketVM);
}
I need help with this code snippet, it is in ASP.NET MVC, I would like to pass it to ASP.NET CORE MVC, however some things I am not finding the similar in ASP.NET core.
public ActionResult Login()
{
VMLogin vm = new VMLogin();
return View(vm);
}
[HttpPost]
public ActionResult Login(VMLogin vm)
{
if (ModelState.IsValid)
{
Usuario usuarioDb = db.Usuarios.Where(u => u.Login == vm.Login).FirstOrDefault();
if (usuarioDb == null)
{
ModelState.AddModelError("", "Não existe usuário com este Login");
return View(vm);
}
bool senhaConfere = Crypto.VerifyHashedPassword(usuarioDb.Senha, vm.Senha);
if (!senhaConfere)
{
ModelState.AddModelError("", "Senha incorreta");
return View(vm);
}
string authId = Guid.NewGuid().ToString();
Session["AuthID"] = authId;
var cookie = new HttpCookie("AuthID");
cookie.Expires = DateTime.Now.AddDays(7);
cookie.Value = authId;
Response.Cookies.Add(cookie);
usuarioDb.AuthId = authId;
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
return View(vm);
}
public ActionResult Logout()
{
if (Request.Cookies.AllKeys.Contains("AuthID"))
{
String authId = Request.Cookies["AuthID"].Value;
Usuario usuarioDb = db.Usuarios.Where(c => c.AuthId == authId).FirstOrDefault();
if (usuarioDb != null)
{
usuarioDb.AuthId = "";
db.SaveChanges();
}
Request.Cookies.Remove("AuthID");
if (Session["AuthID"] != null)
{
Session.Remove("AuthID");
}
}
return RedirectToAction("Index", "Home");
}
Im trying to get the current user form the session UserId but get this error. 'Unable to cast object of type 'System.Int32' to type 'Trinity.Models.tblUser'.'
Where I createthe Session Id:
[HttpPost]
public ActionResult Authorise(tblUser user)
{
using (var db = new TrinityEntities())
{
var userEmail = db.tblUsers.FirstOrDefault(x => x.Email == user.Email);
var userPassword = db.tblUsers.FirstOrDefault(y => y.Password == user.Password);
//check login incorrect
if (userEmail == null || userPassword == null)
{
ViewBag.LoginIncorrect = "E-mail or Password not correct";
return View("Index", user);
}
else
{
Session["UserID"] = userEmail.Id;
return RedirectToAction("Index", "Home");
}
}
}
Where I get the error:
public ActionResult Index()
{
if (Session["UserID"] == null)
{
return Redirect("/");
}
var currentUser = (Models.tblUser) Session["UserID"];
using (var db = new Models.ChatContext())
{
ViewBag.allUsers = db.Users.Where(u => u.FirstName != currentUser.FirstName).ToList();
}
ViewBag.currentUser = currentUser;
return View();
}
You're only storing the ID (a number) but when you read it back you're expecting the whole user - that's not going to work. Instead you'll need to use the ID to reload the user:
var currentUserId = Session["UserID"];
var user = db.tblUsers.FirstOrDefault(x => x.Id == currentUserId);
I am developing MVC application.
I am trying To Pass cityid to _CreateCityWiseArea action method from CityWiseAreaList in same controller.
But data doesn't pass properly.
_CreateCityWiseArea action method getting null value.
Please check below code...
This Is My Area Controller:
public ActionResult CityWiseAreaList(int cityid)
{
if (cityid == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var data = db.Areas.Where(x => x.CityID == cityid).ToList();
//TempData["ID"] = cityid;
RedirectToAction("_CreateCityWiseArea", new RouteValueDictionary(
new { controller = "Area", action = "_CreateCityWiseArea", id = cityid }));
return View(data);
}
public ActionResult _CreateCityWiseArea(int? id)
{
// var cityid = Convert.ToInt32(TempData["ID"]);
if (id == 0)
{
return new HttpStatusCodeResult(HttpStatusCode.BadRequest);
}
var Name = db.Cities.Where(c => c.CityID == id).Select(x => x.CityName).FirstOrDefault();
ViewBag.message = Name;
return View();
}
//Add Area to Corresponding city
// POST: Area/Create
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult _CreateCityWiseArea(Area area)
{
if (ModelState.IsValid)
{
db.Areas.Add(area);
db.SaveChanges();
return RedirectToAction("CityWiseAreaList");
}
ViewBag.CityID = new SelectList(db.Cities, "CityID", "CityName", area.CityID);
return PartialView(" ~/Views/Area/_CreateCityWiseArea.cshtml", area);
}
I Use Redirectoaction, tempdata method to pass Value but both time null value is coming.
You want to pass id from CityWiseAreaList to _CreateCityWiseArea this should be simple, since it's in the same Controller you don't need to add the RouteValueDictionary but it's your choice anyway. The below should work, that's the way I'll go:
return RedirectToAction("_CreateCityWiseArea", new { id = cityid });
I need your help. I'm trying to make a custom registration/login in MVC.Net, which uses SimpleCripto to encrypt the passwords. After I register a user everything is saved in my table and it seems all right, but when I try to LogIn I get an error - "The salt was not in an expected format of {int}.{string}", which comes from my "IsValid" method, in the statement "if (user.Password == crypto.Compute(user.PasswordSalt, password))". I'll post my AuthenticantionController with the Register and LogIn methods and if you can point where the problem is and how to solve it I'll be grateful. Thanks in advance !
namespace Final.Controllers
{
public class AuthenticationController : Controller
{
[HttpGet]
public ActionResult LogIn()
{
return View();
}
[HttpPost]
public ActionResult LogIn(Models.User user)
{
if (IsValid(user.Email, user.Password))
{
FormsAuthentication.SetAuthCookie(user.Email, false);
return RedirectToAction("Index", "Home");
}
else
{
ModelState.AddModelError("", "Login details are wrong.");
}
return View(user);
}
[HttpGet]
public ActionResult Register()
{
return View();
}
[HttpPost]
public ActionResult Register(Models.User user)
{
try
{
if (ModelState.IsValid)
{
using (AppContext db = new AppContext())
{
var crypto = new SimpleCrypto.PBKDF2();
var encrypPass = crypto.Compute(user.Password);
var newUser = db.Users.Create();
newUser.FirstName = user.FirstName;
newUser.LastName = user.LastName;
newUser.Email = user.Email;
newUser.CompanyName = user.CompanyName;
newUser.Password = encrypPass;
newUser.PasswordSalt = crypto.Salt;
newUser.AdminCode = 0;
user.Password = encrypPass;
user.PasswordSalt = crypto.Salt;
db.Users.Add(newUser);
db.SaveChanges();
return RedirectToAction("Index", "Home");
}
}
else
{
ModelState.AddModelError("", "Data is not correct");
}
}
catch (DbEntityValidationException e)
{
foreach (var validationErrors in e.EntityValidationErrors)
{
foreach (var validationError in validationErrors.ValidationErrors)
{
Trace.TraceInformation(
"Class: {0}, Property: {1}, Error: {2}",
validationErrors.Entry.Entity.GetType().FullName,
validationError.PropertyName,
validationError.ErrorMessage);
}
}
}
return View();
}
private bool IsValid(string email, string password)
{
var crypto = new SimpleCrypto.PBKDF2();
bool IsValid = false;
using (AppContext db = new AppContext())
{
var user = db.Users.FirstOrDefault(u => u.Email == email);
if (user != null)
{
if (user.Password == crypto.Compute(user.PasswordSalt, password))
{
IsValid = true;
}
}
}
return IsValid;
}
public ActionResult LogOut()
{
FormsAuthentication.SignOut();
return RedirectToAction("Index", "Home");
}
}
}
Please check the crypto.Compute function parameters. It requires textToHash(which is your password) and salt. You have to interchange the parameters.
you need to modify your IsValid function like this:
private bool IsValid(string email, string password)
{
var crypto = new SimpleCrypto.PBKDF2();
bool IsValid = false;
using (AppContext db = new AppContext())
{
var user = db.Users.FirstOrDefault(u => u.Email == email);
if (user != null)
{
if (user.Password == crypto.Compute(password, user.PasswordSalt))
{
IsValid = true;
}
}
}
return IsValid;
}