I am beginner and developing a silverlight navigation application using RIA services with SQL Server 2008.
I have a 'Registration' table where initially users request for membership are stored. The admins will verify them and later the particular user details are moved to 'Members' table from 'Registration'. Moreover when the term/period of membership comes to end the same details are finally moved to 'PastMembers' table from 'Members' table.
Now what I wanted is that before the registration details are submitted it should be checked in all three tables(Registration,Members,PastMembers) for username specified and if any record is found it should restrict user by submitting details to avoid duplicate userids.
I searched and tried to count the rows but even though I have a record with same userid I get count=0
Please let me know if any other better option or any rectification in this logic (please be a more brief since I am a beginner)
Checking in just first table
Code in submit button click handler
myDomainContext objctx1 = new myDomainContext();
var query1 = objctx1.GetregistrationsByIDQuery(userid_txtbx.Text);
objctx1.Load(query1);
var count = (from c in objctx1.registrations where c.userid == userid_txtbx.Text select c).Count();
// To see how many rows there
MessageBox.Show(count.ToString());
// Code for restricting details to be submitted
...............................
.....................
...............................
Function in myDomainService.cs
// Query to get usernames from registrations table
public IQueryable<registration> GetregistrationsByID(string id)
{
return this.ObjectContext.registrations.Where(s => s.userid == id);
}
consider sample fields in tables as:
Tables: Registration,Members,PastMembers having common columns as
userid,
fullname,
contact
Related
I am attempting to build a web app that allows users to view company policies, procedures, newsletters, and their own employee information.
I have my staff table that contains all the employee information (along with related lookup tables for things like prefix, staff grade, etc)
my app uses asp-identity for the login functionality, but I want to be able to return information from the staff table that is only relevant to that particular user.
I know it is possible to extend the ASP.net users table to include custom fields, but this doesn't really suit my goal as the staff table is used in a desktop based app by the admin team.
Add a field to your Staff table UserId for example ALTER TABLE Staff ADD UserId NVARCHAR(256) DEFAULT NULL;
Optionally, you would reference the AspnetUsers table.
Update Staff table rows in other to set UserId values to related users ids (manually or create an action to do that)
Then, In your the controller, you can select newsletter from table where employee's user id equal connected User.Identity.Id. for example
var news = context.Newsletters.Where(n=>n.Staff.UserId==User.Identity.Id);
var infos = context.StaffInfos.Where(si=>si.Staff.UserId==User.Identity.Id);
in case the tables are not in relationship, you'll need to do like following
var employee = context.Staffs.FirstOrDefault(s => s.UserId == User.Identity.Id);
if(employee != null) {
var infos = context.StaffInfos.Where(si=>si.IdEmployee==employee.EmployeeId);
return View(infos);
} else {
return Content("You don't have an account associated to your staff info...");
}
Please replace fields in these queries with the names of your fields.
In asp.net mvc when creating, updating, deleting data how does one know that the data beeing manipulated does really belong to the user making the call?
[Authorize]
[HttpPost]
public ActionResult Edit(Model model)
{
// edit data in database
}
If a user is only to manipulate his own data but can see and easily find out information of other users witch is public to manipulate.
How can i be sure that the user is really who he says when for example Edit is called?
The Authorize only makes sure that a user has logged in.
I'm thinking about using controller.User.Identity.Name in the update to make sure the user how created the data is the one that changes it.
But then comes the question could it be possible for a user to go around this by manipulating controller.User.Identity.Name ?
How can one know that a user is who he says he is with regard to this?
There are two kinds of authorization.
One, which is very "vertical", has helpers provided by the framework (such as the Authorize attribute). This "vertical authorization" determines if a user is allowed to make a request or perform an action. It knows nothing of the data of the request or the action being performed, just the request/action itself.
The second, which is more "horizontal", doesn't have built-in helpers in the framework because it's subjective based on the business logic of your application. This one is up to you. This "horizontal authorization" determines if a user is permitted to manipulate specific data elements (specific records in the data) under specific conditions.
To put it simply... If a user submits a request to your application (invoking an edit action on a record for example) then while the framework can tell you if that user is permitted to invoke that action you need to manually determine if that user is permitted to edit that specific data.
For example, let's say two users create records in a table. In that table there should be a column indicating the user which created that record. (Username, some identifier, however you want to link it to a user.) This value isn't provided by the user when inserting the data, it's provided by your code when you build the record. You'd probably pull this value from the logged-in identity of the user (however you track username/id in the application).
Later, when a user attempts to edit a record in that table, you would need to validate that the user performing the action (again, based on their logged-in identity) is the user who originally wrote that record (based on the data that's in the table). Or an admin, or in some other way authorized to manage that data based on your business logic. None of this is based on values being sent from the client, it's all entirely server-side.
So while the client-side code may store an identifier for the record being edited, that value can be changed by any savvy user. That value isn't to be trusted. If a user requests a page, edits values, and submits that page then your server-side code would use the page-provided identifier to know which record the user is attempting to edit, but would use the logged-in user identity to determine if the user is allowed to edit that record. In the event that the user has manipulated the form values to edit somebody else's record, the server-side code should just respond with an error or friendly message denying that action.
This is a loaded question. You could do this with roles (if only Admins can edit). You can do this via user IDs (if you only want them to edit their own personal data).
It seems your question on more based on personal user data so lets go that route.
[Authorize]
[HttpPost]
public ActionResult Edit(Model model)
{
var userId = WebSecurity.CurrentUserId;
var previousRecdord = //Logic or service call to get previous record
if (previousRecord.AUthorId != userId)
{
//Do Something
}
else
{
//Edit something
}
}
You could even throw all of this into a service method and have a validate method that is called before the actions on the service are run. something like
[Authorize]
[HttpPost]
public ActionResult Edit(Model model)
{
var userId = WebSecurity.CurrentUserId;
var profileEntity = //some mapper that maps profile to entity
_UserService.EditUserProfile(userId, profileEntity)
}
and then in some service method:
public void EditUserProfile(int userId, profileEntity profile)
{
validateProfile(userId, profile);
saveProfile(profile);
}
private void validateProfile(int userId, profileEntity profile)
{
var previousRecdord = //Logic or service call to get previous record
if (previousRecord.AUthorId != userId)
{
//throw exp of some sort
}
}
In my program I have two tables/models: Users and Groups in a many-to-many relationship.
When someone is logged in, I want to expose certain links that only Users in that specific Group can access.
Now in my view if I do:
#using (var dbContext = new DatabaseContext())
{
var user = dbContext.Users.First(p => p.Id == SecurityContext.CurrentUser.Id);
if (user.Groups.Count() < 1)
Debug.WriteLine("Less than 1");
}
And the list is always empty.
Is this something that view models are meant for? I need to somehow access both tables to find if a certain user is in a certain group.
You have to load related entities
var user = dbContext.Users.Include("Groups").First(p => p.Id == SecurityContext.CurrentUser.Id);
Read more about loading related entities on MSDN
In my .NET CRUD web application I implemented MembershipProvider class.
Now I have function that lists records from database (this controller requires authenticated user). I need to filter out these records with respect to this logged-in user.
//
// GET: /Library/
public ViewResult Index(String orderBy = "")
{
var books = db.Books.Include(b => b.Category).Include(b => b.Writer).Include(b => b.User);
return View(books.ToList());
}
I need to know how to get logged in user's UserId and use it in Where condition (every tutorial I found talks about getting username but I need UserId). Thank you in advance.
Data I store in *.mdf data file.
I think that what you need is:
Membership.GetUser().ProviderUserKey
The type of this is object, but if you are using the out of the box membership, it should be a guid. This can then be used to filter your select accordingly.
Membership is part of the built in Membership Provider with a number of static methods.
Without knowing your DB structure/ORM, I can't exactly say, but it will be something like:
Guid userId = (Guid)Membership.GetUser().ProviderUserKey;
var books = db.Books.Where(b => b.UserId == userId);
At the table level I'm setting aspnet_User.UserID as foreign key of UserID in the other tables (like Posts.UserID, so each post has an owner). Is that the way to go?
When I create the LINQ to SQL model, should I include the aspnet_User table?
When I create a post (record in the Posts table, a Post object), how do I set the relationship to the logged in user (User object in the controller)?
I don't include the aspnet_User table to my linq-to-sql as I don't really need it. I use the built in way of accessing membership data.
But for your table Posts, it might be easier for you to include it so that you can easily display the User's Name by doing myPost.User.Name
edit:
MembershipUser user = Membership.GetUser();
Guid userGuid = (Guid)user.ProviderUserKey;
Post post = new Post
{
UserId =userGuid,
Message = message
};
In your database schema, you should definately have a the UserID in the Post table be a foreign key to the aspnet_user table, on the UserID field. This way, you are making sure your data is clean. I would even add a cascade delete & update on that relationship.
Then, refer to my instructions in a previous question you asked, about how to get the user data.
(Thomas Stock summed it up briefly, above, though :) )