Search code examples
c#asp.net-mvcsql-server-2008forms-authentication

Account creation via Form authentication ASP.NET MVC page


I'm working on an intranet, so far I have switched from Windows authentication to Form authentication and I'm able to connect / register etc.

But here's what I'm expected to do : Instead of being able to create and account through the usual forms route, I wish to link the list of employees (that has many parameters, such as Login, Password, Name etc.) and be able to create a new user when I create a new Employee.

Here is my Employee creation controller :

public ActionResult Create()
    {
        ViewBag.CompanyList = _service.ListCompany();
        ViewBag.SupervisorList = _service.ListSupervisor();

        return View();
    }

    //
    // POST: /Employee/Create

    [HttpPost]
    public ActionResult Create([Bind(Exclude = "Id")] Employee objEmployee, FormCollection form)
    {            
        ViewBag.CompanyList = _service.ListCompany();
        ViewBag.SupervisorList = _service.ListSupervisor();

        objEmployee.CreatedDate = System.DateTime.Now;
        objEmployee.UpdatedDate = System.DateTime.Now;
        objEmployee.CompanyId = int.Parse(form["CompanyId"]);
        objEmployee.Supervisor = form["Supervisor"];

        if (_service.Create(objEmployee))
            return new RedirectResult(Url.Action("Index"));

        else
        {
            if (!_service.Validate(objEmployee))
                return View();
            else
                return new RedirectResult(Url.Action("Index", "Error", new { Message = "Error Create Employee", NextPage = CRAWebSiteMVC.Properties.Resources.Employee + @"/" + CRAWebSiteMVC.Properties.Resources.Create }));
        } 
    }

And here's the usual way I create an account via the normal form auth. registering :

    [HttpPost]
    [AllowAnonymous]
    [ValidateAntiForgeryToken]
    public ActionResult Register(RegisterModel model)
    {
        if (ModelState.IsValid)
        {
            // Attempt to register the user
            try
            {
                WebSecurity.CreateUserAndAccount(model.UserName, model.Password);
                WebSecurity.Login(model.UserName, model.Password);
                return RedirectToAction("Index", "Home");
            }
            [...]
        }

        // If we got this far, something failed, redisplay form
        return View(model);
    }

How may I create an account via the Employee creation panel and basically replace the usual user list by the employee list?


Solution

  • Now Usually the context, is automatically declared as db <- in the controllers. it is Declared as

    private ApplicationDbContext db = new ApplicationDbContext();
    

    But in this Case in my example it says. context so just Change context to db if ApplicationDbContext is declared.

    The bottom is an Example of Creating a User class and an Employee class at the same time. So inserting a record to the User While having a reference to the Employee class. But I guess you get that by now.

    Notice that, I didn't add an encryption to the password. Cause that is a whole new topic of question.

    var userStore = new UserStore<ApplicationUser>(context);
            var userManager = new UserManager<ApplicationUser>(userStore);
    
    
    
            if (!context.Users.Any(t => t.UserName == "[email protected]"))
            {
                var user = new ApplicationUser { UserName = "[email protected]", Email = "[email protected]" };
                userManager.Create(user, "Password1!");
    
                context.Roles.AddOrUpdate(r => r.Name, new IdentityRole { Name = "Admin" });
                context.Roles.AddOrUpdate(r => r.Name, new IdentityRole { Name = "Receptionist" });
                context.Roles.AddOrUpdate(r => r.Name, new IdentityRole { Name = "Security" });
                context.SaveChanges();
    
                userManager.AddToRole(user.Id, "Admin");
    
                Employee admingEmployee = new Employee
                {
                    Age=25,
                    Citizenship="Filipino",
                    CivilStatus=CivilStatus.Single,
                    DateOfBirth=DateTime.Now,
                    EmailAddress="[email protected]",
                    FirstName="Admin",
                    Gender=Gender.Male,
                    HomeAddress="None",
                    LandLine="531-5555",
                    LastName="Administrator",
                    MiddleName="admin",
                    MobileNumber="09275225222",
                    Photo = "*******",
                    PlaceofBirth="*****",
                    Password = "********",
                    Role=Role.Admin
                };
    
                context.Employees.Add(admingEmployee);
                context.SaveChanges();