Edit Account user and role .Net core Identity - asp.net-core

I am using .Net Core Identity 5, I did add Role for the user when registering the account. I want when I Edit the user information of that account, I can change their Role in the system.
I am working in Repo, how can I work with it most effectively?
Viewmodel
public class UserRoleViewModel
{
public string UserId { get; set; }
public string FullName { get; set; }
public string Email { get; set; }
public string Role { get; set; }
}

Related

Extend Asp Net Core Identity Relation

In Asp net core (3.1) Identity i want add a many to many relationship between user and TourOperators.
(The concept is that many user can follow many tour operators).
I have the tour operators class:
public class TourOperator
{
public int Id { get; set; }
public ICollection<Follow> Follows { get; set; }
}
I have extended the UserIdentity class:
public class ApplicationUser: IdentityUser
{
public ICollection<Follow> Follow { get; set; }
}
I have the Follow class:
public class Follow
{
public long Id { get; set; }
public string UserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
public int TourOperatorId { get; set; }
public TourOperator TourOperator{ get; set; }
}
After execute the migration, why in the Follow table i have 4 field instead of 3?
I have the following field:
I think that ApplicationUserId couldn't be present
Entity Framework has no way to link the UserId and ApplicationUser properties. So you either need to follow convention, whereby EF can make an educated guess. The simplest option is to rename your string property:
public string ApplicationUserId { get; set; }
Alternatively, you can configure it, for example using an attribute:
[ForeignKey("ApplicationUser"]
public string UserId { get; set; }
public ApplicationUser ApplicationUser { get; set; }
Or in the OnModelCreating method, for example:
modelBuilder.Entity<Follow>()
.WithOne(f => f.ApplicationUser)
.HasForeignKey("UserId");

Add custom fields for AspNetUser [duplicate]

This question already has answers here:
extend ASP.NET Core Identity user
(2 answers)
Closed 3 years ago.
I am a newbie in ASP.NET Core.
How can I add custom fields to my user model both in code and UI?
Current user management UI is something like this, but I want to add some extra fields, like credit or scores, in model, DB & UI:
And this is my AspNetUser model :
public partial class AspNetUsers
{
public AspNetUsers()
{
AspNetUserClaims = new HashSet<AspNetUserClaims>();
AspNetUserLogins = new HashSet<AspNetUserLogins>();
AspNetUserRoles = new HashSet<AspNetUserRoles>();
AspNetUserTokens = new HashSet<AspNetUserTokens>();
}
public string Id { get; set; }
public string UserName { get; set; }
public string NormalizedUserName { get; set; }
public string Email { get; set; }
public string NormalizedEmail { get; set; }
public bool EmailConfirmed { get; set; }
public string PasswordHash { get; set; }
public string SecurityStamp { get; set; }
public string ConcurrencyStamp { get; set; }
public string PhoneNumber { get; set; }
public bool PhoneNumberConfirmed { get; set; }
public bool TwoFactorEnabled { get; set; }
public DateTimeOffset? LockoutEnd { get; set; }
public bool LockoutEnabled { get; set; }
public int AccessFailedCount { get; set; }
public double Credit { get; set; }
public virtual ICollection<AspNetUserClaims> AspNetUserClaims { get; set; }
public virtual ICollection<AspNetUserLogins> AspNetUserLogins { get; set; }
public virtual ICollection<AspNetUserRoles> AspNetUserRoles { get; set; }
public virtual ICollection<AspNetUserTokens> AspNetUserTokens { get; set; }
}
Custom user data is supported by inheriting from IdentityUser. It's customary to name this type ApplicationUser:
public class ApplicationUser : IdentityUser
{
public string CustomTag { get; set; }
}
The detail steps to customize could be found in Customize the model document .
In ASP.NET Core 2.1 or later, Identity is provided as a Razor Class Library. For more information, see Scaffold Identity in ASP.NET Core projects .
After scaffolding , you can find the profile page in Areas.Identity.Pages.Account.Manage.Index.cshtml , you can add entities in InputModel of Index.cshtml.cs and customize the data in OnGetAsync and OnPostAsync function .

How to Extend Roles for Multiple Locations / Sites with Asp.Net Core Identity

I have an API that is used in a multi-site/multi-location environment. At the moment, each user has roles defined but is locked to only one location. I am needing to extend this out to where a user may have admin roles for one location and then may be standard user at another location. They may also have no roles/no access to a bunch of locations.
Here is what I am working with right now (asp.net core 2.2):
public class ApplicationUser : IdentityUser
{
public string FirstName { get; set; }
public string LastName { get; set; }
public int? LocationId { get; set; }
public virtual Locations Locations { get; set; }
public int? ContactPersonId { get; set; }
public virtual ContactPerson ContactPerson { get; set; }
}
public class Locations
{
public int Id { get; set; }
public string Name { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
}
public class ContactPerson
{
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string UserId { get; set; }
public virtual ApplicationUser ApplicationUser { get; set; }
public virtual ICollection<ContactOrganizationPerson> ContactOrganizationPeople { get; set; }
public virtual ICollection<ContactAddress> ContactAddresses { get; set; }
public virtual ICollection<ContactPhone> ContactPhones { get; set; }
public virtual ICollection<ContactEmail> ContactEmails { get; set; }
}
I am planning on changing the ApplicationUser to Locations table relationship to a Many to Many which would link the User to the Locations they are allowed to access. I have though about placing a payload in the M2M relationship table that would specify UserId, LocationId and Roles, but I would rather let Identity handle it if possible.
Is there a way to extend AspNetUserRoles so that I can specify a User to Role relationship for each location? Or is there a better way to accomplish this?
I'm not sure if this is going to help you, but I have extended .Net Core with functionality with IAuthorizationRequirement.
public class CustomRequirement : IAuthorizationRequirement
{
public CustomRequirement ()
{
}
}
Create a new class
public class CustomHandler : AuthorizationHandler<CustomRequirement>
Override HandleRequirementAsync
protected override Task HandleRequirementAsync(AuthorizationHandlerContext context, CustomRequirement requirement)
Here you can extract info about user from DB, compare, etc. If user is not allowed, return
return Task.CompletedTask;
If user is allowed, then use
context.Succeed(requirement);
Before returning. Then in your startup.cs:
services
.AddAuthorization(options =>
{
options.AddPolicy("CustomPolicy", policy =>
policy.Requirements.Add(new CustomRequirement()));
})
And then in your controllers you can add attribute
[Authorize(Policy = "CustomPolicy", Roles = "Admin")]
If requirement is not meet, user will get 401 unauthorized, which might not be what you want.

MVC4 model custom function

Sorry for newbie questions, i'm brand new to MVC and OOP
I have the following model for my USER db table
namespace MyApp.Models
{
public class User
{
public int user_id { get; set; }
public string username { get; set; }
public string password { get; set; }
public string salt { get; set; }
public string email { get; set; }
public sbyte status { get; set; }
public System.DateTime creation_date { get; set; }
public sbyte type { get; set; }
public virtual Doctor Doctor { get; set; }
public virtual Owner Owner { get; set; }
public virtual UserToken UserToken { get; set; }
public virtual Veterinarian Veterinarian { get; set; }
}
}
Actually in order to recall a particular USER based on the mail or the id i use a specific class called CustomDbFunctions
namespace MyApp.Models.DAL
{
public static class CustomDbFunctions
{
public static User GetUserEntityFromEmail(string email, DbContext db)
{
return db.Users.FirstOrDefault(u => u.email == (string)email);
}
}
}
in that way i use in my code
User user = CustomDbFunctions.GetUserEntityFromEmail(email, db)
and this it 100% OK with me, but i don't know if this kind of approach is correct or not, or if there's a better way like
//select the single user by calling only the class USER
User mySelectedUser = new User(email)
Thank you very much.
Well for understanding how to access your data in your MVC4 application you could read this tutorial from the Asp.Net MVC main page. Read the whole tutorial about MVC4 and you'll get a solid idea on how to work with it.
But I also recommend this tutorial on a good Entityframework design pattern, it's called Repository Pattern, I just a nice way to get all your code ordered (like all other patterns). Let me know.

How to get the email of the current user in Silverlight 4 Business Application?

I am using a custom MembershipProvider (using EF, rather than Sql) with a SL4 business application.
The default implementation of the MembershipUser class has an e-mail address property, however the User object defined by the SL4 Business Application template (inheriting from UserBase )does not give you access to the Email property.
Moreover when the AuthenticationService (inheriting from AuthenticationBase<User>) does not even attempt to read the user's e-mail.
Is there a way to access the Email property of the MembershipUser(server side)/User(client side) by using the AuthenticationService, or do I have to create my own routines to return the right properties of the user?
Thanks,
Martin
You can create your own User class as long as you implement IUser.
public class User : IUser
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Email { get; set; }
#region Implementation of IUser
public string Name { get; set; }
public IEnumerable<string> Roles { get; set; }
#endregion
}
You can modify the AuthenticationService to Implement IAuthentication<User> and implement Login. As part of your implemented Login process you can populate the User.Email.
public class AuthenticationService : DomainService, IAuthentication<User>
{
public User Login(string userName, string password, bool isPersistent, string customData)
{
//can populate User.Email on successful login.
}
}