Subversion Repositories Code-Repo

Rev

Go to most recent revision | 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;
53 Kevin 9
using System.DirectoryServices.AccountManagement;
9 Kevin 10
 
11
namespace SWAT_Office_App
12
{
63 Kevin 13
    class Manage_User_Accounts
9 Kevin 14
    {
53 Kevin 15
        private static string studentGroupName = "StudentAccounts";
16
        public static List<UserPrincipal> UserAccountsList = new List<UserPrincipal>();
9 Kevin 17
        public static bool AddUser(string username, string password)
18
        {
19
            try
20
            {
53 Kevin 21
                PrincipalContext localSystem = new PrincipalContext(ContextType.Machine);
22
                // Creates a new user after checking if it already exists or not
23
                UserPrincipal newUser = new UserPrincipal(localSystem);
24
                newUser.Name = username;
25
                PrincipalSearcher searcher = new PrincipalSearcher(newUser);
26
                Principal result = searcher.FindOne();
27
                if (result == null)
9 Kevin 28
                {
53 Kevin 29
                    newUser = new UserPrincipal(localSystem);
30
                    newUser.Name = username;
31
                    newUser.SetPassword(password);
32
                    newUser.PasswordNeverExpires = true;
33
                    newUser.PasswordNotRequired = false;
34
                    newUser.UserCannotChangePassword = true;
35
                    newUser.Description = DateTime.Now.ToShortDateString();
36
                    newUser.Save();
37
 
38
                    // Creates a new group after checking if it already exists or not
39
                    GroupPrincipal studentGroup = new GroupPrincipal(localSystem);
40
                    studentGroup.Name = studentGroupName;
41
                    searcher = new PrincipalSearcher(studentGroup);
42
                    result = searcher.FindOne();
43
                    // Creates group if it doesnt already exist
44
                    if (result == null)
9 Kevin 45
                    {
53 Kevin 46
                        studentGroup = new GroupPrincipal(localSystem, studentGroupName);
47
                        studentGroup.Name = studentGroupName;
48
                        studentGroup.IsSecurityGroup = true;
49
                        studentGroup.Members.Add(newUser);
50
                        studentGroup.Save();
9 Kevin 51
                    }
53 Kevin 52
                    // Otherwise add to existing group
53
                    else
54
                    {
55
                        studentGroup = (GroupPrincipal)result;
56
                        studentGroup.Members.Add(newUser);
57
                        studentGroup.Save();
58
                    }
63 Kevin 59
                    Debug.appendText("Account " + username + " has been created");
60
                    Stat_Logging.AccountsCreated += 1;
53 Kevin 61
                    return true;
9 Kevin 62
                }
53 Kevin 63
                else
64
                {
65
                    // local account already exists, return with error
66
                    return false;
67
                }
9 Kevin 68
            }
69
            catch (Exception e)
70
            {
53 Kevin 71
                //MessageBox.Show(e.ToString(), "Error");
63 Kevin 72
                Debug.appendText(e.ToString());
53 Kevin 73
                MessageBox.Show("An error has occured. Please notify a supervisor to debug.", "Error");
9 Kevin 74
                return false;
75
            }
76
        }
53 Kevin 77
        public static bool DeleteUser(List<string> usernames)
9 Kevin 78
        {
79
            try
80
            {
53 Kevin 81
                bool Success = true;
82
                PrincipalContext localSystem = new PrincipalContext(ContextType.Machine);
83
                // Iterates through and deletes selected users
9 Kevin 84
                foreach (string user in usernames)
85
                {
53 Kevin 86
                    bool deleteShare = false;
9 Kevin 87
                    if (Directory.Exists(Settings_Form.sharedFolderLocation + @"\" + user))
88
                    {
89
                        // Prompts for deletion of folder as well as the user account
90
                        DialogResult result = MessageBox.Show("A shared folder exists for the user " + user + "!" +
91
                            "\nDelete the folder and all data within the folder?",
92
                           "Warning!", MessageBoxButtons.YesNo);
93
                        if (result == DialogResult.Yes)
53 Kevin 94
                            deleteShare = true;
9 Kevin 95
                    }
53 Kevin 96
                    // Finds and deletes user and share
97
                    UserPrincipal toDelete = new UserPrincipal(localSystem);
98
                    toDelete.Name = user;
99
                    PrincipalSearcher searcher = new PrincipalSearcher(toDelete);
100
                    Principal found = searcher.FindOne();
101
                    toDelete = (UserPrincipal)found;
102
                    toDelete.Delete();
63 Kevin 103
                    Debug.appendText("Account " + user + " has been deleted");
53 Kevin 104
                    // Deletes share if selected
105
                    if (deleteShare)
106
                        if (!DeleteShareFolder(user))
107
                            Success = false;
9 Kevin 108
                }
53 Kevin 109
                return Success;
9 Kevin 110
            }
111
            catch (Exception e)
112
            {
53 Kevin 113
                //MessageBox.Show(e.ToString(), "Error");
63 Kevin 114
                Debug.appendText(e.ToString());
53 Kevin 115
                MessageBox.Show("An error has occured. Please notify a supervisor to debug.", "Error");
116
                return false;
9 Kevin 117
            }
118
        }
53 Kevin 119
        public static bool QueryUserAccounts()
9 Kevin 120
        {
121
            // Function that reads the user accounts on the local computer to UserAccountsList
122
            UserAccountsList.Clear();
123
            try
124
            {
53 Kevin 125
                PrincipalContext localSystem = new PrincipalContext(ContextType.Machine);
126
                UserPrincipal user = new UserPrincipal(localSystem);
127
                user.Name = "*";
128
                PrincipalSearcher searcher = new PrincipalSearcher(user);
129
                PrincipalSearchResult<Principal> result = searcher.FindAll();
130
                foreach (Principal p in result)
131
                    UserAccountsList.Add((UserPrincipal)p);
132
                return true;
9 Kevin 133
            }
134
            catch (Exception e)
135
            {
53 Kevin 136
                //MessageBox.Show(e.ToString(), "Error");
63 Kevin 137
                Debug.appendText(e.ToString());
53 Kevin 138
                MessageBox.Show("An error has occured. Please notify a supervisor to debug.", "Error");
139
                return false;
9 Kevin 140
            }
141
        }
142
        public static bool QueryUserSharedFolderExist(string username)
143
        {
144
            return Directory.Exists(Settings_Form.sharedFolderLocation + @"\" + username);
145
        }
53 Kevin 146
        public static bool CreateShareFolder(string username)
9 Kevin 147
        {
148
 
149
            try
150
            {
151
                // Creates the directory with only the specific NTFS and share permissions for the user.
152
                DirectorySecurity dSecurity = new DirectorySecurity();
53 Kevin 153
                // Adds NTFS permissions for system accounts
9 Kevin 154
                foreach (string systemUser in Settings_Form.systemAccounts)
155
                {
156
                    dSecurity.AddAccessRule(new FileSystemAccessRule("\\" + systemUser, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
157
                    dSecurity.AddAccessRule(new FileSystemAccessRule("\\" + systemUser, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
158
                }
53 Kevin 159
                // Adds NTFS permissions for the user
9 Kevin 160
                dSecurity.AddAccessRule(new FileSystemAccessRule("\\" + username, FileSystemRights.FullControl, InheritanceFlags.ContainerInherit, PropagationFlags.None, AccessControlType.Allow));
161
                dSecurity.AddAccessRule(new FileSystemAccessRule("\\" + username, FileSystemRights.FullControl, InheritanceFlags.ObjectInherit, PropagationFlags.None, AccessControlType.Allow));
162
                Directory.CreateDirectory(Settings_Form.sharedFolderLocation + @"\" + username, dSecurity);
63 Kevin 163
                Debug.appendText("Shared folder for " + username + " has been created");
57 Kevin 164
                if (SetSharePermissions(username))
165
                {
63 Kevin 166
                    Stat_Logging.SharesCreated += 1;
57 Kevin 167
                    return true;
168
                }
169
                else
170
                    return false;
9 Kevin 171
            }
172
            catch (Exception e)
173
            {
53 Kevin 174
                //MessageBox.Show(e.ToString(), "Error");
63 Kevin 175
                Debug.appendText(e.ToString());
53 Kevin 176
                MessageBox.Show("An error has occured. Please notify a supervisor to debug.", "Error");
177
                return false;
9 Kevin 178
            }
179
        }
53 Kevin 180
        public static bool DeleteShareFolder(string username)
9 Kevin 181
        {
182
            try
183
            {
53 Kevin 184
                bool Success = true;
9 Kevin 185
                // Removes the share BEFORE deleting the folder. Otherwise share will error on remove.
53 Kevin 186
                if (!RemoveSharePermissions(username))
187
                    Success = false;
9 Kevin 188
                Directory.Delete(Settings_Form.sharedFolderLocation + @"\" + username, true);
63 Kevin 189
                Debug.appendText("Shared folder for " + username + " has been deleted");
53 Kevin 190
                return Success;
9 Kevin 191
            }
192
            catch (Exception e)
193
            {
53 Kevin 194
                //MessageBox.Show(e.ToString(), "Error");
63 Kevin 195
                Debug.appendText(e.ToString());
53 Kevin 196
                MessageBox.Show("An error has occured. Please notify a supervisor to debug.", "Error");
197
                return false;
9 Kevin 198
            }
199
        }
53 Kevin 200
        public static bool ToggleShare(string username)
9 Kevin 201
        {
202
            try
203
            {
53 Kevin 204
                // Checks if a share already exists for the user
9 Kevin 205
                if (Directory.Exists(Settings_Form.sharedFolderLocation + @"\" + username))
206
                {
207
                    DialogResult result = MessageBox.Show("A shared folder exists for the user " + username + "!" +
208
                                "\nDelete the folder and all data within the folder?",
209
                               "Warning!", MessageBoxButtons.YesNo);
210
                    if (result == DialogResult.Yes)
53 Kevin 211
                        return DeleteShareFolder(username);
9 Kevin 212
                }
53 Kevin 213
                // Otherwise creates the share for the user
9 Kevin 214
                else
53 Kevin 215
                    return CreateShareFolder(username);
216
                return true;
9 Kevin 217
            }
218
            catch (Exception e)
219
            {
53 Kevin 220
                //MessageBox.Show(e.ToString(), "Error");
63 Kevin 221
                Debug.appendText(e.ToString());
53 Kevin 222
                MessageBox.Show("An error has occured. Please notify a supervisor to debug.", "Error");
223
                return false;
9 Kevin 224
            }
225
        }
48 Kevin 226
        public static long GetShareSize(string username)
227
        {
228
            DirectoryInfo dir = new DirectoryInfo(Settings_Form.sharedFolderLocation + @"\" + username);
229
            long size = GetDirSize(dir);
230
            return size;
231
        }
53 Kevin 232
        private static long GetDirSize(DirectoryInfo input)
9 Kevin 233
        {
234
            try
235
            {
53 Kevin 236
                if (input.Exists)
237
                {
238
                    long size = 0;
239
                    FileInfo[] files = input.GetFiles();
240
                    foreach (FileInfo file in files)
241
                    {
242
                        size += file.Length;
243
                    }
244
                    DirectoryInfo[] dirs = input.GetDirectories();
245
                    foreach (DirectoryInfo dir in dirs)
246
                    {
247
                        size += GetDirSize(dir);
248
                    }
249
                    return size;
250
                }
251
                else 
252
                    return 0;
9 Kevin 253
            }
254
            catch (Exception e)
255
            {
53 Kevin 256
                //MessageBox.Show(e.ToString(), "Error");
63 Kevin 257
                Debug.appendText(e.ToString());
53 Kevin 258
                MessageBox.Show("An error has occured. Please notify a supervisor to debug.", "Error");
259
                return 0;
9 Kevin 260
            }
261
        }
53 Kevin 262
        public static bool ChangeUserPassword(string username, string password)
263
        {
264
            try
265
            {
266
                // Queries for the specified user password
267
                PrincipalContext localSystem = new PrincipalContext(ContextType.Machine);
268
                UserPrincipal user = new UserPrincipal(localSystem);
269
                user.Name = username;
270
                PrincipalSearcher searcher = new PrincipalSearcher(user);
271
                Principal result = searcher.FindOne();
272
                user = (UserPrincipal)result;
273
                user.SetPassword(password);
274
                user.Save();
63 Kevin 275
                Debug.appendText("Password for " + username + " has been changed");
53 Kevin 276
                return true;
277
            }
278
            catch (Exception e)
279
            {
280
                //MessageBox.Show(e.ToString(), "Error");
63 Kevin 281
                Debug.appendText(e.ToString());
53 Kevin 282
                MessageBox.Show("An error has occured. Please notify a supervisor to debug.", "Error");
283
                return false;
284
            }
285
        }
9 Kevin 286
        public static bool SessionsOpen()
287
        {
288
            try
289
            {
290
                Process netProcess = new Process();
291
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
292
                netProcess.StartInfo.FileName = "net.exe";
293
                netProcess.StartInfo.UseShellExecute = false;
294
                netProcess.StartInfo.RedirectStandardOutput = true;
295
                netProcess.StartInfo.CreateNoWindow = true;
296
                netProcess.StartInfo.Arguments = "SESSION";
297
                netProcess.Start();
298
                string netOutput = netProcess.StandardOutput.ReadToEnd();
299
                // Splits the output into seperate strings for further processing
300
                string[] tempSplit = netOutput.Split(new string[] { "  ", "\r", "\n" }, StringSplitOptions.RemoveEmptyEntries);
301
                netProcess.WaitForExit();
302
                netProcess.Close();
303
 
304
                if (tempSplit[0] == "There are no entries in the list.")
53 Kevin 305
                    return false;
50 Kevin 306
                else
53 Kevin 307
                    return true;
50 Kevin 308
            }
309
            catch (Exception e)
310
            {
53 Kevin 311
                //MessageBox.Show(e.ToString(), "Error");
63 Kevin 312
                Debug.appendText(e.ToString());
53 Kevin 313
                MessageBox.Show("An error has occured. Please notify a supervisor to debug.", "Error");
314
                return true;
50 Kevin 315
            }
316
        }
53 Kevin 317
        private static bool SetSharePermissions(string username)
9 Kevin 318
        {
319
            string combinationString = "";
320
            foreach (string systemUser in Settings_Form.systemAccounts)
321
            {
322
                combinationString = combinationString.Insert(combinationString.Length, " /GRANT:\"" + systemUser + "\",FULL");
323
            }
324
            combinationString = combinationString.Insert(combinationString.Length, " /GRANT:\"" + username + "\",FULL");
325
            try
326
            {
327
                Process netProcess = new Process();
328
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
329
                netProcess.StartInfo.FileName = "net.exe";
330
                netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
331
                netProcess.StartInfo.CreateNoWindow = true;
332
                netProcess.StartInfo.Arguments = "SHARE \"" + username + "\"=\"" + Settings_Form.sharedFolderLocation + "\\" + username + "\" " + combinationString;
333
                netProcess.Start();
334
                netProcess.WaitForExit();
335
                netProcess.Close();
63 Kevin 336
                Debug.appendText("Share permissions for " + username + " has been set");
53 Kevin 337
                return true;
9 Kevin 338
            }
339
            catch (Exception e)
340
            {
53 Kevin 341
                //MessageBox.Show(e.ToString(), "Error");
63 Kevin 342
                Debug.appendText(e.ToString());
53 Kevin 343
                MessageBox.Show("An error has occured. Please notify a supervisor to debug.", "Error");
344
                return false;
9 Kevin 345
            }
346
        }
53 Kevin 347
        private static bool RemoveSharePermissions(string username)
9 Kevin 348
        {
349
            try
350
            {
351
                Process netProcess = new Process();
352
                netProcess.StartInfo.WorkingDirectory = System.Environment.SystemDirectory;
353
                netProcess.StartInfo.FileName = "net.exe";
354
                netProcess.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
355
                netProcess.StartInfo.CreateNoWindow = true;
356
                netProcess.StartInfo.Arguments = "SHARE \"" + username + "\" /Delete";
357
                netProcess.Start();
358
                netProcess.WaitForExit();
359
                netProcess.Close();
63 Kevin 360
                Debug.appendText("Share permissions for " + username + " has been removed");
53 Kevin 361
                return true;
9 Kevin 362
            }
363
            catch (Exception e)
364
            {
53 Kevin 365
                //MessageBox.Show(e.ToString(), "Error");
63 Kevin 366
                Debug.appendText(e.ToString());
53 Kevin 367
                MessageBox.Show("An error has occured. Please notify a supervisor to debug.", "Error");
368
                return false;
9 Kevin 369
            }
370
        }
371
    }
372
}