Exemple #1
0
        public ActionResult ViewOU(string id)
        {
            using (var db = new ADWebDB())
            {
                var organizationalUnit = db.DomainOU.Where(o => o.Name == id).FirstOrDefault();

                if (organizationalUnit != null)
                {
                    List <SelectListItem> enabledList = new List <SelectListItem>();
                    enabledList.Add(new SelectListItem {
                        Text = "Enabled", Value = "true"
                    });
                    enabledList.Add(new SelectListItem {
                        Text = "Disabled", Value = "false"
                    });

                    ViewBag.EnabledList = enabledList;
                    return(View(organizationalUnit));
                }
                else
                {
                    // If the user has clicked on (or typed in) an invalid OU
                    // we are going to re-direct them to the OU page and let them
                    // know that this was not a valid OU.
                    TempData["invalid_ou"] = "The OU " + id + " is not valid.";
                    return(RedirectToAction("OU"));
                }
            }
        }
Exemple #2
0
        public ActionResult ViewUser(string user)
        {
            ADDomain domain   = new ADDomain();
            ADUser   userInfo = domain.GetUserByID(user);

            if (userInfo != null)
            {
                // This is a good candidate to use Automapper on!
                UserViewModel userInfoVM = new UserViewModel();
                userInfoVM.SamAccountName = userInfo.SamAccountName;
                userInfoVM.GivenName      = userInfo.GivenName;
                userInfoVM.MiddleName     = userInfo.MiddleName;
                userInfoVM.Surname        = userInfo.Surname;
                userInfoVM.DisplayName    = userInfo.DisplayName;
                userInfoVM.EmailAddress   = userInfo.EmailAddress;
                userInfoVM.Title          = userInfo.Title;
                userInfoVM.Department     = userInfo.Department;
                userInfoVM.PhoneNumber    = userInfo.PhoneNumber;
                userInfoVM.Company        = userInfo.Company;
                userInfoVM.Notes          = userInfo.Notes;
                userInfoVM.Enabled        = userInfo.Enabled;
                userInfoVM.ExpirationDate = userInfo.AccountExpirationDate;

                // We are not using the WhenCreated field form the DomainUser
                // table in the database because each user object in the domain
                // should have a value for this property.
                userInfoVM.WhenCreated = userInfo.WhenCreated;

                userInfoVM.WhenChanged = userInfo.WhenChanged.ToLocalTime();
                userInfoVM.LogonCount  = userInfo.LogonCount.ToString();

                using (var db = new ADWebDB())
                {
                    var userDbInfo = db.DomainUsers.Find(user);

                    if (userDbInfo != null)
                    {
                        // If this part of the code is reached, then it means that the user
                        // currently being viewed is was created outside of the application and
                        // thus has an entry in the DomainUsers table.
                        var domainUser = domain.GetUserByID(userDbInfo.CreatedBy);
                        userInfoVM.DBInfo.Createdby   = userDbInfo.CreatedBy;
                        userInfoVM.DBInfo.WhenCreated = userDbInfo.DateCreated;
                        userInfoVM.UserHistory        = userDbInfo.UpdateHistory.OrderByDescending(u => u.DateUpdated).ToList();
                    }
                    else
                    {
                        userInfoVM.DBInfo.Createdby = "Unknown";
                    }
                }

                userInfoVM.UserGroups = domain.GetUserGroupsByUserId(user);

                userInfo.Dispose();
                return(View(userInfoVM));
            }

            return(View());
        }
Exemple #3
0
        public ActionResult CreateUserTemplate(CreateUserTemplateVM id)
        {
            if (ModelState.IsValid)
            {
                using (var db = new ADWebDB())
                {
                    id.UserTemplate.Enabled = true;
                    db.UserTemplate.Add(id.UserTemplate);
                    db.SaveChanges();

                    // We now have to iterate thru the list of groups that
                    // this user template has been configured to have so that
                    // we can add this information to the database. But we have
                    // to also be careful to make sure that only valid groups are
                    // added to the database because we are allowing users to enter
                    // the name of the group(s) they are looking for, there is a
                    // possibility that a group may not exist in the domain.
                    ADDomain domain = new ADDomain();
                    ADGroup  group;

                    // There is a possibility that the users will not add any groups
                    // when they first create the user template. We have to check for
                    // this now so that we can avoid a nasty error message!
                    if (id.Groups.Count > 0)
                    {
                        foreach (var grp in id.Groups)
                        {
                            group = domain.GetGroupBasicInfo(grp);

                            // We have to check if this group is in the domain, if it
                            // is then we would have retrieved a name for the group.
                            // If it's not a valid name, then the group name will be
                            // blank and thus this is a group that doesn't exit in
                            // the domain.
                            if (!string.IsNullOrWhiteSpace(group.GroupName))
                            {
                                db.UserTemplateGroup.Add(new UserTemplateGroup()
                                {
                                    Enabled           = true,
                                    Name              = group.GroupName,
                                    DistinguishedName = group.DN,
                                    UserTemplateID    = id.UserTemplate.UserTemplateID
                                });
                                db.SaveChanges();
                            }
                        }
                    }

                    TempData["user_template_created"] = "The user template '" + id.UserTemplate.Name + "' has been created successfully!";

                    return(RedirectToAction("UserTemplates"));
                }
            }
            else
            {
                return(View());
            }
        }
Exemple #4
0
 public ActionResult UserTemplates()
 {
     using (var db = new ADWebDB())
     {
         ViewBag.ActiveUserTemplates   = db.UserTemplate.Where(u => u.Enabled).ToList();
         ViewBag.DisabledUserTemplates = db.UserTemplate.Where(u => u.Enabled == false).ToList();
         return(View());
     }
 }
Exemple #5
0
 public void RemoveGroupFromUserTemplate(string groupID)
 {
     using (var db = new ADWebDB())
     {
         UserTemplateGroup group = db.UserTemplateGroup.Find(Int32.Parse(groupID));
         group.Enabled = false;
         db.SaveChanges();
     }
 }
Exemple #6
0
        public ActionResult CreateUser(CreateUserVM user)
        {
            if (ModelState.IsValid)
            {
                using (var db = new ADWebDB())
                {
                    ADWeb.Core.Models.User newUser = Mapper.Map <User>(user);
                    ADDomain domain = new ADDomain();

                    // Get User Template Settings so that we can use it to create
                    // the user.
                    UserTemplate userTemplate = db.UserTemplate
                                                .Find(user.UserTemplateID);

                    UserTemplateSettings userTemplateSettings = new UserTemplateSettings();
                    userTemplateSettings.ChangePasswordAtNextLogon = userTemplate.ChangePasswordAtNextLogon;
                    userTemplateSettings.UserCannotChangePassword  = userTemplate.UserCannotChangePassword;
                    userTemplateSettings.PasswordNeverExpires      = userTemplate.PasswordNeverExpires;
                    userTemplateSettings.AccountExpires            = userTemplate.AccountExpires;
                    userTemplateSettings.ExpirationRange           = userTemplate.ExpirationRange;
                    userTemplateSettings.ExpirationValue           = userTemplate.ExpirationValue;
                    userTemplateSettings.DomainOU = userTemplate.DomainOU.DistinguishedName;

                    // When getting the groups associated with a user template, we
                    // are only interested in getting those groups that are active (i.e.
                    // they have not been removed by the admins of the application). If this is
                    // not done, then there will be an error if a group happens to have been
                    // added, removed and then added again by one of the administrators. This should
                    // be a rare occurrance, but we have to check just to make sure no errors occur
                    // when creating user accounts.
                    foreach (var group in userTemplate.Groups.Where(u => u.Enabled == true).ToList())
                    {
                        userTemplateSettings.Groups.Add(group.Name);
                    }

                    domain.CreateUserWithTemplate(newUser, userTemplateSettings);
                    ADUser currentUser = domain.GetUserByID(User.Identity.Name);

                    // Insert the account to the Database. Note: we are only
                    // interested in basic information
                    DomainUser newDomainUser = new DomainUser();
                    newDomainUser.DateCreated = DateTime.Now;
                    newDomainUser.CreatedBy   = currentUser.GivenName + " " + currentUser.Surname;
                    newDomainUser.Username    = newUser.Username;

                    db.DomainUsers.Add(newDomainUser);
                    db.SaveChanges();

                    TempData["user_created_successfully"] = newUser.FirstName + " " + newUser.LastName + " has been created successfully!";
                    return(RedirectToAction("ViewUser", new { user = user.Username }));
                }
            }

            return(View());
        }
Exemple #7
0
        public ActionResult UserTemplates()
        {
            using (var db = new ADWebDB())
            {
                UserTemplateVM templateVM = new UserTemplateVM();
                templateVM.ActiveUserTemplates   = db.UserTemplate.Where(u => u.Enabled).ToList();
                templateVM.DisabledUserTemplates = db.UserTemplate.Where(u => u.Enabled == false).ToList();

                return(View(templateVM));
            }
        }
Exemple #8
0
        public ActionResult ViewUserTemplate(int id)
        {
            using (var db = new ADWebDB())
            {
                ViewUserTemplateVM utVM = new ViewUserTemplateVM();

                utVM.UserTemplate = db.UserTemplate.Where(ut => ut.UserTemplateID == id).FirstOrDefault();
                var ous = db.DomainOU.Where(ou => ou.Enabled == true).ToList();

                List <SelectListItem> ouItems = new List <SelectListItem>();
                foreach (var ou in ous)
                {
                    ouItems.Add(new SelectListItem {
                        Text     = ou.Name,
                        Value    = ou.DomainOUID.ToString(),
                        Selected = utVM.UserTemplate.DomainOUID == ou.DomainOUID
                    });
                }

                List <SelectListItem> utStatus = new List <SelectListItem>();
                utStatus.Add(new SelectListItem()
                {
                    Text = "Enabled", Value = "true"
                });
                utStatus.Add(new SelectListItem()
                {
                    Text = "Disabled", Value = "false"
                });

                // I am calling the ToList method here so that we can get a list groups
                // associated with this User Template. If we don'd do this here, then
                // I cannot get access to this list from the View (I get a message that
                // the context has already been disposed of and therefore cannot access
                // this information). Calling this method here should not be that big of
                // hit performance wise as I don't expect user templates to have a lot of
                // groups associated with them.
                utVM.UserTemplate.Groups.Where(g => g.Enabled == true).ToList();

                ViewBag.OUList   = ouItems;
                ViewBag.UTStatus = utStatus;

                if (utVM.UserTemplate != null)
                {
                    return(View(utVM));
                }
                else
                {
                    TempData["invalid_user_template"] = "Invalid User template ID";
                    return(RedirectToAction("UserTemplates"));
                }
            }
        }
Exemple #9
0
        public ActionResult OU()
        {
            using (var db = new ADWebDB())
            {
                OUViewModel ouVM = new OUViewModel();
                ouVM.ActiveOUs   = new List <DomainOU>();
                ouVM.DisabledOUs = new List <DomainOU>();

                ouVM.ActiveOUs   = db.DomainOU.Where(ou => ou.Enabled).ToList();
                ouVM.DisabledOUs = db.DomainOU.Where(ou => ou.Enabled == false).ToList();

                return(View(ouVM));
            }
        }
Exemple #10
0
        public ADDomain()
        {
            using (var db = new ADWebDB())
            {
                ServerName = db.ADSetting.Where(a => a.Name == "server_name").Select(a => a.Value).SingleOrDefault();
                TempUsers  = db.ADSetting.Where(a => a.Name == "temp_users").Select(a => a.Value).SingleOrDefault();
                GroupsOU   = db.ADSetting.Where(a => a.Name == "groups_ou").Select(a => a.Value).SingleOrDefault();
                UPNSuffix  = db.ADSetting.Where(a => a.Name == "upn_suffix").Select(a => a.Value).SingleOrDefault();
            }

            // These will be stored in the web.config file for now, may be moved
            // to the database on a later date if deemed necessary.
            ServiceUser     = WebConfigurationManager.AppSettings["service_user"];
            ServicePassword = WebConfigurationManager.AppSettings["service_password"];
        }
Exemple #11
0
        public ActionResult ViewUserTemplate(int id)
        {
            using (var db = new ADWebDB())
            {
                ViewUserTemplateVM utVM = new ViewUserTemplateVM();
                utVM.UserTemplate = db.UserTemplate.Where(ut => ut.UserTemplateID == id).FirstOrDefault();

                var ous = db.DomainOU.Where(ou => ou.Enabled == true).ToList();

                List <SelectListItem> ouItems = new List <SelectListItem>();
                foreach (var ou in ous)
                {
                    ouItems.Add(new SelectListItem {
                        Text     = ou.Name,
                        Value    = ou.DomainOUID.ToString(),
                        Selected = utVM.UserTemplate.DomainOUID == ou.DomainOUID
                    });
                }

                List <SelectListItem> utStatus = new List <SelectListItem>();
                utStatus.Add(new SelectListItem()
                {
                    Text = "Enabled", Value = "true"
                });
                utStatus.Add(new SelectListItem()
                {
                    Text = "Disabled", Value = "false"
                });

                ViewBag.OUList   = ouItems;
                ViewBag.UTStatus = utStatus;

                // We are only interested in seeing groups that are enabled. The users have the
                // ability to remove groups that have been added to this template, at which time
                // those groups have their Enabled property set to false.
                utVM.UserTemplate.Groups = utVM.UserTemplate.Groups.Where(g => g.Enabled).ToList();

                if (utVM.UserTemplate != null)
                {
                    return(View(utVM));
                }
                else
                {
                    TempData["invalid_user_template"] = "Invalid User template ID";
                    return(RedirectToAction("UserTemplates"));
                }
            }
        }
Exemple #12
0
        public JsonResult IsTemplateNameUnique(string Name)
        {
            using (var db = new ADWebDB())
            {
                var doesTemplateExist = db.UserTemplate.Any(t => t.Name == Name);

                if (doesTemplateExist)
                {
                    return(Json(false, JsonRequestBehavior.AllowGet));
                }
                else
                {
                    return(Json(true, JsonRequestBehavior.AllowGet));
                }
            }
        }
Exemple #13
0
        public ActionResult CreateUser()
        {
            using (var db = new ADWebDB())
            {
                List <SelectListItem> userTemplates = new List <SelectListItem>();

                var templates = db.UserTemplate.Where(u => u.Enabled).ToList();
                foreach (var template in templates)
                {
                    userTemplates.Add(new SelectListItem()
                    {
                        Value = template.UserTemplateID.ToString(), Text = template.Name
                    });
                }

                ViewBag.UTList = userTemplates;
            }

            return(View());
        }
Exemple #14
0
        public ActionResult UpdateOU(DomainOU id)
        {
            if (ModelState.IsValid)
            {
                using (var db = new ADWebDB())
                {
                    db.Entry(id).State = EntityState.Modified;
                    db.SaveChanges();

                    TempData["ou_updated"] = "The OU " + id.Name + " has been successfully updated!";
                    return(RedirectToAction("OU"));
                }
            }
            else
            {
                ModelState.AddModelError("", "Unable to update the Organizational Unit.");
            }

            return(View());
        }
Exemple #15
0
        public ActionResult CreateUserTemplate()
        {
            using (var db = new ADWebDB())
            {
                CreateUserTemplateVM userTemplateVM = new CreateUserTemplateVM();
                userTemplateVM.OrganizationalUnits          = db.DomainOU.Where(o => o.Enabled == true).ToList();
                userTemplateVM.UserTemplate.ExpirationRange = UserExpirationRange.Days;

                List <SelectListItem> ouItems = new List <SelectListItem>();
                foreach (var ou in userTemplateVM.OrganizationalUnits)
                {
                    ouItems.Add(new SelectListItem {
                        Text = ou.Name, Value = ou.DomainOUID.ToString()
                    });
                }

                ViewBag.OUList = ouItems;

                return(View(userTemplateVM));
            }
        }
Exemple #16
0
        public ActionResult CreateOU(DomainOU newOU)
        {
            if (ModelState.IsValid)
            {
                using (var db = new ADWebDB())
                {
                    newOU.Enabled = true;

                    db.DomainOU.Add(newOU);
                    db.SaveChanges();

                    TempData["ou_created"] = "The Organizationl Unit " + newOU.Name + " has been created successfully!";
                    return(RedirectToAction("OU"));
                }
            }
            else
            {
                ModelState.AddModelError("", "Unable to create Organizational Unit.");
            }

            return(View("OU"));
        }
Exemple #17
0
        public ActionResult ViewUser(string userId)
        {
            ADDomain domain = new ADDomain();
            ADUser   user   = domain.GetUserByID(userId);

            if (user != null)
            {
                UserViewModel viewModel = new UserViewModel();
                viewModel.SamAccountName = user.SamAccountName;
                viewModel.GivenName      = user.GivenName;
                viewModel.MiddleName     = user.MiddleName;
                viewModel.Surname        = user.Surname;
                viewModel.DisplayName    = user.DisplayName;
                viewModel.EmailAddress   = user.EmailAddress;
                viewModel.Title          = user.Title;
                viewModel.Department     = user.Department;
                viewModel.PhoneNumber    = user.PhoneNumber;
                viewModel.Company        = user.Company;
                viewModel.Notes          = user.Notes;
                viewModel.Enabled        = user.Enabled;
                viewModel.ExpirationDate = user.AccountExpirationDate;

                // We are not using the WhenCreated field form the DomainUser
                // table in the database because each user object in the domain
                // should have a value for this property.
                viewModel.WhenCreated = user.WhenCreated;

                // The WhenChanged property comes straight from Active Directory
                // I may have to come back to this and use data from the database
                // to get the date when an account was last changed. The reason for
                // this is because if a user logins, this value is updated to reflect
                // this and it's not really a change in my mind. Any changes that are
                // done on a user account (thru the application) should be the real
                // indicators when an account was changed (and also indicate what type
                // of change happened).
                viewModel.WhenChanged = user.WhenChanged.ToLocalTime();
                viewModel.LogonCount  = user.LogonCount.ToString();

                using (var db = new ADWebDB())
                {
                    var userDbInfo = db.DomainUsers.Where(u => u.Username == userId).FirstOrDefault();

                    if (userDbInfo != null)
                    {
                        // If this part of the code is reached, then it means that the user
                        // currently being viewed is was created inside of the application and
                        // thus has an entry in the DomainUsers table.
                        var domainUser = domain.GetUserByID(userDbInfo.CreatedBy);
                        viewModel.DBInfo.Createdby   = userDbInfo.CreatedBy;
                        viewModel.DBInfo.WhenCreated = userDbInfo.DateCreated;
                        viewModel.UserHistory        = userDbInfo.UpdateHistory.OrderByDescending(u => u.DateUpdated).ToList();
                    }
                    else
                    {
                        viewModel.DBInfo.Createdby = "Unknown";
                    }
                }

                viewModel.UserGroups = domain.GetUserGroupsByUserId(userId);

                user.Dispose();
                return(View(viewModel));
            }

            return(View());
        }
Exemple #18
0
        public ActionResult UpdateUser(UserViewModel user)
        {
            if (ModelState.IsValid)
            {
                ADDomain      domain         = new ADDomain();
                StringBuilder msg            = new StringBuilder();
                bool          userInfoUpdate = false;

                msg.Append("<ul class=\"update-details\">");

                // We first need to record what was changed on the user
                // account by comparing what the user currently has on
                // Active Directory to what is being passed to this method
                ADUser currentUser = domain.GetUserByID(user.SamAccountName);

                // Now we compare the values that are currently stored in the domain
                // with what's being passed to this method. If there are any changes,
                // then these are recorded and will be stored in the database.
                if (!currentUser.GivenName.Equals(user.GivenName))
                {
                    userInfoUpdate = true;
                    msg.Append("<li>First Name Changed from '" + currentUser.GivenName + "' to '" + user.GivenName + "'</li>");
                }

                if (!currentUser.Surname.Equals(user.Surname))
                {
                    userInfoUpdate = true;
                    msg.Append("<li>Last Name Changed from '" + currentUser.Surname + "' to '" + user.Surname + "'</li>");
                }

                if (!currentUser.MiddleName.Equals(user.MiddleName))
                {
                    if (!String.IsNullOrEmpty(user.MiddleName))
                    {
                        userInfoUpdate = true;
                        msg.Append("<li>Middle Name Changed from '" + currentUser.MiddleName + "' to '" + user.MiddleName + "'</li>");
                    }
                }

                if (!currentUser.DisplayName.Equals(user.DisplayName))
                {
                    userInfoUpdate = true;
                    msg.Append("<li>Display Name Changed from '" + currentUser.DisplayName + "' to '" + user.DisplayName + "'</li>");
                }

                if (!currentUser.EmailAddress.Equals(user.EmailAddress))
                {
                    userInfoUpdate = true;
                    msg.Append("<li>Email Address Changed from '" + currentUser.EmailAddress + "' to '" + user.EmailAddress + "'</li>");
                }

                if (!currentUser.PhoneNumber.Equals(user.PhoneNumber))
                {
                    if (!String.IsNullOrEmpty(user.PhoneNumber))
                    {
                        userInfoUpdate = true;
                        msg.Append("<li>Phone Number Changed from '" + currentUser.PhoneNumber + "' to '" + user.PhoneNumber + "'</li>");
                    }
                }

                if (!currentUser.Title.Equals(user.Title))
                {
                    userInfoUpdate = true;
                    msg.Append("<li>Title Changed from '" + currentUser.Title + "' to '" + user.Title + "'</li>");
                }

                if (!currentUser.Company.Equals(user.Company))
                {
                    userInfoUpdate = true;
                    msg.Append("<li>Company Changed from '" + currentUser.Company + "' to '" + user.Company + "'</li>");
                }

                if (!currentUser.Department.Equals(user.Department))
                {
                    userInfoUpdate = true;
                    msg.Append("<li>Department Changed from '" + currentUser.Department + "' to '" + user.Department + "'</li>");
                }

                if (!currentUser.Notes.Equals(user.Notes))
                {
                    if (!String.IsNullOrEmpty(user.Notes))
                    {
                        userInfoUpdate = true;
                        msg.Append("<li>Notes Changed from '" + currentUser.Notes + "' to '" + user.Notes + "'</li>");
                    }
                }

                msg.Append("</ul>");

                ADWeb.Core.Models.User userModel = Mapper.Map <User>(user);

                domain.UpdateUser(userModel);

                // There is a possiblity that a user may accidentally hit the update
                // button but nothing has changed in the user's information. If this
                // happens, we don't want anything to be written to the database. The
                // following condition checks for this scenario.
                if (userInfoUpdate)
                {
                    using (var db = new ADWebDB())
                    {
                        ADUser loggedInUser = domain.GetUserByID(User.Identity.Name);

                        // Before adding a new update history for this user, we first have
                        // to check to see if this account has an entry in the DomainUsers
                        // table. If it doesn't then we'll go ahead and create one. If it does,
                        // then we'll just insert the update history to the table.
                        var userDbInfo = db.DomainUsers.Find(user.SamAccountName);

                        if (userDbInfo == null)
                        {
                            // If we have reached this part of the code then it means that
                            // we have come accross a user that was not created thru the
                            // application and thus has no entry in the DomainUsers table.
                            // We are going to be creating an entry into the DomainUser table,
                            // but we are not going to use the currently logged in user who is
                            // viewing this account as the person that created the account.
                            // The reason I don't want to store the username is because the
                            // entry was not created by the user, instead it was created
                            // outside the application. I am going to be making this a unique
                            // value just in case we need to use this later on for reports.
                            string createdBy = "Outside of Application";

                            DomainUser newUser = new DomainUser();
                            newUser.CreatedBy   = createdBy;
                            newUser.Username    = currentUser.SamAccountName;
                            newUser.DateCreated = currentUser.WhenCreated;

                            // Entry that identifies this as a user who we just inserted
                            // an entry to the DomainUsers table for.
                            UserUpdateHistory newUserHistory = new UserUpdateHistory();
                            newUserHistory.UpdatedBy   = createdBy;
                            newUserHistory.Username    = user.SamAccountName;
                            newUserHistory.UpdateType  = UserUpdateType.CreatedDBEntry;
                            newUserHistory.DateUpdated = DateTime.Now;
                            newUserHistory.Notes       = "<ul class=\"update-details\"><li>New User Added to table by the system.</li></ul>";

                            // This is the actual changes that were made for this user
                            // when the update user button was clicked on and submitted for
                            // this request.
                            UserUpdateHistory userChange = new UserUpdateHistory();
                            userChange.UpdatedBy  = loggedInUser.GivenName + " " + loggedInUser.Surname;
                            userChange.Username   = user.SamAccountName;
                            userChange.UpdateType = UserUpdateType.UserInfo;

                            // I am adding 10 milli seconds to this value so that when we
                            // retrieve it from the database this will show up later on
                            // as we order the results from this table based on the
                            // date updated field!
                            userChange.DateUpdated = DateTime.Now.AddMilliseconds(10);
                            userChange.Notes       = msg.ToString();

                            db.DomainUsers.Add(newUser);
                            db.UserUpdateHistory.Add(newUserHistory);
                            db.UserUpdateHistory.Add(userChange);
                            db.SaveChanges();
                        }
                        else
                        {
                            UserUpdateHistory userChange = new UserUpdateHistory();
                            userChange.UpdatedBy   = loggedInUser.GivenName + " " + loggedInUser.Surname;
                            userChange.Username    = user.SamAccountName;
                            userChange.UpdateType  = UserUpdateType.UserInfo;
                            userChange.DateUpdated = DateTime.Now;
                            userChange.Notes       = msg.ToString();

                            db.UserUpdateHistory.Add(userChange);
                        }

                        db.SaveChanges();
                    }

                    TempData["user_updated_successfully"] = user.GivenName + " " + user.Surname + "'s account has been successfully updated!";
                }
                else
                {
                    TempData["user_updated_successfully"] = "No updates were done for " + user.GivenName + " " + user.Surname + "'s account.";
                }

                return(RedirectToAction("ViewUser", new { user = user.SamAccountName }));
            }

            return(View());
        }
Exemple #19
0
        public ActionResult AddUserToGroups(string SamAccountName, List <string> Groups)
        {
            ADDomain domain = new ADDomain();

            // The current implementation of this feature will allow users to type in
            // a few characters of a group name and if any matches are found then those
            // matches are displayed to the user. There is a chance that the user may just
            // type in the name of the group he/she wants to add and not use any of the
            // returned results. For this reason, I am doing an extra check on the domain
            // to make sure that whatever has been entered are valid groups. If a group
            // name has been entered that is not valid (i.e. it doesn't exist) then that
            // group will not be added to the following list. After generating this list,
            // we are doing an extra check to see if it's empty (which can theoretically
            // happen) and if so then we just re-direct the user back to the ViewUser page
            // and send a long a message of the issue why no group(s) were added to the user.
            List <string> validatedGroups = domain.ValidateGroups(Groups);

            if (validatedGroups.Count == 0)
            {
                TempData["invalid_groups"] = @"Invalid Group Names. The group(s) you tried to add are not valid group name. 
                                               Please check the name of the group and try again.";
                return(RedirectToAction("ViewUser", new { user = SamAccountName }));
            }

            // There is the posibility that a group that the user already belongs
            // to is part of the groups list being passed to this method. I have to
            // get a list of the current groups that this user belongs to and before
            // adding any of the groups that have been passed to this method, I must
            // make sure that it doesn't already exist. If it does, then the group
            // trying to be added will just be discarded.
            List <string> currentGroups = domain.GetCurrentUserGroups(SamAccountName);

            // This will hold the list of groups that will be added to the
            // user account.
            List <string> newGroupsToAdd = new List <string>();

            foreach (var group in validatedGroups)
            {
                if (!currentGroups.Contains(group))
                {
                    newGroupsToAdd.Add(group);
                }
            }

            // If we are adding a group (or list of groups) that the user already
            // belongs to then none of these group should be added.
            if (newGroupsToAdd.Count == 0)
            {
                TempData["no_groups_added"] = "No Groups have been added to this user as the user already is part of the groups submitted.";
                return(RedirectToAction("ViewUser", new { user = SamAccountName }));
            }

            // At this time we have filtered out the groups so that only
            // new groups are added to this user
            domain.AddUserToGroups(SamAccountName, newGroupsToAdd);

            // Now we have to log this action so that it shows up on the
            // change history for this user
            using (var db = new ADWebDB())
            {
                ADUser loggedInUser = domain.GetUserByID(User.Identity.Name);

                // The following code generates the update details for this action
                StringBuilder updateNotes = new StringBuilder();
                updateNotes.Append("<p>The following groups have been added to this user:</p>");
                updateNotes.Append("<ul class=\"update-details\">");

                foreach (var group in newGroupsToAdd)
                {
                    updateNotes.Append("<li>" + group + "</li>");
                }

                updateNotes.Append("</ul>");

                UserUpdateHistory newGroupHistory = new UserUpdateHistory();
                newGroupHistory.UpdatedBy   = loggedInUser.GivenName + " " + loggedInUser.Surname;
                newGroupHistory.DateUpdated = DateTime.Now;
                newGroupHistory.UpdateType  = UserUpdateType.AddedToGroup;
                newGroupHistory.Notes       = updateNotes.ToString();
                newGroupHistory.Username    = SamAccountName;

                // Before adding this update history entry into the database
                // we have to check for the possibility of the user having no
                // entry in the DomainUsers table.
                DomainUser user = db.DomainUsers.Find(SamAccountName);

                if (user != null)
                {
                    // The user has an existing entry in the DomainUser
                    // table
                    db.UserUpdateHistory.Add(newGroupHistory);
                    db.SaveChanges();
                }
                else
                {
                    DomainUser newDomainUser = new DomainUser();
                    newDomainUser.DateCreated = DateTime.Now;
                    newDomainUser.CreatedBy   = loggedInUser.GivenName + " " + loggedInUser.Surname;
                    newDomainUser.Username    = SamAccountName;

                    db.DomainUsers.Add(newDomainUser);
                    db.SaveChanges();

                    // Entry that identifies this as a user who we just inserted
                    // an entry to the DomainUsers table for.
                    UserUpdateHistory newUserHistory = new UserUpdateHistory();
                    newUserHistory.UpdatedBy   = "System Generated";
                    newUserHistory.Username    = SamAccountName;
                    newUserHistory.UpdateType  = UserUpdateType.CreatedDBEntry;
                    newUserHistory.DateUpdated = DateTime.Now;
                    newUserHistory.Notes       = "<ul class=\"update-details\"><li>New User Added to table by the system.</li></ul>";

                    db.UserUpdateHistory.Add(newUserHistory);
                    db.UserUpdateHistory.Add(newGroupHistory);
                    db.SaveChanges();
                }

                TempData["groups_added_successfully"] = "Groups have been added successfully to this user!";
                return(RedirectToAction("ViewUser", new { user = SamAccountName }));
            }
        }
Exemple #20
0
        public ActionResult UpdateUserTemplate(ViewUserTemplateVM id)
        {
            if (ModelState.IsValid)
            {
                using (var db = new ADWebDB())
                {
                    db.UserTemplate.Attach(id.UserTemplate);
                    db.Entry(id.UserTemplate).Property(ut => ut.Name).IsModified                      = true;
                    db.Entry(id.UserTemplate).Property(ut => ut.Enabled).IsModified                   = true;
                    db.Entry(id.UserTemplate).Property(ut => ut.DomainOUID).IsModified                = true;
                    db.Entry(id.UserTemplate).Property(ut => ut.PasswordNeverExpires).IsModified      = true;
                    db.Entry(id.UserTemplate).Property(ut => ut.ChangePasswordAtNextLogon).IsModified = true;
                    db.Entry(id.UserTemplate).Property(ut => ut.UserCannotChangePassword).IsModified  = true;
                    db.Entry(id.UserTemplate).Property(ut => ut.AccountExpires).IsModified            = true;
                    db.Entry(id.UserTemplate).Property(ut => ut.ExpirationRange).IsModified           = true;
                    db.Entry(id.UserTemplate).Property(ut => ut.ExpirationValue).IsModified           = true;
                    db.Entry(id.UserTemplate).Property(ut => ut.Notes).IsModified                     = true;

                    db.SaveChanges();

                    // We need to check to see if a new group (or groups) have been
                    // added to this user template. If so then we'll add the group!
                    if (id.Groups.Count > 0)
                    {
                        ADDomain domain = new ADDomain();
                        ADGroup  group;

                        // We also have to check that the group(s) being added to this
                        // user template don't alreay exist. If it does, then it will
                        // not be added. For us to do this check, we have to get the list
                        // of groups first. Also, please note that we have to check that we
                        // only get active groups!
                        var existingGroups = db.UserTemplateGroup
                                             .Where(u => u.UserTemplateID == id.UserTemplate.UserTemplateID && u.Enabled == true)
                                             .Select(u => u.Name).ToList();

                        foreach (var grp in id.Groups)
                        {
                            // This is where we check if this user template already has
                            // the group that is being added. If it does, then we simply
                            // continue out of this iteration of the foreach loop and go on
                            // to the next group being added.
                            if (existingGroups.Contains(grp))
                            {
                                continue;
                            }

                            group = domain.GetGroupBasicInfo(grp);

                            // We have to check if this group is in the domain, if it
                            // is then we would have retrieved a name for the group.
                            // If it's not a valid name, then the group name will be
                            // blank and thus this is a group that doesn't exit in
                            // the domain.
                            if (!string.IsNullOrWhiteSpace(group.GroupName))
                            {
                                db.UserTemplateGroup.Add(new UserTemplateGroup()
                                {
                                    Enabled           = true,
                                    Name              = group.GroupName,
                                    DistinguishedName = group.DN,
                                    UserTemplateID    = id.UserTemplate.UserTemplateID
                                });
                                db.SaveChanges();
                            }
                        }
                    }

                    TempData["user_template_updated"] = "The user template '" + id.UserTemplate.Name + "' has been successfully updated!";
                    return(RedirectToAction("UserTemplates"));
                }
            }
            else
            {
                TempData["error_updating_user_template"] = "Error updating Template";
                return(RedirectToAction("ViewUserTemplate", new { id = id.UserTemplate.UserTemplateID }));
            }
        }