Subversion Repositories Code-Repo

Rev

Details | Last modification | View Log | RSS feed

Rev Author Line No. Line
9 Kevin 1
using System;
2
using System.Collections.Generic;
3
using System.Linq;
4
using System.Text;
5
using System.Diagnostics;
6
using System.IO;
7
using System.Windows.Forms;
8
using System.Security.AccessControl;
9
 
10
namespace SWAT_Office_App
11
{
12
    class ManageUserAccounts
13
    {
14
        public static List<string> UserAccountsList = new List<string>();
15
        public static bool AddUser(string username, string password)
16
        {
17
            try
18
            {
19
                // Returns true if user was added successfully
20
                foreach (string user in UserAccountsList)
21
                {
22
                    if (username.ToLower() == user.ToLower())
23
                    {
24
                        MessageBox.Show("Username already exists", "Error");
25
                        return false;
26
                    }
27
                }
28
                Process netProcess = new Process();
29
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
30
                netProcess.StartInfo.FileName = "net.exe";
31
                netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
32
                netProcess.StartInfo.CreateNoWindow = true;
33
                // Arguments for user account creation. Run NET HELP USER from the command prompt for more info.
34
                netProcess.StartInfo.Arguments = "USER \"" + username + "\" \"" + password + 
35
                    "\" /ADD /ACTIVE:YES /PASSWORDCHG:NO /PASSWORDREQ:YES /EXPIRES:NEVER /COMMENT:" + DateTime.Now.ToShortDateString();
36
                netProcess.Start();
37
                netProcess.WaitForExit();
38
                netProcess.Close();
39
                return true;
40
            }
41
            catch (Exception e)
42
            {
43
                MessageBox.Show(e.ToString(), "Error");
44
                return false;
45
            }
46
        }
47
        public static void DeleteUser(List<string> usernames)
48
        {
49
            try
50
            {
51
                foreach (string user in usernames)
52
                {
53
                    if (Directory.Exists(Settings_Form.sharedFolderLocation + @"\" + user))
54
                    {
55
                        // Prompts for deletion of folder as well as the user account
56
                        DialogResult result = MessageBox.Show("A shared folder exists for the user " + user + "!" +
57
                            "\nDelete the folder and all data within the folder?",
58
                           "Warning!", MessageBoxButtons.YesNo);
59
                        if (result == DialogResult.Yes)
60
                        {
61
                            Process netProcess = new Process();
62
                            netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
63
                            netProcess.StartInfo.FileName = "net.exe";
64
                            netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
65
                            netProcess.StartInfo.CreateNoWindow = true;
66
                            // Arguments for user account deletion. Run NET HELP USER from the command prompt for more info.
67
                            netProcess.StartInfo.Arguments = "USER \"" + user + "\" /DELETE";
68
                            netProcess.Start();
69
                            netProcess.WaitForExit();
70
                            netProcess.Close();
71
 
72
                            DeleteShareFolder(user);
73
                        }
74
                    }
75
                    // If no folders exist for the user, account is deleted without prompting
76
                    else
77
                    {
78
                        Process netProcess = new Process();
79
                        netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
80
                        netProcess.StartInfo.FileName = "net.exe";
81
                        netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
82
                        netProcess.StartInfo.CreateNoWindow = true;
83
                        // Arguments for user account deletion. Run NET HELP USER from the command prompt for more info.
84
                        netProcess.StartInfo.Arguments = "USER \"" + user + "\" /DELETE";
85
                        netProcess.Start();
86
                        netProcess.WaitForExit();
87
                        netProcess.Close();
88
                    }
89
 
90
                }
91
            }
92
            catch (Exception e)
93
            {
94
                MessageBox.Show(e.ToString(), "Error");
95
            }
96
        }
97
        public static void QueryUserAccounts()
98
        {
99
            // Function that reads the user accounts on the local computer to UserAccountsList
100
            UserAccountsList.Clear();
101
            try
102
            {
103
                Process netProcess = new Process();
104
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
105
                netProcess.StartInfo.FileName = "net.exe";
106
                netProcess.StartInfo.UseShellExecute = false;
107
                netProcess.StartInfo.RedirectStandardOutput = true;
108
                netProcess.StartInfo.CreateNoWindow = true;
109
                netProcess.StartInfo.Arguments = "USER";
110
                netProcess.Start();
111
                string netOutput = netProcess.StandardOutput.ReadToEnd();
112
                // Splits the output into seperate strings for further processing
113
                string[] tempSplit = netOutput.Split(new string[] { "  ", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
114
                // Roundabout way of trimming each string in the array
115
                string[] netOutputSplit = new string[tempSplit.Length];
116
                for (int i = 0; i < tempSplit.Length; i++)
117
                    netOutputSplit[i] = tempSplit[i].Trim();
118
                // Imports the string array into the UserAccountsList List
119
                UserAccountsList.AddRange(netOutputSplit);
120
                // Removes the header and footer from the List
121
                UserAccountsList.RemoveRange(0, 2);
122
                UserAccountsList.RemoveRange(UserAccountsList.Count() - 1, 1);
123
                // Removes any additional empty entries
124
                UserAccountsList.RemoveAll(IsStringBlank);
125
                netProcess.WaitForExit();
126
                netProcess.Close();
127
            }
128
            catch (Exception e)
129
            {
130
                MessageBox.Show(e.ToString(), "Error");
131
            }
132
        }
133
        public static string [] QueryUserAccountExtraInformation(string username)
134
        {
135
            // Returns a string array with password requirement and date of account creation
136
            string[] stringArray = { "", "" };
137
            try
138
            {
139
                Process netProcess = new Process();
140
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
141
                netProcess.StartInfo.FileName = "net.exe";
142
                netProcess.StartInfo.UseShellExecute = false;
143
                netProcess.StartInfo.RedirectStandardOutput = true;
144
                netProcess.StartInfo.CreateNoWindow = true;
145
                netProcess.StartInfo.Arguments = "USER " + "\"" + username + "\"";
146
                netProcess.Start();
147
                string netOutput = netProcess.StandardOutput.ReadToEnd();
148
                // Splits the output into seperate strings for further processing
149
                string[] tempSplit = netOutput.Split(new string[] { "  ", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
150
                // Roundabout way of trimming each string in the array
151
                string[] netOutputSplit = new string[tempSplit.Length];
152
                for (int i = 0; i < tempSplit.Length; i++)
153
                    netOutputSplit[i] = tempSplit[i].Trim();
154
                stringArray[0] = netOutputSplit[20];
155
                stringArray[1] = netOutputSplit[4];
156
                netProcess.WaitForExit();
157
                netProcess.Close();
158
            }
159
            catch (Exception e)
160
            {
161
                MessageBox.Show(e.ToString(), "Error");
162
            }
163
            return stringArray;
164
        }
165
        public static bool QueryUserSharedFolderExist(string username)
166
        {
167
            return Directory.Exists(Settings_Form.sharedFolderLocation + @"\" + username);
168
        }
169
        public static void CreateShareFolder(string username)
170
        {
171
 
172
            try
173
            {
174
                // Creates the directory with only the specific NTFS and share permissions for the user.
175
                DirectorySecurity dSecurity = new DirectorySecurity();
176
                foreach (string systemUser in Settings_Form.systemAccounts)
177
                {
178
                    dSecurity.AddAccessRule(new FileSystemAccessRule("\\" + systemUser, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
179
                    dSecurity.AddAccessRule(new FileSystemAccessRule("\\" + systemUser, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
180
                }
181
                //dSecurity.AddAccessRule(new FileSystemAccessRule("\\Administrator", FileSystemRights.FullControl, AccessControlType.Allow));
182
                //dSecurity.AddAccessRule(new FileSystemAccessRule("\\SWAT", FileSystemRights.FullControl, AccessControlType.Allow));
183
                //dSecurity.AddAccessRule(new FileSystemAccessRule("\\Administrators", FileSystemRights.FullControl, AccessControlType.Allow));
184
                dSecurity.AddAccessRule(new FileSystemAccessRule("\\" + username, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
185
                dSecurity.AddAccessRule(new FileSystemAccessRule("\\" + username, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
186
                Directory.CreateDirectory(Settings_Form.sharedFolderLocation + @"\" + username, dSecurity);
187
                SetSharePermissions(username);
188
            }
189
            catch (Exception e)
190
            {
191
                MessageBox.Show(e.ToString(), "Error");
192
            }
193
        }
194
        public static void DeleteShareFolder(string username)
195
        {
196
            try
197
            {
198
                // Removes the share BEFORE deleting the folder. Otherwise share will error on remove.
199
                RemoveSharePermissions(username);
200
                Directory.Delete(Settings_Form.sharedFolderLocation + @"\" + username, true);
201
            }
202
            catch (Exception e)
203
            {
204
                MessageBox.Show(e.ToString(), "Error");
205
            }
206
        }
207
        public static void ToggleShare(string username)
208
        {
209
            try
210
            {
211
                if (Directory.Exists(Settings_Form.sharedFolderLocation + @"\" + username))
212
                {
213
                    DialogResult result = MessageBox.Show("A shared folder exists for the user " + username + "!" +
214
                                "\nDelete the folder and all data within the folder?",
215
                               "Warning!", MessageBoxButtons.YesNo);
216
                    if (result == DialogResult.Yes)
217
                    {
218
                        DeleteShareFolder(username);
219
                    }
220
                }
221
                else
222
                {
223
                    CreateShareFolder(username);
224
                }
225
            }
226
            catch (Exception e)
227
            {
228
                MessageBox.Show(e.ToString(), "Error");
229
            }
230
        }
231
        public static void ChangeUserPassword(string username, string password)
232
        {
233
            try
234
            {
235
                Process netProcess = new Process();
236
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
237
                netProcess.StartInfo.FileName = "net.exe";
238
                netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
239
                netProcess.StartInfo.CreateNoWindow = true;
240
                // Arguments for changing user password. Run NET HELP USER from the command prompt for more info.
241
                netProcess.StartInfo.Arguments = "USER \"" + username + "\" \"" + password + "\"";
242
                netProcess.Start();
243
                netProcess.WaitForExit();
244
                netProcess.Close();
245
            }
246
            catch (Exception e)
247
            {
248
                MessageBox.Show(e.ToString(), "Error");
249
            }
250
        }
251
        public static bool SessionsOpen()
252
        {
253
            bool sessionsOpen = true;
254
            try
255
            {
256
                Process netProcess = new Process();
257
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
258
                netProcess.StartInfo.FileName = "net.exe";
259
                netProcess.StartInfo.UseShellExecute = false;
260
                netProcess.StartInfo.RedirectStandardOutput = true;
261
                netProcess.StartInfo.CreateNoWindow = true;
262
                netProcess.StartInfo.Arguments = "SESSION";
263
                netProcess.Start();
264
                string netOutput = netProcess.StandardOutput.ReadToEnd();
265
                // Splits the output into seperate strings for further processing
266
                string[] tempSplit = netOutput.Split(new string[] { "  ", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
267
                netProcess.WaitForExit();
268
                netProcess.Close();
269
 
270
                if (tempSplit[0] == "There are no entries in the list.")
271
                    sessionsOpen = false;
272
            }
273
            catch (Exception e)
274
            {
275
                MessageBox.Show(e.ToString(), "Error");
276
            }
277
            return sessionsOpen;
278
        }
279
        private static void SetSharePermissions(string username)
280
        {
281
            string combinationString = "";
282
            foreach (string systemUser in Settings_Form.systemAccounts)
283
            {
284
                combinationString = combinationString.Insert(combinationString.Length, " /GRANT:\"" + systemUser + "\",FULL");
285
            }
286
            combinationString = combinationString.Insert(combinationString.Length, " /GRANT:\"" + username + "\",FULL");
287
            try
288
            {
289
                Process netProcess = new Process();
290
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
291
                netProcess.StartInfo.FileName = "net.exe";
292
                netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
293
                netProcess.StartInfo.CreateNoWindow = true;
294
                netProcess.StartInfo.Arguments = "SHARE \"" + username + "\"=\"" + Settings_Form.sharedFolderLocation + "\\" + username + "\" " + combinationString;
295
                netProcess.Start();
296
                netProcess.WaitForExit();
297
                netProcess.Close();
298
            }
299
            catch (Exception e)
300
            {
301
                MessageBox.Show(e.ToString(), "Error");
302
            }
303
        }
304
        private static void RemoveSharePermissions(string username)
305
        {
306
            try
307
            {
308
                Process netProcess = new Process();
309
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
310
                netProcess.StartInfo.FileName = "net.exe";
311
                netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
312
                netProcess.StartInfo.CreateNoWindow = true;
313
                netProcess.StartInfo.Arguments = "SHARE \"" + username + "\" /Delete";
314
                netProcess.Start();
315
                netProcess.WaitForExit();
316
                netProcess.Close();
317
            }
318
            catch (Exception e)
319
            {
320
                MessageBox.Show(e.ToString(), "Error");
321
            }
322
        }
323
        private static bool IsStringBlank(string s)
324
        {
325
            if (s == "")
326
                return true;
327
            else
328
                return false;
329
        }
330
    }
331
}