Subversion Repositories Code-Repo

Rev

Blame | Last modification | View Log | RSS feed

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Diagnostics;
using System.IO;
using System.Windows.Forms;
using System.Security.AccessControl;

namespace SWAT_Office_App
{
    class ManageUserAccounts
    {
        public static List<string> UserAccountsList = new List<string>();
        public static bool AddUser(string username, string password)
        {
            try
            {
                // Returns true if user was added successfully
                foreach (string user in UserAccountsList)
                {
                    if (username.ToLower() == user.ToLower())
                    {
                        MessageBox.Show("Username already exists", "Error");
                        return false;
                    }
                }
                Process netProcess = new Process();
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
                netProcess.StartInfo.FileName = "net.exe";
                netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                netProcess.StartInfo.CreateNoWindow = true;
                // Arguments for user account creation. Run NET HELP USER from the command prompt for more info.
                netProcess.StartInfo.Arguments = "USER \"" + username + "\" \"" + password + 
                    "\" /ADD /ACTIVE:YES /PASSWORDCHG:NO /PASSWORDREQ:YES /EXPIRES:NEVER /COMMENT:" + DateTime.Now.ToShortDateString();
                netProcess.Start();
                netProcess.WaitForExit();
                netProcess.Close();
                return true;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
                return false;
            }
        }
        public static void DeleteUser(List<string> usernames)
        {
            try
            {
                foreach (string user in usernames)
                {
                    if (Directory.Exists(Settings_Form.sharedFolderLocation + @"\" + user))
                    {
                        // Prompts for deletion of folder as well as the user account
                        DialogResult result = MessageBox.Show("A shared folder exists for the user " + user + "!" +
                            "\nDelete the folder and all data within the folder?",
                           "Warning!", MessageBoxButtons.YesNo);
                        if (result == DialogResult.Yes)
                        {
                            Process netProcess = new Process();
                            netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
                            netProcess.StartInfo.FileName = "net.exe";
                            netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                            netProcess.StartInfo.CreateNoWindow = true;
                            // Arguments for user account deletion. Run NET HELP USER from the command prompt for more info.
                            netProcess.StartInfo.Arguments = "USER \"" + user + "\" /DELETE";
                            netProcess.Start();
                            netProcess.WaitForExit();
                            netProcess.Close();

                            DeleteShareFolder(user);
                        }
                    }
                    // If no folders exist for the user, account is deleted without prompting
                    else
                    {
                        Process netProcess = new Process();
                        netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
                        netProcess.StartInfo.FileName = "net.exe";
                        netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                        netProcess.StartInfo.CreateNoWindow = true;
                        // Arguments for user account deletion. Run NET HELP USER from the command prompt for more info.
                        netProcess.StartInfo.Arguments = "USER \"" + user + "\" /DELETE";
                        netProcess.Start();
                        netProcess.WaitForExit();
                        netProcess.Close();
                    }

                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }
        public static void QueryUserAccounts()
        {
            // Function that reads the user accounts on the local computer to UserAccountsList
            UserAccountsList.Clear();
            try
            {
                Process netProcess = new Process();
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
                netProcess.StartInfo.FileName = "net.exe";
                netProcess.StartInfo.UseShellExecute = false;
                netProcess.StartInfo.RedirectStandardOutput = true;
                netProcess.StartInfo.CreateNoWindow = true;
                netProcess.StartInfo.Arguments = "USER";
                netProcess.Start();
                string netOutput = netProcess.StandardOutput.ReadToEnd();
                // Splits the output into seperate strings for further processing
                string[] tempSplit = netOutput.Split(new string[] { "  ", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                // Roundabout way of trimming each string in the array
                string[] netOutputSplit = new string[tempSplit.Length];
                for (int i = 0; i < tempSplit.Length; i++)
                    netOutputSplit[i] = tempSplit[i].Trim();
                // Imports the string array into the UserAccountsList List
                UserAccountsList.AddRange(netOutputSplit);
                // Removes the header and footer from the List
                UserAccountsList.RemoveRange(0, 2);
                UserAccountsList.RemoveRange(UserAccountsList.Count() - 1, 1);
                // Removes any additional empty entries
                UserAccountsList.RemoveAll(IsStringBlank);
                netProcess.WaitForExit();
                netProcess.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }
        public static string [] QueryUserAccountExtraInformation(string username)
        {
            // Returns a string array with password requirement and date of account creation
            string[] stringArray = { "", "" };
            try
            {
                Process netProcess = new Process();
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
                netProcess.StartInfo.FileName = "net.exe";
                netProcess.StartInfo.UseShellExecute = false;
                netProcess.StartInfo.RedirectStandardOutput = true;
                netProcess.StartInfo.CreateNoWindow = true;
                netProcess.StartInfo.Arguments = "USER " + "\"" + username + "\"";
                netProcess.Start();
                string netOutput = netProcess.StandardOutput.ReadToEnd();
                // Splits the output into seperate strings for further processing
                string[] tempSplit = netOutput.Split(new string[] { "  ", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                // Roundabout way of trimming each string in the array
                string[] netOutputSplit = new string[tempSplit.Length];
                for (int i = 0; i < tempSplit.Length; i++)
                    netOutputSplit[i] = tempSplit[i].Trim();
                stringArray[0] = netOutputSplit[20];
                stringArray[1] = netOutputSplit[4];
                netProcess.WaitForExit();
                netProcess.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
            return stringArray;
        }
        public static bool QueryUserSharedFolderExist(string username)
        {
            return Directory.Exists(Settings_Form.sharedFolderLocation + @"\" + username);
        }
        public static void CreateShareFolder(string username)
        {
            
            try
            {
                // Creates the directory with only the specific NTFS and share permissions for the user.
                DirectorySecurity dSecurity = new DirectorySecurity();
                foreach (string systemUser in Settings_Form.systemAccounts)
                {
                    dSecurity.AddAccessRule(new FileSystemAccessRule("\\" + systemUser, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
                    dSecurity.AddAccessRule(new FileSystemAccessRule("\\" + systemUser, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                }
                //dSecurity.AddAccessRule(new FileSystemAccessRule("\\Administrator", FileSystemRights.FullControl, AccessControlType.Allow));
                //dSecurity.AddAccessRule(new FileSystemAccessRule("\\SWAT", FileSystemRights.FullControl, AccessControlType.Allow));
                //dSecurity.AddAccessRule(new FileSystemAccessRule("\\Administrators", FileSystemRights.FullControl, AccessControlType.Allow));
                dSecurity.AddAccessRule(new FileSystemAccessRule("\\" + username, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
                dSecurity.AddAccessRule(new FileSystemAccessRule("\\" + username, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
                Directory.CreateDirectory(Settings_Form.sharedFolderLocation + @"\" + username, dSecurity);
                SetSharePermissions(username);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }
        public static void DeleteShareFolder(string username)
        {
            try
            {
                // Removes the share BEFORE deleting the folder. Otherwise share will error on remove.
                RemoveSharePermissions(username);
                Directory.Delete(Settings_Form.sharedFolderLocation + @"\" + username, true);
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }
        public static void ToggleShare(string username)
        {
            try
            {
                if (Directory.Exists(Settings_Form.sharedFolderLocation + @"\" + username))
                {
                    DialogResult result = MessageBox.Show("A shared folder exists for the user " + username + "!" +
                                "\nDelete the folder and all data within the folder?",
                               "Warning!", MessageBoxButtons.YesNo);
                    if (result == DialogResult.Yes)
                    {
                        DeleteShareFolder(username);
                    }
                }
                else
                {
                    CreateShareFolder(username);
                }
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }
        public static void ChangeUserPassword(string username, string password)
        {
            try
            {
                Process netProcess = new Process();
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
                netProcess.StartInfo.FileName = "net.exe";
                netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                netProcess.StartInfo.CreateNoWindow = true;
                // Arguments for changing user password. Run NET HELP USER from the command prompt for more info.
                netProcess.StartInfo.Arguments = "USER \"" + username + "\" \"" + password + "\"";
                netProcess.Start();
                netProcess.WaitForExit();
                netProcess.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }
        public static bool SessionsOpen()
        {
            bool sessionsOpen = true;
            try
            {
                Process netProcess = new Process();
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
                netProcess.StartInfo.FileName = "net.exe";
                netProcess.StartInfo.UseShellExecute = false;
                netProcess.StartInfo.RedirectStandardOutput = true;
                netProcess.StartInfo.CreateNoWindow = true;
                netProcess.StartInfo.Arguments = "SESSION";
                netProcess.Start();
                string netOutput = netProcess.StandardOutput.ReadToEnd();
                // Splits the output into seperate strings for further processing
                string[] tempSplit = netOutput.Split(new string[] { "  ", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
                netProcess.WaitForExit();
                netProcess.Close();

                if (tempSplit[0] == "There are no entries in the list.")
                    sessionsOpen = false;
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
            return sessionsOpen;
        }
        private static void SetSharePermissions(string username)
        {
            string combinationString = "";
            foreach (string systemUser in Settings_Form.systemAccounts)
            {
                combinationString = combinationString.Insert(combinationString.Length, " /GRANT:\"" + systemUser + "\",FULL");
            }
            combinationString = combinationString.Insert(combinationString.Length, " /GRANT:\"" + username + "\",FULL");
            try
            {
                Process netProcess = new Process();
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
                netProcess.StartInfo.FileName = "net.exe";
                netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                netProcess.StartInfo.CreateNoWindow = true;
                netProcess.StartInfo.Arguments = "SHARE \"" + username + "\"=\"" + Settings_Form.sharedFolderLocation + "\\" + username + "\" " + combinationString;
                netProcess.Start();
                netProcess.WaitForExit();
                netProcess.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }
        private static void RemoveSharePermissions(string username)
        {
            try
            {
                Process netProcess = new Process();
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
                netProcess.StartInfo.FileName = "net.exe";
                netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
                netProcess.StartInfo.CreateNoWindow = true;
                netProcess.StartInfo.Arguments = "SHARE \"" + username + "\" /Delete";
                netProcess.Start();
                netProcess.WaitForExit();
                netProcess.Close();
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString(), "Error");
            }
        }
        private static bool IsStringBlank(string s)
        {
            if (s == "")
                return true;
            else
                return false;
        }
    }
}