c# - Auto-populate CreatedByUserId in MVC5 models -
i have asp.net mvc5 crud application using windows authentication , site secured active directory group, members in group have same permissions. using entity framework 6 access database.
i have basic user
model @ present login
domain\username
. models reference model via createdbyuserid
property, i've omitted relationships other models below.
public class user { [databasegenerated(databasegeneratedoption.identity)] public int id { get; set; } [index(isunique = true)] [maxlength(100)] public string login { get; set; } [databasegenerated(databasegeneratedoption.computed)] public datetime createddatetime { get; set; } }
i want able achieve 2 things though not sure how without repeating code in controllers:
- users authenticated via active directory group have user model created , stored in database, if doesn't exist.
- when new items created
createdbyuserid
populatedid
ofuser
performing action.
i believe first part achieved via global authorizeattribute
filter create new user
if didn't exist , retreive id
when do, should stored future reference.
the second part not sure on, believe possible without having keep querying database based on current user. value set via constructor using id
retrieved when user
accesses site?
the custom authorize attribute sounds idea. can verify user authenticated , check member of authorized group. suggest don't need store id separately. identity available throughout application via
httpcontext.current.request.requestcontext.httpcontext.user.identity.name
in dbcontext
can override savechanges()
, access user's identity.
here link started overriding savechanges , setting modifieddate, how set modifiedby?
in authorize attribute this:
protected override void onauthorization(authorizationcontext filtercontext) { // user id (create if not exists) using // filtercontext.httpcontext.user.identity.name // set generic principal using id iprincipal principal = new genericprincipal( new genericidentity("myuserid"), new string[] { "myrole" }); httpcontext.current.user = principal; }
then user id accessible anywhere old domain\username
value was.
an point bear in mind when authenticating via active directory users can , change usernames example when getting married or divorced. ad has unique id (a guid) can used reference, can change - when user's profile gets deleted , recreated. if maintaining own user records should maintain ad id , logic should go like:
query user table username
query ad by username (returns ad id guid)
my user exists -> update ad id if changed. return user.
my user not exist -> query user table ad id
my user exists -> update user username. return user.
my user not exist -> create new user (username, ad id). return user.
Comments
Post a Comment