0

I am trying to learn to use Authentication & Identity Security in MVC and Entity Framework and having some difficulty.

I am working on a University Web App and the issue I am having is connecting the new Users who will be registering in the App as different roles like Students or Instructor. I have created 3 roles already in my Seed method, Admin, Student, and Instructor.

How can I write the Register method in the AccountController to connect the Student table and the ApplicationUser table?

Or like when a Student logs in, he is only able to see his account, not the list of students in the Students page?

I created a Foreign Key with the ApplicationUser table and the Person table (Student and Instructor tables inherit from Person table).

public abstract class Person
    {
    public int ID {get; set;}
    [ForeignKey("ApplicationUser")]
    public string ApplicationUserId { get; set; }
    public virtual ApplicationUser ApplicationUser { get; set; }

AccountController.cs

public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new ApplicationUser { UserName = model.UserName, Email = model.Email };
                var result = await UserManager.CreateAsync(user, model.Password);

                if (result.Succeeded)
                {
                    await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);

                    //Assign Role to User
                    await this.UserManager.AddToRoleAsync(user.Id, model.UserRoles);
                    return RedirectToAction("Index", "Home");
                }
                ViewBag.Name = new SelectList(context.Roles.Where(u => !u.Name.Contains("Admin"))
                    .ToList(), "Name", "Name");

                AddErrors(result);
            }

      // Register Student

RegisterViewModel

public class RegisterViewModel
    {
        [Required]
        [Display(Name = "UserRoles")]
        public string UserRoles { get; set; }

        [Required]
        [Display(Name = "First Name")]
        public string FirstName { get; set; }

        [Required]
        [Display(Name = "Last Name")]
        public string LastName { get; set; }

        [Required]
        [EmailAddress]
        [Display(Name = "Email")]
        public string Email { get; set; }

        //[Required]
        [Display(Name = "Username")]
        public string UserName { get; set; }

        [Required]
        [StringLength(100, ErrorMessage = "The {0} must be at least {2} characters long.", MinimumLength = 6)]
        [DataType(DataType.Password)]
        [Display(Name = "Password")]
        public string Password { get; set; }

        [DataType(DataType.Password)]
        [Display(Name = "Confirm password")]
        [Compare("Password", ErrorMessage = "The password and confirmation password do not match.")]
        public string ConfirmPassword { get; set; }
    }

Currently, a student user can see everyone, but I want the student to see only his account information. Note everyone's info.

Students Page

Configuration.cs (Seed method)

protected override void Seed(SchoolContext context)
        {
            var students = new List<Student>
            {
                new Student { FirstMidName = "Carson",   LastName = "Alexander",
                    EnrollmentDate = DateTime.Parse("2010-09-01") },
                new Student { FirstMidName = "Meredith", LastName = "Alonso",
                    EnrollmentDate = DateTime.Parse("2012-09-01") },
                new Student { FirstMidName = "Arturo",   LastName = "Anand",
                    EnrollmentDate = DateTime.Parse("2013-09-01") },
                new Student { FirstMidName = "Gytis",    LastName = "Barzdukas",
                    EnrollmentDate = DateTime.Parse("2012-09-01") },
                new Student { FirstMidName = "Yan",      LastName = "Li",
                    EnrollmentDate = DateTime.Parse("2012-09-01") },
                new Student { FirstMidName = "Peggy",    LastName = "Justice",
                    EnrollmentDate = DateTime.Parse("2011-09-01") },
                new Student { FirstMidName = "Laura",    LastName = "Norman",
                    EnrollmentDate = DateTime.Parse("2013-09-01") },
                new Student { FirstMidName = "Nino",     LastName = "Olivetto",
                    EnrollmentDate = DateTime.Parse("2005-09-01") }
            };


            students.ForEach(s => context.Students.AddOrUpdate(p => p.LastName, s));
            context.SaveChanges();

            //Adding users
            //if (!context.Users.Any(u => u.UserName == "Car"))
            //{
            //    var store = new UserStore<ApplicationUser>(context);
            //    var manager = new UserManager<ApplicationUser>(store);
            //    var user = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" };

            //    manager.Create(user, "password123");
            //}

I have googled a lot, but was not able to come up with a customized register method to work with different tables. Any assistance will be much helpful.

6
  • But you are logged in as an admin...that's the expected result, right?
    – Hackerman
    Feb 23, 2017 at 15:34
  • As an Admin, yeah, it is fine.But when I log in as a Student user, he is also able to do the same and I don't want that.
    – Truecolor
    Feb 23, 2017 at 15:39
  • Can you log in as Alonso and change the picture in your question?
    – Hackerman
    Feb 23, 2017 at 15:43
  • the problem in the data that is returned to the view. in the controller filter the results by the user id and if the user is in the role "Admin" don't apply the filter....
    – BillRuhl
    Feb 23, 2017 at 15:47
  • @Hackerman I can create a Alonso User who has a role of a Student, but that is not the same Alonso as the one in Student list. That is one of my main concern. I don't know how to have the same person in both the ApplicationUser table and the Student table. I have added my Seed() method in my original post.
    – Truecolor
    Feb 23, 2017 at 15:48

1 Answer 1

2

You can alter your SQL hit based on user role.

      var whereClause = "";
      if (User.Roll = "Student")
      {
            whereClause = "WHERE USER_NAME = '" + User.Name + "'";
      }
            sqlQuery = "SELECT .... " + whereClause;

If the user is not an Admin, only their record will be returned.

10
  • 1
    But dont do it like that ;) use parameterised queries... technet.microsoft.com/en-us/library/ms175852(v=sql.105).aspx
    – richzilla
    Feb 23, 2017 at 15:53
  • 1
    Oh I completely agree! Sorry I just wrote it up quick and dirty. I excluded most of the SQL-y syntax out.
    – Ethilium
    Feb 23, 2017 at 15:55
  • Is there a way where when someone registers as a role of a Student, he gets created in the Student table also?
    – Truecolor
    Feb 23, 2017 at 15:59
  • In all honesty, you probably don't even what to give them the choice. Make everyone who logs in a student, or teacher? (I don't know how you want to split up roles outside of Admin) Then Allow admins a separate tab to add users to the Admin role/ table as needed.
    – Ethilium
    Feb 23, 2017 at 16:06
  • To answer your question, all you need is another SQL hit to the student table to update it as well as the Application Users table. You should already have all of the necessary pieces of user data to do so.
    – Ethilium
    Feb 23, 2017 at 16:08

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.