特定代码,控制器,型号或其他地方的正确位置

时间:2015-07-30 08:32:43

标签: c# asp.net-mvc asp.net-mvc-5

我已经开始学习C#MVC 5用于我正在工作的房间库存项目。 我正在使用活动目录对用户进行身份验证,然后将这些详细信息存储在数据库中,以便我可以将用户分配给分配了项目的房间和租赁。

我使用了Visual Studio 2013附带的股票MVC 5模板,因为我只有一个月的时间来完成项目,没有先前的知识,也没有时间编写花哨的html / css前端和我依赖于开箱即用的外观。

我编写了一些代码,一旦用户使用与AD链接的表单身份验证成功登录,它会运行检查以查看数据库中是否存在用户,如果没有创建一个用户,如果没有,则会检查是否存在它已被设置为非活动状态,并在需要时重新激活它。

我已将此代码放在登录httppost操作下的AccountController中。因为我是MVC的新手,我想检查这是否是正确的位置,或者我是否应该为此功能创建一个新类,或者它是否应该在我使用实体框架代码创建数据库的模型区域中。什么是最佳做法?

以下是代码,并提前感谢任何帮助。我为冗长的帖子而不是恒星代码道歉。不要抱怨任何批评,因为我宁愿现在就把它弄得比一次又一次犯错误。

[HttpPost]
    public ActionResult Login(LoginModel model, string returnUrl)
    {
        if (!ModelState.IsValid)
        {
            return View(model);
        }

        // Put this method in place to allow multiple domains for login. References Web.config for providers
        MembershipProvider domainProvider;
        switch (model.Domain)
        {
            case "Student":
                domainProvider = Membership.Providers["studentADMembershipProvider"];
                break;
            case "Staff":
                domainProvider = Membership.Providers["staffADMembershipProvider"];
                break;
            default:
                throw (new Exception("This domain is not supported"));
        }


        // Method for authenticating users on AD to allow system integration and also add or update user in Users Database
        if (domainProvider.ValidateUser(model.UserName, model.Password))
        {
            FormsAuthentication.SetAuthCookie(model.UserName, model.RememberMe);


            //Code for creating new user based on successfull logged in user.

            //define which domain to link too. otherwise will always default to staff
            PrincipalContext myContext;
            if (model.Domain == "Staff")
            {
                myContext = new PrincipalContext(ContextType.Domain, "staff.domain.com");
            }
            else
            {
                myContext = new PrincipalContext(ContextType.Domain, "student.domain.com");
            }
            UserPrincipal aduser = UserPrincipal.FindByIdentity(myContext, IdentityType.SamAccountName, model.UserName);

            //Check for existence of user with username that matches loged in user
            var userSearch = db.Users.Count(b => b.Username == aduser.SamAccountName);
            if (userSearch == 0)
            {
                // User does not exist, therefore create user
                User user = new User()
                {
                    IsActive = 1,
                    Username = aduser.SamAccountName,
                    FirstName = aduser.GivenName,
                    LastName = aduser.Surname,
                    Extension = aduser.VoiceTelephoneNumber,
                    Email = aduser.EmailAddress,
                    UserTypeId = 3
                };
                db.Users.Add(user);
                db.SaveChanges();
            }
            else
            {
                // User does exist, but has been deactivated, therefore reactivate
                var activateUser = db.Users.FirstOrDefault(d => d.Username == aduser.SamAccountName);
                if (activateUser.IsActive == 0)
                {
                    activateUser.IsActive = 1;
                    db.SaveChanges();
                    //db.Users(activateUser.UserId).State = EntityState.Modified;
                }
            }


            if (Url.IsLocalUrl(returnUrl) && returnUrl.Length > 1 && returnUrl.StartsWith("/")
                && !returnUrl.StartsWith("//") && !returnUrl.StartsWith("/\\"))
            {
                return Redirect(returnUrl);
            }

            return RedirectToAction("Index", "Home");
        }

        ModelState.AddModelError(string.Empty, "The user name or password provided is incorrect.");

        return View(model);
    }

0 个答案:

没有答案