Reputation: 193
I am doing Authentication depending on the username.So an unauthorized person can't see any methods which is working fine.
The problem is all of the users are able to each others data. Person A shouldn't see the records of person B so that he/she can't edit another person's records.Does anyone know how I can write a lambda expression for that? I have my Edit method pasted below:
// GET: /IcerikDB_/Edit/5
[Authorize(Roles = "Administrator")]
public ActionResult Edit(int id)
{
icerik icerik = db.icerik.Find(id);
ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);
ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);
return View(icerik);
}
[HttpPost]
public ActionResult Edit(icerik icerik)
{
if (ModelState.IsValid)
{
if (User != null && User.Identity != null && User.Identity.IsAuthenticated)
{
string userName = User.Identity.Name;
var user = db.Users.First(u => u.UserName == userName);
icerik.Userid = user.UserId;
db.Entry(icerik).State = EntityState.Modified;
db.SaveChanges();
return RedirectToAction("Index");
}
}
ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);
ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);
return View(icerik);
}
Here is the code for icerik.cs
namespace KategoriEditor.Icerik_DB
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public partial class icerik
{
public int Id { get; set; }
public Nullable<int> Kategorid { get; set; }
public Nullable<System.Guid> Userid { get; set; }
[DataType(DataType.Date)]
public Nullable<System.DateTime> Baslangic { get; set; }
[DataType(DataType.Date)]
public Nullable<System.DateTime> Bitis { get; set; }
public string tamicerik { get; set; }
public string kisaicerik { get; set; }
public string resimlink { get; set; }
public virtual Kategoriler Kategoriler { get; set; }
public virtual Users Users { get; set; }
}
}
Upvotes: 1
Views: 104
Reputation: 46531
Try this:
public ActionResult Edit(int id)
{
// Get the currently logged in user.
string userName = User.Identity.Name;
var user = db.Users.First(u => u.UserName == userName);
// Determine whether the requested id is the same id as the currently logged in user.
icerik icerik = db.icerik.Find(id);
if (icerik.Userid.HasValue && icerik.Userid.Value == user.UserId)
{
ViewBag.Kategorid = new SelectList(db.Kategoriler, "Id", "Adi", icerik.Kategorid);
// You should not need this SelectList anymore.
//ViewBag.Userid = new SelectList(db.Users, "UserId", "UserName", icerik.Userid);
return View(icerik);
}
// This redirect the unauthorized user to the homepage. This can be any other page of course.
return RedirectToAction("Index", "Home");
}
Upvotes: 1