Ejemplo n.º 1
0
        public void Init_Upgrade()
        {
            string testDir = Path.Combine(Environment.GetEnvironmentVariable("TEMP"), Guid.NewGuid().ToString());

            Directory.CreateDirectory(testDir);

            MockRepository mocks = new MockRepository();
            IHostV30       host  = mocks.DynamicMock <IHostV30>();

            Expect.Call(host.GetSettingValue(SettingName.PublicDirectory)).Return(testDir).Repeat.AtLeastOnce();
            Expect.Call(host.GetSettingValue(SettingName.AdministratorsGroup)).Return("Administrators").Repeat.Once();
            Expect.Call(host.GetSettingValue(SettingName.UsersGroup)).Return("Users").Repeat.Once();

            Expect.Call(host.UpgradeSecurityFlagsToGroupsAcl(null, null)).IgnoreArguments().Repeat.Times(1).Return(true);

            mocks.Replay(host);

            string file = Path.Combine(host.GetSettingValue(SettingName.PublicDirectory), "Users.cs");

            File.WriteAllText(file, "user|PASSHASH|[email protected]|Inactive|2008/10/31 15:15:15|USER\r\nsuperuser|SUPERPASSHASH|[email protected]|Active|2008/10/31 15:15:16|ADMIN");

            UsersStorageProvider prov = new UsersStorageProvider();

            prov.Init(host, "");

            UserInfo[] users = prov.GetUsers();

            Assert.AreEqual(2, users.Length, "Wrong user count");

            Assert.AreEqual("superuser", users[0].Username, "Wrong username");
            Assert.AreEqual("*****@*****.**", users[0].Email, "Wrong email");
            Assert.IsTrue(users[0].Active, "User should be active");
            Assert.AreEqual("2008/10/31 15:15:16", users[0].DateTime.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss"), "Wrong date/time");
            Assert.AreEqual(1, users[0].Groups.Length, "Wrong user count");
            Assert.AreEqual("Administrators", users[0].Groups[0], "Wrong group");

            Assert.AreEqual("user", users[1].Username, "Wrong username");
            Assert.AreEqual("*****@*****.**", users[1].Email, "Wrong email");
            Assert.IsFalse(users[1].Active, "User should be inactive");
            Assert.AreEqual("2008/10/31 15:15:15", users[1].DateTime.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss"), "Wrong date/time");
            Assert.AreEqual(1, users[1].Groups.Length, "Wrong user count");
            Assert.AreEqual("Users", users[1].Groups[0], "Wrong group");

            mocks.Verify(host);

            Directory.Delete(testDir, true);
        }
Ejemplo n.º 2
0
        /// <summary>
        /// Verifies the need for a data upgrade, and performs it when needed.
        /// </summary>
        private void VerifyAndPerformUpgrade()
        {
            // Load file lines
            // Parse first line (if any) with old (v2) algorithm
            // If parsing is successful, then the file must be converted
            // Conversion consists in removing the 'ADMIN|USER' field, creating the proper default groups and setting user membership

            // Structure v2:
            // Username|PasswordHash|Email|Active-Inactive|DateTime|Admin-User

            //string[] lines = File.ReadAllLines(GetFullPath(UsersFile));
            // Use this method because version 2.0 file might have started with a blank line
            string[] lines = File.ReadAllText(GetFullPath(UsersFile)).Replace("\r", "").Split(new char[] { '\n' }, StringSplitOptions.RemoveEmptyEntries);

            if (lines.Length > 0)
            {
                bool            upgradeIsNeeded = false;
                LocalUserInfo[] users           = new LocalUserInfo[lines.Length];
                bool[]          oldStyleAdmin   = new bool[lines.Length];      // Values are valid only if upgradeIsNeeded=true

                char[] splitter = new char[] { '|' };

                for (int i = 0; i < lines.Length; i++)
                {
                    string line = lines[i];

                    string[] fields = line.Split(splitter, StringSplitOptions.RemoveEmptyEntries);

                    string displayName = null;

                    if (fields.Length == 6)
                    {
                        if (fields[5] == "ADMIN" || fields[5] == "USER")
                        {
                            // Version 2.0
                            upgradeIsNeeded  = true;
                            oldStyleAdmin[i] = fields[5] == "ADMIN";
                        }
                        else
                        {
                            // Version 3.0 with DisplayName specified
                            oldStyleAdmin[i] = false;
                            displayName      = fields[5];
                        }
                    }
                    else
                    {
                        // Can be a version 3.0 file, with empty DisplayName
                        oldStyleAdmin[i] = false;
                    }

                    users[i] = new LocalUserInfo(fields[0], displayName, fields[2],
                                                 fields[3].ToLowerInvariant() == "active", DateTime.Parse(fields[4]), this, fields[1]);
                }

                if (upgradeIsNeeded)
                {
                    // Dump users
                    // Create default groups
                    // Set membership for old users
                    // Tell the host to set the permissions for the default groups

                    string backupFile = GetFullPath(Path.GetFileNameWithoutExtension(UsersFile) + "_v2" + Path.GetExtension(UsersFile));
                    File.Copy(GetFullPath(UsersFile), backupFile);

                    host.LogEntry("Upgrading users format from 2.0 to 3.0", LogEntryType.General, null, this);

                    DumpUsers(users);
                    UserGroup adminsGroup = AddUserGroup(host.GetSettingValue(SettingName.AdministratorsGroup), "Built-in Administrators");
                    UserGroup usersGroup  = AddUserGroup(host.GetSettingValue(SettingName.UsersGroup), "Built-in Users");

                    for (int i = 0; i < users.Length; i++)
                    {
                        if (oldStyleAdmin[i])
                        {
                            SetUserMembership(users[i], new string[] { adminsGroup.Name });
                        }
                        else
                        {
                            SetUserMembership(users[i], new string[] { usersGroup.Name });
                        }
                    }

                    host.UpgradeSecurityFlagsToGroupsAcl(adminsGroup, usersGroup);
                }
            }
        }
        public void Init_Upgrade( )
        {
            FixtureTearDown( );

            SqlConnection cn = new SqlConnection(ConnString);

            cn.Open( );

            SqlCommand cmd = cn.CreateCommand( );

            cmd.CommandText = "create database [ScrewTurnWikiTest];";
            cmd.ExecuteNonQuery( );
            cn.Close( );

            cn = new SqlConnection(ConnString + InitialCatalog);
            cn.Open( );

            cmd             = cn.CreateCommand( );
            cmd.CommandText =
                @"CREATE TABLE [UsersProviderVersion] (
	[Version] varchar(12) PRIMARY KEY
);
INSERT INTO [UsersProviderVersion] ([Version]) VALUES ('Irrelevant');

CREATE TABLE [User] (
	[Username] nvarchar(128) PRIMARY KEY,
	[PasswordHash] varchar(128) NOT NULL,
	[Email] varchar(128) NOT NULL,
	[DateTime] datetime NOT NULL,
	[Active] bit NOT NULL DEFAULT ((0)),
	[Admin] bit NOT NULL DEFAULT ((0))
);

INSERT INTO [User] ([Username], [PasswordHash], [Email], [DateTime], [Active], [Admin]) values ('user', 'hash', '*****@*****.**', '2008/12/27 12:12:12', 'true', 'false');
INSERT INTO [User] ([Username], [PasswordHash], [Email], [DateTime], [Active], [Admin]) values ('user2', 'hash2', '*****@*****.**', '2008/12/27 12:12:13', 'false', 'true');";

            bool done = false;

            try
            {
                cmd.ExecuteNonQuery( );
                done = true;
            }
            catch (SqlException sqlex)
            {
                Console.WriteLine(sqlex.ToString( ));
            }
            finally
            {
                cn.Close( );
            }

            if (!done)
            {
                throw new Exception("Could not create v2 test database");
            }

            MockRepository mocks = new MockRepository( );
            IHostV30       host  = mocks.DynamicMock <IHostV30>( );

            Expect.Call(host.GetSettingValue(SettingName.AdministratorsGroup)).Return("Administrators").Repeat.Once( );
            Expect.Call(host.GetSettingValue(SettingName.UsersGroup)).Return("Users").Repeat.Once( );

            Expect.Call(host.UpgradeSecurityFlagsToGroupsAcl(null, null)).IgnoreArguments( ).Repeat.Times(1).Return(true);

            mocks.Replay(host);

            IUsersStorageProviderV30 prov = new SqlServerUsersStorageProvider( );

            prov.Init(host, ConnString + InitialCatalog);

            mocks.Verify(host);

            UserInfo[] users = prov.GetUsers( );

            Assert.AreEqual(2, users.Length, "Wrong user count");

            Assert.AreEqual("user", users[0].Username, "Wrong username");
            Assert.IsNull(users[0].DisplayName, "Display name should be null");
            Assert.AreEqual("*****@*****.**", users[0].Email, "Wrong email");
            Assert.AreEqual("2008/12/27 12:12:12", users[0].DateTime.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss"), "Wrong date/time");
            Assert.IsTrue(users[0].Active, "User should be active");
            Assert.AreEqual(1, users[0].Groups.Length, "Wrong group count");
            Assert.AreEqual("Users", users[0].Groups[0], "Wrong group");

            Assert.AreEqual("user2", users[1].Username, "Wrong username");
            Assert.IsNull(users[1].DisplayName, "Display name should be null");
            Assert.AreEqual("*****@*****.**", users[1].Email, "Wrong email");
            Assert.AreEqual("2008/12/27 12:12:13", users[1].DateTime.ToString("yyyy'/'MM'/'dd' 'HH':'mm':'ss"), "Wrong date/time");
            Assert.IsFalse(users[1].Active, "User should be inactive");
            Assert.AreEqual(1, users[1].Groups.Length, "Wrong group count");
            Assert.AreEqual("Administrators", users[1].Groups[0], "Wrong group");
        }