Multiple role based registration in mvc4 c# aspx - c#

I have 5 roles of users.They are Admin,Distributor,Micro-distributor,Dealer and User.Admin has the privilege of accessing all pages of other user and all CRUD operations on it.All these users have different fields from others.If dealer register his details then the values stored into a register table in SQL server database.this is same for all roles.basic details of all users columns are same.but other details like bank details and shop details are extra columns of distributors and dealers.So you can store the registration details to one column or different columns.but user can login to their account based on their roles,that is if a dealer tries to login,then server must check such a dealer exist in the database.If yes then he redirect to his profile page.I need the complete model view and controller source code for this problem in mvc4 or mvc3.you canuse the sql server database for this action...
I use the following code snippet for login action
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Login(UserLogon u)
{
if (ModelState.IsValid)
{
using (TranzEntities2 dc = new TranzEntities2())
{
var v = dc.tbl_User.Where(a => a.user_name.Equals(u.user_name) && a.password.Equals(u.password)).FirstOrDefault();
if (v != null)
{
Session["LogedUserID"] = v.user_id.ToString();
Session["LogedUserFullname"] = v.first_name.ToString();
return RedirectToAction("Home");
}
else
{
ModelState.AddModelError("Error", "Login failed, Try again");
}
}
}
return View(u);
}
But it is for only one table.I need to check the user login based on their roles.Suppose if someone try to login then it automatically check the user belongs to which table.if he belongs to a dealer table then dealer page will redirect after login success.

Related

Get all data from database for Administrator role but not for other roles, using same query

I am currently developing a Web Application with ASP.NET MVC 5 with Visual Studio 2019.
The App is about a school management system.
App has a Control and Management System, which is having same UI for all logged in users with some roles.
Roles are Administrator, Teacher, Accountant
When logged in by any of the user of above Roles, user is presented with a Home Screen Dashboard, where they can view School related and class related brief snapshot data.
An Administrator will be able to see all the data of school and students and teachers on the same dashboard page and all over the web app.
A Teacher will be able to see data related to their class and students only, not the data of Administrator and Accountant Roles.
I thought of using passing a parameter to each LINQ query with some id of logged in user, but what happens is, where in LINQ is beneficial only when Teacher is logged in but Administrator needs all data so I need to modify the query that time.
How to achieve this with same controller, giving full data to Administrator role and giving partial data to Teacher Role?
HomeController
public class HomeController : Controller
{
DBEntities db = new DBEntities();
public ActionResult Index()
{
return View();
}
public ActionResult GetLatestActivity(int id)
{
var data = from n in db.ACTIVITies
where n.USERID == id //This is ok when teacher is logged in but Admin needs all data, so not useful there
orderby n.ID descending
select new ActivityViewModel
{
ID = n.ID,
AREA = n.AREA,
SECTION = n.SECTION,
MESSAGE = n.MESSAGE,
CREATE_TIMESTAMP = (DateTime)n.CREATE_TIMESTAMP
};
return Json(data.Take(6), JsonRequestBehavior.AllowGet);
}
}
I think you can do something like this if you are using Microsoft.AspNet.Identity, because it's not clear to me. Otherwise you can implement your own isAdmin check method.
public ActionResult GetLatestActivity(int id)
{
var isAdmin = User.IsInRole("Administrator");
var data = from n in db.ACTIVITies
where n.USERID == (isAdmin ? n.USERID : id)
orderby n.ID descending
select new ActivityViewModel
{
ID = n.ID,
AREA = n.AREA,
SECTION = n.SECTION,
MESSAGE = n.MESSAGE,
CREATE_TIMESTAMP = (DateTime)n.CREATE_TIMESTAMP
};
return Json(data.Take(6), JsonRequestBehavior.AllowGet);
}

RedirectToAction redirecting to wrong User ID

Edit: I am still encountering this issue but I have solved it displaying the applications on 2 users profile instead of the user that created it. I am still running into the issue of redirecting to the wrong ID however and I can't find any information online about it. All the breakpoints up to the redirect point to the correct ID so I am really perplexed. As stated below, I had altered my viewbag and variables to be consistent and it did not fix the issue.
I have an application that allows users to add applications to their profile. Their profile will list all of the applications made by that user. The application has been configured in the RouteConfig file to initialise the application in the profile of UserId 1.
What is happening is that if I create an application for UserId 1, it works fine, adds the application to the list of applications for UserId 1 and displays it. If I create a new user (UserId 2) and then proceed to add a new application for that user, the redirect action that happens when the application is submitted to the database takes me back to UserId 1's page with the application being added to UserId 1's list and also to the UserId that created it (In this instance, UserId 2). I'm not sure why this is happening as I am explicitly telling it to get the UserId from the ViewBag that is storing the correct UserId.
If I look into the database, there is only 1 record for the application. I can delete the application in UserId 1's list and it will still exist in UserId 2's list and also the database. If I remove it through the UserId 2's page, it will remove the record from all lists and database. This also applies to updating the details of the application.
When I've set a breakpoint at the very end where the controller will pick up the UserId and then redirect me to that UserId's page. It states the correct UserId's page it needs to redirect to (In the scenario above, it states the UserId is 2). However, as already stated, it is redirecting me to the UserId 1.
If I remove the route in the RouteConfig file that initialises the application in UserId 1 and just load up the default index page, create a user then create an application, I am given an error stating System.NullReferenceException because I'm trying to display the name of the user using - <h2>User Profile for #Model.Name</h2> so it's not picking up the details of the UserId. I'm not sure why this is happening either as I thought the RouteConfig file was purely to tell the application where to inialise.
Code below, some points to make:
This is what the URL looks like when I am about to submit the application = https://localhost:44313/Service/AddApplication?Course=Level1&DriverId=1&UserId=2
RoutesConfig is sending to "GetUser", "User", 1 at application start
The viewbags are working as I can see that it picks up the correct UserId at the very end of the adding process.
Controller Action to Add Application;
[HttpPost]
public ActionResult AddNewApplication(ApplicationAdd applicationAdd, string UserId, int DriverId)
{
try
{
// TODO: Add insert logic here
applicationService.AddApplication(applicationAdd, UserId, DriverId);
return RedirectToAction("GetUser", "User", new { UserId = ViewBag.UserId });
}
catch
{
return View();
}
}
GetUser action in User Controller:
public ActionResult GetUser(string id)
{
return View(userService.GetUser(id));
}
GetUser action in userService:
public User GetUser(string id)
{
using (var context = new MyContext())
{
return userDAO.GetUser(id, context);
}
}
GetUser in userDAO:
public User GetUser(string id, MyContext context)
{
context.Users.Include(g => g.Applications).ToList();
return context.Users.Find(id);
}
RouteConfig file path:
defaults: new { controller = "User", action = "GetUser", id = 1 }
Controller Action that is giving the view to display the list of applications for a user:
public ActionResult GetApplications(string id)
{
User user = userService.GetUser(id);
IList<Application> applications = user.Applications.ToList();
return View(applications);
}
Try using this
RedirectToAction("GetUser", "User", new { id = ViewBag.UserId });
the parameter name UserId needs to be the same as the one in the funcation id.

login form not submitting after adding new fields to table .net mvc

I added 1 new field to my table, added the field to Model DTO and Model ViewModel cs, but Login form submit seems to be not working post that.
There is no error showing, login page simply refreshes. Steps I took are as follows
1) New field added manually to the Table
2) Added new field to the Model DTO and Model ViewModel cs
[HttpPost]
public ActionResult Login(UserVM model)
{
if(ModelState.IsValid)
{
using (Db db = new Db())
{
var user = db.User.Where(x => x.Username.Equals(model.Username) && x.Password.Equals(model.Password)).FirstOrDefault();
if(user != null)
{
Session["Id"] = user.Id.ToString();
Session["Username"] = user.Username.ToString();
Session["Password"] = user.Password.ToString();
Session["Firstname"] = user.Firstname.ToString(); //NewField
Session["RoleName"] = user.RoleName.ToString();
return RedirectToAction("UserProfile");
}
else
{
ModelState.AddModelError("", "Username / Password is Invalid");
return View(model);
}
}
}
return View();
}
Ok, I was able fix this by myself. Issue here I noticed was very unique, And i will be glad to explain from start.
I created a table with this info first
Id, Username, Password.
Then created its Action in Controller, and all was set to work.
Later I decided to add new fields to table, say Firstname, Lastname and Email.
Now, here is where the problem came. In Model ViewModel I had created a Model Class as UserVM, So, if I add these new properties to ModelClass with [Required] data annotaion, only then the Login Action does not respond. Action works if I go back and remove [Required] Data annotation.
I did google this to see a solution but no success.
For now Closing this ticket as resolved, but would love to know how can we make the Action run with [Required] data annotation added on the new fields in the Model Class.

Registration Admin Approval verification in C# asp dot net MVC

I need "admin approval" for login as user after the registration. I am doing it in asp.net MVC, using ms sql, visual studio. I am new to it,need help badly, how many way I can do it and whats the process to do that.
My thought: I made login Registration with email verify. Now I need to make admin verify.
Here is my database table :
Database: I made a registration table(Tbl_User), Approval Table(Tbl_Approval). I need to confirm admin approval while login:
var approval = dc.Tbl_Approval.Where(m => m.Tbl_User.EmailID == login.EmailID).FirstOrDefault();
if (!approval.ApprovalStatus)
{
ViewBag.Message = "Please wait for admin approval";
return View();
}
For this I need to insert the Tbl_User data into Tbl_Approval table which is previously empty. so I need the query in the controller action(for Tbl_Approval) to get the (Tbl_User)list into Tbl_Approval table and edit the Approval status. I tried this:-
public ActionResult List()
{
List<Tbl_User> userList = db.Tbl_User.ToList();
Tbl_Approval approval = new Tbl_Approval();
List<Tbl_Approval> approvalUserList = userList.Select(x => new Tbl_Approval { UserID = x.UserID }).ToList();
return View(approvalUserList);
}
Please help me on the controller action to get the(Tbl_User) list into the Tbl_Approval table. Also suggest me any other good way to do this task.
You can create the Action method for approval process. When admin approves any particular user, you need to pass that userId. I have used EntityFramework for the example.
Here is the code that should work
public ActionResult ApproveUser(int userId)
{
var user = context.Users.Find(userId);
if(user != null)
{
user.ApproveStatus = 1;
context.Entry(user).State = System.Data.Entity.EntityState.Modified;
context.SaveChanges();
}
return View();
}
TO solve this issue do the following i.e.
Add the status column in your login table and set the default approval status for all new sign ups as not approved.
Create a module for admin only in your web portal to view/approve the new sign ups.
Create designated actions with view pages in your new module to view and approve the signups.
I recommend creating a new controller for this new module that is accessible to the admin only and not to everyone else.
When the admin login the system show notifications to him so, he can open and go to this new module and perform approval actions.
When the admin performs the approval action update the approval status from not approve to approve.

How to find the data related to a specific user in ASP.NET MVC

I am now learning ASP.NET MVC 5 and working on a little project to improve my knowledge.
Using Entity Framework, I didn't see until now a table for the Users although there is a login and register functionality.
I wonder for example: what shall I do when I want show the data related to a specific user? With a code like that:
public ActionResult MyAnnoncement()
{
if (!User.Identity.IsAuthenticated)
{
return View("~/Views/Account/Login.cshtml");
}
else
{
return View(db.Voitures.ToList());
}
}
You can use User.Identity.GetUserId() to get the ID of the user from the AspNetUsers table, then populate the User object like this:
ApplicationDbContext db = new ApplicationDbContext();
string uid = User.Identity.GetUserId();
ApplicationUser u = db.Users.Find(uid);
Please note you'll need to add "using Microsoft.AspNet.Identity;" at the top of your code to use User.Identity.GetUserId().
You need an instance of the UserManager "ApplicationUser can be different in your case can by some other object
Then you can do something like this
var user = UserManager.FindById(User.Identity.GetUserId());
the user object has your data

Categories

Resources