Assign permission for pages using Code first in asp.net MVC - sql

Here I have created a Model Structure in asp.net mvc:
public class UserModel
{
public int UserId { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public List<Permission> Permissions { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
}
public class Permission
{
public int PermissionID { get; set; }
public bool IsPermit { get; set; }
public string Name { get; set; }
}
and setting some default values in the list and while I am adding the user in the list I assign the permission for pages to that user through the UI (by checking permission checkboxes), so that user can access only the assigned pages:
public static class Repository
{
public static List<UserModel> GetUsers()
{
List<UserModel> listUsers = new List<UserModel>
{
new UserModel
{
UserId = 1,
UserName = "abc",
Password = "abc",
Permissions = new List<Permission>
{
new Permission
{
PermissionID = 1,
IsPermit = true,
Name = "Page1"
},
new Permission
{
PermissionID = 2,
IsPermit = false,
Name = "Page2"
},
new Permission
{
PermissionID = 3,
IsPermit = false,
Name = "Page3"
},
new Permission
{
PermissionID = 4,
IsPermit = false,
Name = "Page4"
}
},
FirstName = "Rohit",
LastName = "Sharma"
},
new UserModel
{
UserId = 2,
UserName = "xyz",
Password = "xyz",
Permissions = new List<Permission>
{
new Permission
{
PermissionID = 1,
IsPermit = false,
Name = "Page1"
},
new Permission
{
PermissionID = 2,
IsPermit = true,
Name = "Page2"
},
new Permission
{
PermissionID = 3,
IsPermit = true,
Name = "Page3"
},
new Permission
{
PermissionID = 4,
IsPermit = true,
Name = "Page4"
}
},
FirstName = "Rahul",
LastName = "Sharma"
}
};
return listUsers;
}
}
Now I want to do the same by using code first approach of database with the help of DbContext class. I have a static list of page permission in a database table (Id =1, Name=Page1; Id =2, Name=Page2; Id =3, Name=Page3; Id =4, Name=Page4).
I am confused while creating model structure for database. Please guide me how to create model structure and mapping of structure with the tables.
I have a table (Permission) in my database with default rows.
ID Name
1 Page1
2 Page2
3 Page3
4 Page4
Now, when I adding user I assigning permission to that user through static checkboxes (Page1, Page2, Page3 and Page4). That’s why I created static table in a database that contains list of pages. My User table is initially blank.
User
Id int NotNull
UserName nvarchar(100) AllowNull
Password nvarchar(100) AllowNull
FirstName nvarchar(100) AllowNull
LastName nvarchar(100) AllowNull

You can use below mentioned structure when you're using code first.You have to maintain conventions when you're using code first (But can be changed when you're using Fluent API).
Model Classes
public class User
{
public int Id { get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public virtual ICollection<Permission> Permissions { get; set; }
}
public class Permission
{
public int Id { get; set; }
public bool IsPermit { get; set; }
public string Name { get; set; }
public virtual User { get; set; }
}
Tables (This will auto generate.But If you want you can create manually also)
Users
Id int NotNull
UserName nvarchar(100) AllowNull
Password nvarchar(100) AllowNull
FirstName nvarchar(100) AllowNull
LastName nvarchar(100) AllowNull
Permissions
Id int NotNull
IsPermit bit AllowNull
Name nvarchar(100) AllowNull
User_Id int NotNull
DbContext Derived Class
public class UserEntities : DbContext
{
public DbSet<User> Users { get; set; }
public DbSet<Permission> Permissions { get; set; }
}
Fore more information check Code-First Development with Entity Framework
I hope this will help to you.

Related

Unique constraint not respected when inserting into SQL table with .NET Core framework

I try to make a register functionality for a REST API in .NET Core 5.
When I create a new user the unique index is not respected and it lets me insert a new user with the same email.
Also, if let's say this constraint would work, what should I get as a result if the insert fails?
[Table("users")]
[Index(nameof(Email), IsUnique = true)]
public class UserDAO
{
[DatabaseGenerated(DatabaseGeneratedOption.Identity)]
public int Id { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime DateOfBirth { get; set; }
public string Email { get; set; }
public string Password { get; set; }
}
DbContext:
public class DatabaseContext : DbContext
{
public DatabaseContext(DbContextOptions<DatabaseContext> options) : base(options)
{
}
public DbSet<UserDAO> Users { get; set; }
}
And the code from the Provider that inserts the user(it should return -1 if the insert fails):
public int createUser(string firstName, string lastName, DateTime dateOfBirth, string email, string password)
{
UserDAO user = new UserDAO
{
FirstName = firstName,
LastName = lastName,
DateOfBirth = dateOfBirth,
Email = email,
Password = password
};
_dbContext.Users.Add(user);
_dbContext.SaveChanges();
return user.Id;
}

Custom Field bool type some time insert false in ApplicationUser

I have add few custom field in ApplicationUser Class and adding in Aspnetusers.
some time one field "IsActive" it's insert properly as hardcoded true by default but for few user insert false.
Class is
public class ApplicationUser : IdentityUser
{
public virtual string CountryCode { get; set; }
public virtual string UsedReferralCode { get; set; }
public virtual DateTime? LastLoginTime { get; set; }
public virtual DateTime? RegistrationDate { get; set; }
public virtual string UserType { get; set; }
public virtual bool? IsActive { get; set; } = true;
[DatabaseGenerated(DatabaseGeneratedOption.Computed)]
public int UniqueId { get; set; }
public virtual string FaceBookId { get; set; }
public virtual string AppleId { get; set; }
}
Register user Code
var user = new ApplicationUser
{
UserName = model.Email,
Email = model.Email,
PhoneNumber = model.Mobile,
CountryCode = model.CountryCode,
UsedReferralCode = model.ReferralCode,
RegistrationDate = DateTime.Now,
LastLoginTime = DateTime.Now,
UserType = "Register",
IsActive = true
};
var result = await _userManager.CreateAsync(user, model.Password).ConfigureAwait(false);
I didn't understand why its insert false for few users.
suggest some idea.
Thanks

How to log in my custom user table in MVC 4?

I want to use my custom User table in MVC 4 code first application. I defined advance User table in my database context:
public class MyDatabase : DbContext
{
public DbSet<User> UserSet { get; set; }
public DbSet<News> NewsSet { get; set; }
...
}
Model is like:
public class User
{
[Key]
public int Id{ get; set; }
public string UserName { get; set; }
public string Password { get; set; }
public string Name { get; set; }
public string SurName { get; set; }
...
}
When application start, it calls this:
WebSecurity.InitializeDatabaseConnection("MyDatabase", "Users", "Id", "UserName", autoCreateTables: true);
In controller I use Add(entity) to save user entity. After saving I want to log in user. But it does not work:
[HttpPost]
public ActionResult Register(User user)
{
var result = MyService.SaveUser(user);
WebSecurity.Login(result.UserName, result.Password, true);
return RedirectToAction("Index", "Profile", new { id = result.Id });
}
After saving user, it's data stored in my database, but it can not log in. How should I do?
Edit:
Is it right to save User entity with my business method? Or I must do it only with
WebSecurity.CreateUserAndAccount()?
If I can use my own save method, how to save password in database?
You could just use forms authentication directly.
[HttpPost]
public ActionResult Register(User user)
{
var result = MyService.SaveUser(user);
SignIn(result.Id, "");
return RedirectToAction("Index", "Profile", new { id = result.Id });
}
public void SignIn(string accountId, string roles)
{
var authTicket = new FormsAuthenticationTicket(
1,
accountId,
DateTime.Now,
DateTime.Now.AddMinutes(20),
false,
roles
);
string encryptedTicket = FormsAuthentication.Encrypt(authTicket);
var authCookie = new HttpCookie(FormsAuthentication.FormsCookieName, encryptedTicket);
HttpContext.Current.Response.Cookies.Add(authCookie);
}
Here is a user class that will help you with password issue. It relies on BCrypt
public class UserAccount
{
public string Id { get; set; }
public string Username { get; set; }
public string Email { get; set; }
public string Password
{
get { return PasswordHash; }
set { PasswordHash = HashPassword(value); }
}
public string PasswordHash { get; private set; }
public List<string> Roles { get; set; }
public string AuthenticationRoles
{
get { return Roles == null ? "" : String.Join(",", Roles.Select(x => x.ToString())); }
}
public bool IsActive { get; set; }
public string Name { get; set; }
public bool PasswordIsValid(string password)
{
bool matches = BCrypt.Net.BCrypt.Verify(password, Password);
return matches;
}
private string HashPassword(string value)
{
return BCrypt.Net.BCrypt.HashPassword(value);
}
}

Entity Framework Creates New Record in Table I Didn't Reference when Inserting Into Other Table

In this website, users can register under a username and password, and can also post comments on articles. The models are pretty straightforward:
public class User
{
public int Id { get; set; }
public string Username { get; set; }
public string Password { get; set; }
public bool IsAdmin { get; set; }
public DateTime JoinDate { get; set; }
public string AvatarPath { get; set; }
public string EmailAddress { get; set; }
}
public class ArticleComment
{
public int Id { get; set; }
public int ArticleId { get; set; }
public int UserId { get; set; }
public string CommenterName { get; set; }
public string Message { get; set; }
public DateTime CommentDate { get; set; }
public User User { get; set; }
}
Entity Framework correctly made the foreign key relationship between UserId on ArticleComment and Id on User when the database was created using code-first.
Here's my code for when a user posts a new comment:
public JsonResult SubmitComment(int articleId, string comment)
{
var response = new JsonResponse();
var currentUser = _userRepository.GetUserByUsername(User.Identity.Name);
//...
var newComment = new ArticleComment
{
ArticleId = articleId,
CommentDate = DateTime.Now,
CommenterName = currentUser.Username,
UserId = currentUser.Id,
User = currentUser,
Message = comment,
};
try
{
_articleRepository.Insert(newComment);
}
catch (Exception e)
{
response.Success = false;
response.AddError("newComment", "Sorry, we could not add your comment. Server error: " + e.Message);
return Json(response);
}
response.Success = true;
response.Value = newComment;
return Json(response);
}
The values that make up the newComment object all appear to be correct, and the Insert method in my Article repository class is straight and to the point:
public void Insert(ArticleComment input)
{
DataContext.ArticleComments.Add(input);
DataContext.SaveChanges();
}
But once this happens, poof: a new record in my Users table appears along with the new record in ArticleComments. All of the info in the new Users record is duplicated from that user's existing record - the only difference is the value for the primary key Id. What gives?
In addition to my comment, you need to make sure that both _userRepository and _articleRepository are using the same DbContext instance.
Either that, or you can try this:
var newComment = new ArticleComment
{
ArticleId = articleId,
CommentDate = DateTime.Now,
CommenterName = currentUser.Username,
UserId = currentUser.Id,
// User = currentUser, let the UserId figure out the User, don't set it yourself.
Message = comment,
};

Criteria question with NHibernate

I'm trying to use NHibernate for data access, and I have 2 simple entities that look like this:
public class User : IEntity
{
public int ID { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public string Email { get; set; }
public string Logon { get; set; }
public string Password { get; set; }
public ICollection<Role> Roles { get; set; }
public bool IsNew
{
get { return (ID == 0) ? true : false; }
}
public User()
{
Roles = new List<Role>();
}
}
public class Role : IEntity
{
public int ID { get; set; }
public string RoleName { get; set; }
public string RoleDescription { get; set; }
public bool IsNew
{
get { return (ID == 0) ? true : false; }
}
}
My question......how do I construct a Criteria if I want to find any user that contains a Role with an ID of 1 in it's Roles collection?
Never mind, this ended up being relatively straight forward to do:
// role was the role passed in to my Find method.
var criteria = DetachedCriteria.For(typeof (User))
.CreateCriteria("Roles")
.Add(Restrictions.Eq("ID", role.ID));