public async void ChangeUsername()
        {
            // Create user, then lookup by Id
            var originalUser = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(originalUser);
            CassandraUser foundUser = await UserManager.FindByIdAsync(originalUser.Id);
            
            // Change the username and update
            const string newUserName = "******";
            foundUser.UserName = newUserName;
            IdentityResult result = await UserManager.UpdateAsync(foundUser);
            result.ShouldBeSuccess();

            // Should not be able to find them by the old username
            foundUser = await UserManager.FindByNameAsync(originalUser.UserName);
            foundUser.Should().BeNull();

            // Should still be able to find by id and new username
            foundUser = await UserManager.FindByIdAsync(originalUser.Id);
            foundUser.Should().NotBeNull();
            foundUser.UserName.Should().Be(newUserName);

            foundUser = await UserManager.FindByNameAsync(newUserName);
            foundUser.Should().NotBeNull();
            foundUser.Id.Should().Be(originalUser.Id);
        }
Exemple #2
0
        /// <summary>
        /// Creates a CassandraUser from a Row.  If the Row is null, returns null.
        /// </summary>
        static CassandraUser ToCassandraUser(this Row row)
        {
            if (row == null)
            {
                return(null);
            }

            var user = new CassandraUser(row.GetValue <Guid>("userid"), row.GetValue <Guid>("tenantid"), row.GetValue <string>("username"), row.GetValue <string>("email"))
            {
                PasswordHash         = row.GetValue <string>("password_hash"),
                SecurityStamp        = row.GetValue <string>("security_stamp"),
                TwoFactorEnabled     = row.GetValue <bool>("two_factor_enabled"),
                AccessFailedCount    = row.GetValue <int>("access_failed_count"),
                LockoutEnabled       = row.GetValue <bool>("lockout_enabled"),
                LockoutEndDate       = row.GetValue <DateTimeOffset>("lockout_end_date"),
                PhoneNumber          = row.GetValue <string>("phone_number"),
                PhoneNumberConfirmed = row.GetValue <bool>("phone_number_confirmed"),
                EmailConfirmed       = row.GetValue <bool>("email_confirmed"),
                Created  = row.GetValue <DateTimeOffset>("created"),
                Modified = row.IsNull("modified") ? new DateTimeOffset?() : row.GetValue <DateTimeOffset>("modified"),
                Enabled  = row.GetValue <bool>("enabled"),
                Source   = row.GetValue <string>("source"),
                SourceId = row.GetValue <string>("source_id")
            };

            return(user);
        }
        public async Task Test_Add_User_Find_by_email_Delete_User_Async()
        {
            var dao = Global.TenantDao;
            await dao.EstablishConnectionAsync();

            List <CassandraUser> insertedUsers = new List <CassandraUser>();
            int nCount = 1;

            for (int i = 0; i < nCount; ++i)
            {
                string userName = Guid.NewGuid().ToString();
                var    user     = new CassandraUser()
                {
                    Email                = userName,
                    UserName             = userName,
                    AccessFailedCount    = 123,
                    EmailConfirmed       = true,
                    Enabled              = true,
                    LockoutEnabled       = true,
                    PasswordHash         = Guid.NewGuid().ToString(),
                    PhoneNumber          = Guid.NewGuid().ToString(),
                    PhoneNumberConfirmed = true,
                    SecurityStamp        = Guid.NewGuid().ToString(),
                    Source               = Guid.NewGuid().ToString(),
                    SourceId             = Guid.NewGuid().ToString(),
                    TwoFactorEnabled     = true
                };
                insertedUsers.Add(user);
                await dao.UpsertUserAsync(user);
            }

            foreach (var testUser in insertedUsers)
            {
                testUser.TenantId = dao.TenantId;
                var foundUserResult = await dao.FindUserByEmailAsync(testUser.Email);

                Assert.IsNotNull(foundUserResult);
                var foundUserList = foundUserResult.ToList();
                Assert.IsTrue(foundUserList.Any());
                Assert.AreEqual(foundUserList.Count, 1);
                var foundUser = foundUserList[0];
                Assert.IsTrue(CassandraUserComparer.ShallowComparer.Equals(foundUser, testUser));
            }

            foreach (var testUser in insertedUsers)
            {
                await dao.DeleteUserAsync(testUser);

                var foundUserResult = await dao.FindUserByEmailAsync(testUser.Email);

                Assert.IsNotNull(foundUserResult);
                var foundUserList = foundUserResult.ToList();
                Assert.IsFalse(foundUserList.Any());
                Assert.AreEqual(foundUserList.Count, 0);
            }
        }
        public async void Authenticate()
        {
            // Create a user with a password
            var user = new CassandraUser(Guid.NewGuid()) {UserName = "******"};
            await UserManager.CreateAsync(user, "somePassword");

            // Should be able to authenticate user with password
            bool authenticated = await UserManager.CheckPasswordAsync(user, "somePassword");
            authenticated.Should().BeTrue();
        }
Exemple #5
0
        public async Task Test_add_user_modify_lockout_end_date_delete()
        {
            var dao = Global.TenantDao;
            await dao.EstablishConnectionAsync();

            var guidId    = Guid.NewGuid();
            var userStore = new CassandraUserStore();

            string userName = Guid.NewGuid().ToString();
            var    user     = new CassandraUser()
            {
                Email                = userName,
                UserName             = userName,
                EmailConfirmed       = false,
                PhoneNumberConfirmed = false,
                PhoneNumber          = "310.383.1111",
                LockoutEnabled       = false,
                PasswordHash         = "1234",
                SecurityStamp        = "1234",
                LockoutEndDate       = DateTimeOffset.UtcNow
            };
            await userStore.CreateAsync(user);

            var foundUser = await userStore.FindByEmailAsync(userName);

            Assert.IsNotNull(foundUser);
            var lockOutDate = await userStore.GetLockoutEndDateAsync(foundUser);

            Assert.AreEqual(lockOutDate.Day, user.LockoutEndDate.Day);
            Assert.AreEqual(lockOutDate.Hour, user.LockoutEndDate.Hour);
            Assert.AreEqual(lockOutDate.Minute, user.LockoutEndDate.Minute);
            Assert.AreEqual(lockOutDate.Year, user.LockoutEndDate.Year);

            var future = user.LockoutEndDate.AddDays(5);
            await userStore.SetLockoutEndDateAsync(foundUser, future);

            await userStore.UpdateAsync(foundUser);

            foundUser = await userStore.FindByEmailAsync(userName);

            Assert.IsNotNull(foundUser);
            lockOutDate = await userStore.GetLockoutEndDateAsync(foundUser);

            Assert.AreEqual(lockOutDate.Day, future.Day);
            Assert.AreEqual(lockOutDate.Hour, future.Hour);
            Assert.AreEqual(lockOutDate.Minute, future.Minute);
            Assert.AreEqual(lockOutDate.Year, future.Year);

            await userStore.DeleteAsync(foundUser);

            foundUser = await userStore.FindByEmailAsync(userName);

            Assert.IsNull(foundUser);
        }
        public async void FindByLogin()
        {
            // Create a user and add a login to the user
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(user);

            var login = new UserLoginInfo("facebook", Guid.NewGuid().ToString());
            await UserManager.AddLoginAsync(user.Id, login);

            // Now we should be able to find the user by that login info
            CassandraUser foundUser = await UserManager.FindAsync(login);
            foundUser.ShouldBeEquivalentToUser(user);
        }
Exemple #7
0
            public static void Menu(string e, MongoUser m, NeoUser n, CassandraUser c)
            {
                Console.WriteLine("Do you want to:\n 1 Find new friend \n " +
                                  "2-Write a post\n" +
                                  "3-Look over s-bodies post\n" +
                                  "4-Go out");
                var x = Console.ReadLine();

                switch (x)
                {
                case "1":
                    Console.WriteLine("Write FirstName of searched person ");
                    string FN = Console.ReadLine();
                    Console.WriteLine("Write LastName");
                    string LN = Console.ReadLine();
                    if (n.Relationship == true)
                    {
                        Console.WriteLine("There is relationship");
                    }
                    else
                    {
                        Console.WriteLine("There is not relationship");
                    }
                    Console.WriteLine("The lenght is", n.PathBetweenID(e, LN));
                    m.ToFollow(FN, LN, e);
                    n.Follow(e, LN);
                    Menu(e, m, n, c);

                    break;

                case "2":
                    ISession session;
                    c.NewPost(session);
                    break;

                case "3":
                    Console.WriteLine("Write FirstName of searched person ");
                    N = Console.ReadLine();
                    Console.WriteLine("Write LastName");
                    S = Console.ReadLine();
                    m.PostReaction(N, S, e);
                    Menu(e, m, n);
                    break;

                case "4":
                    Console.WriteLine("Bye:(");
                    Thread.Sleep(1000);
                    System.Environment.Exit(20);
                    break;
                }
            }
        static void Main(string[] args)
        {
            CassandraUser cu = new CassandraUser();

            Console.WriteLine("Hello,sweety,enter your email,please!");
            var em = Console.ReadLine();

            cu.Login(em);

            cu.ReadAllPosts();
            Menu(em, cu);

            Console.ReadKey();
        }
        public async void CreateUser()
        {
            // Create user
            var originalUser = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            IdentityResult result = await UserManager.CreateAsync(originalUser);
            result.ShouldBeSuccess();

            // Try to find users by id and username
            CassandraUser foundUser = await UserManager.FindByIdAsync(originalUser.Id);
            foundUser.ShouldBeEquivalentToUser(originalUser);

            foundUser = await UserManager.FindByNameAsync(originalUser.UserName);
            foundUser.ShouldBeEquivalentToUser(originalUser);
        }
        public async void GetSetLockoutEndDate()
        {
            // Create a user and enable lockout
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(user);
            await UserManager.SetLockoutEnabledAsync(user.Id, true);

            // Should be able to set lockout end date
            DateTimeOffset lockoutDate = DateTimeOffset.UtcNow;
            IdentityResult result = await UserManager.SetLockoutEndDateAsync(user.Id, lockoutDate);
            result.ShouldBeSuccess();

            // Should be able to retrieve that lockout date
            DateTimeOffset lookupDate = await UserManager.GetLockoutEndDateAsync(user.Id);
            lookupDate.Should().BeCloseTo(lockoutDate);     // Use CloseTo because C* is not accurate down to the ticks level
        }
        public async Task DeleteUserAsync(CassandraUser user,
                                          CancellationToken cancellationToken = default(CancellationToken))
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (string.IsNullOrEmpty(user.UserName))
            {
                throw new ArgumentNullException("user", "user.UserName cannot be null or empty");
            }

            var foundUserResult = await FindUserByUserNameAsync(user.UserName, cancellationToken);

            var foundUserlist = foundUserResult.ToList();

            if (!foundUserlist.Any())
            {
                return;
            }
            user = foundUserlist[0];


            var batch = new BatchStatement();

            PreparedStatement prepared = await _deleteUserById;
            BoundStatement    bound    = prepared.Bind(user.Id);

            batch.Add(bound);

            prepared = await _deleteUserByEmail;
            bound    = prepared.Bind(user.Email);
            batch.Add(bound);

            prepared = await _deleteUserByUserName;
            bound    = prepared.Bind(user.UserName);
            batch.Add(bound);


            await RemoveLoginsFromUserAsync(user.Id, cancellationToken);
            await DeleteUserFromRolesAsync(user.Id, cancellationToken);
            await DeleteClaimHandleByUserIdAsync(user.Id, cancellationToken);

            await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false);
        }
        public async Task Test_Add_User_Find_by_userid_Delete_User_Async()
        {
            var dao = Global.TenantDao;
            await dao.EstablishConnectionAsync();

            List <CassandraUser> insertedUsers = new List <CassandraUser>();
            int nCount = 1;

            for (int i = 0; i < nCount; ++i)
            {
                string userName = Guid.NewGuid().ToString();
                var    user     = new CassandraUser()
                {
                    Email    = userName,
                    UserName = userName
                };
                insertedUsers.Add(user);
                await dao.UpsertUserAsync(user);
            }

            foreach (var testUser in insertedUsers)
            {
                testUser.TenantId = dao.TenantId;
                var foundUserResult = await dao.FindUserByIdAsync(testUser.Id);

                Assert.IsNotNull(foundUserResult);
                var foundUserList = foundUserResult.ToList();
                Assert.IsTrue(foundUserList.Any());
                Assert.AreEqual(foundUserList.Count, 1);
                var foundUser = foundUserList[0];
                Assert.IsTrue(CassandraUserComparer.ShallowComparer.Equals(foundUser, testUser));
            }

            foreach (var testUser in insertedUsers)
            {
                await dao.DeleteUserAsync(testUser);

                var foundUserResult = await dao.FindUserByEmailAsync(testUser.Email);

                Assert.IsNotNull(foundUserResult);
                var foundUserList = foundUserResult.ToList();
                Assert.IsFalse(foundUserList.Any());
                Assert.AreEqual(foundUserList.Count, 0);
            }
        }
        public async void HasPassword()
        {
            // Create a user
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(user);

            // Verify they are created without a password
            bool hasPassword = await UserManager.HasPasswordAsync(user.Id);
            hasPassword.Should().BeFalse();

            // Create a user with a password
            user = new CassandraUser(Guid.NewGuid()) {UserName = "******"};
            await UserManager.CreateAsync(user, "somePassword");

            // Verify they have a password
            hasPassword = await UserManager.HasPasswordAsync(user.Id);
            hasPassword.Should().BeTrue();
        }
        public async void GetSetLockoutEnabled()
        {
            // Create a user
            var user = new CassandraUser(Guid.NewGuid()) {UserName = "******"};
            await UserManager.CreateAsync(user);

            // Lockout should not be enabled by default
            bool isLockoutEnabled = await UserManager.GetLockoutEnabledAsync(user.Id);
            isLockoutEnabled.Should().BeFalse();

            // Should be able to turn on lockout for a user
            IdentityResult result = await UserManager.SetLockoutEnabledAsync(user.Id, true);
            result.ShouldBeSuccess();

            // Should now be enabled
            isLockoutEnabled = await UserManager.GetLockoutEnabledAsync(user.Id);
            isLockoutEnabled.Should().BeTrue();
        }
        public async void DeleteUser()
        {
            // Create user, then lookup by Id
            var originalUser = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(originalUser);
            CassandraUser foundUser = await UserManager.FindByIdAsync(originalUser.Id);
            
            // Delete the user
            IdentityResult result = await UserManager.DeleteAsync(foundUser);
            result.ShouldBeSuccess();

            // Should not be able to find by id or username
            foundUser = await UserManager.FindByIdAsync(originalUser.Id);
            foundUser.Should().BeNull();

            foundUser = await UserManager.FindByNameAsync(originalUser.UserName);
            foundUser.Should().BeNull();
        }
        public async void EnableDisableTwoFactor()
        {
            // Create a user
            var user = new CassandraUser(Guid.NewGuid()) {UserName = "******"};
            await UserManager.CreateAsync(user);

            // 2FA should be disabled by default
            bool isEnabled = await UserManager.GetTwoFactorEnabledAsync(user.Id);
            isEnabled.Should().BeFalse();

            // Can set 2FA enabled
            IdentityResult result = await UserManager.SetTwoFactorEnabledAsync(user.Id, true);
            result.ShouldBeSuccess();

            // Should be enabled now
            isEnabled = await UserManager.GetTwoFactorEnabledAsync(user.Id);
            isEnabled.Should().BeTrue();
        }
        public async void AddRemovePassword()
        {
            // Create user without password
            var user = new CassandraUser(Guid.NewGuid()) {UserName = "******"};
            await UserManager.CreateAsync(user);

            // Adding a password should succeed
            IdentityResult result = await UserManager.AddPasswordAsync(user.Id, "somePassword");
            result.ShouldBeSuccess();
            bool hasPassword = await UserManager.HasPasswordAsync(user.Id);
            hasPassword.Should().BeTrue();

            // Now removing a password should succeed
            result = await UserManager.RemovePasswordAsync(user.Id);
            result.ShouldBeSuccess();
            hasPassword = await UserManager.HasPasswordAsync(user.Id);
            hasPassword.Should().BeFalse();
        }
        public async void LockUserOut()
        {
            // Create a user and enable lockout
            var user = new CassandraUser(Guid.NewGuid()) {UserName = "******"};
            await UserManager.CreateAsync(user);
            await UserManager.SetLockoutEnabledAsync(user.Id, true);

            // Should be able to record a failed login
            IdentityResult result = await UserManager.AccessFailedAsync(user.Id);
            result.ShouldBeSuccess();

            // Since the test setup uses one as the threshold for lockouts, the user should now be locked out
            bool isLockedOut = await UserManager.IsLockedOutAsync(user.Id);
            isLockedOut.Should().BeTrue();

            // Since the test setup set the lockout period to 15 mins, the lockout end date should be approximately 15 mins from now
            DateTimeOffset lockoutEndDate = await UserManager.GetLockoutEndDateAsync(user.Id);
            lockoutEndDate.Should().BeCloseTo(DateTimeOffset.UtcNow.Add(15.Minutes()), precision: 1000);    // 1000 == Within 1 second
        }
        public async void GetAndSetEmail()
        {
            // Create a user
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(user);
            
            // User should not have an email address initially
            string userEmail = await UserManager.GetEmailAsync(user.Id);
            userEmail.Should().BeNullOrEmpty();

            // Set email address for user
            const string email = "*****@*****.**";
            IdentityResult result = await UserManager.SetEmailAsync(user.Id, email);
            result.ShouldBeSuccess();

            // Now user should have email
            userEmail = await UserManager.GetEmailAsync(user.Id);
            userEmail.Should().Be(email);
        }
        public async void GetSetPhoneNumber()
        {
            // Create a user
            var user = new CassandraUser(Guid.NewGuid()) {UserName = "******"};
            await UserManager.CreateAsync(user);

            // Should not have phone number by default
            string phoneNumber = await UserManager.GetPhoneNumberAsync(user.Id);
            phoneNumber.Should().BeNullOrEmpty();

            // Can set phone number
            const string phone = "555-555-1212";
            IdentityResult result = await UserManager.SetPhoneNumberAsync(user.Id, phone);
            result.ShouldBeSuccess();

            // Should now have phone number
            phoneNumber = await UserManager.GetPhoneNumberAsync(user.Id);
            phoneNumber.Should().Be(phone);
        }
Exemple #21
0
        public async Task Test_add_user_modify_twofactor_enabled_delete()
        {
            var dao = Global.TenantDao;
            await dao.EstablishConnectionAsync();

            var guidId    = Guid.NewGuid();
            var userStore = new CassandraUserStore();

            string userName = Guid.NewGuid().ToString();
            var    user     = new CassandraUser()
            {
                Email                = userName,
                UserName             = userName,
                EmailConfirmed       = false,
                PhoneNumberConfirmed = false,
                PhoneNumber          = "310.383.1111",
                LockoutEnabled       = false,
                PasswordHash         = "1234",
                SecurityStamp        = "1234",
                TwoFactorEnabled     = false
            };
            await userStore.CreateAsync(user);

            var foundUser = await userStore.FindByEmailAsync(userName);

            Assert.IsNotNull(foundUser);
            Assert.IsFalse(await userStore.GetTwoFactorEnabledAsync(foundUser));

            await userStore.SetTwoFactorEnabledAsync(foundUser, true);

            await userStore.UpdateAsync(foundUser);

            foundUser = await userStore.FindByEmailAsync(userName);

            Assert.IsNotNull(foundUser);
            Assert.IsTrue(await userStore.GetTwoFactorEnabledAsync(foundUser));

            await userStore.DeleteAsync(foundUser);

            foundUser = await userStore.FindByEmailAsync(userName);

            Assert.IsNull(foundUser);
        }
        public async void ChangePassword()
        {
            // Create a user with a password
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(user, "somePassword");

            // Should be able to change the password
            IdentityResult result = await UserManager.ChangePasswordAsync(user.Id, "somePassword", "someNewPassword");
            result.ShouldBeSuccess();

            // Should be able to authenticate with new password
            user = await UserManager.FindByIdAsync(user.Id);
            bool authenticated = await UserManager.CheckPasswordAsync(user, "someNewPassword");
            authenticated.Should().BeTrue();

            // Should not be able to authenticate with old password
            authenticated = await UserManager.CheckPasswordAsync(user, "somePassword");
            authenticated.Should().BeFalse();
        }
        public async void FindByEmail()
        {
            // Create a user and set their email address
            const string email = "*****@*****.**";
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(user);
            await UserManager.SetEmailAsync(user.Id, email);
            
            // User should be able to be looked up by email
            CassandraUser foundUser = await UserManager.FindByEmailAsync(email);
            foundUser.ShouldBeEquivalentToUser(user);

            // Delete the user
            await UserManager.DeleteAsync(foundUser);

            // User should no longer be able to be found by email
            foundUser = await UserManager.FindByEmailAsync(email);
            foundUser.Should().BeNull();
        }
        public static void Menu(string e, CassandraUser cu)
        {
            Console.WriteLine("Do you want to:\n 1-Find new friend \n " +
                              "2-Write a post\n" +
                              "3-Look over s-bodies post\n" +
                              "4-Go out");
            var x = Console.ReadLine();

            switch (x)
            {
            case "1":
                Console.WriteLine("Write name of searched person ");
                string N = Console.ReadLine();
                Console.WriteLine("Write surname now");
                string S = Console.ReadLine();

                cu.ToFollow(N, S, e);
                Menu(e, cu);

                break;

            case "3":
                Console.WriteLine("Write name of searched person ");
                N = Console.ReadLine();
                Console.WriteLine("Write surname now");
                S = Console.ReadLine();
                cu.PostReaction(N, S, e);
                Menu(e, cu);
                break;

            case "2":
                var post = cu.CreatePost(e);
                Menu(e, cu);
                break;

            case "4":
                Console.WriteLine("Bye:(");
                Thread.Sleep(1000);
                System.Environment.Exit(20);
                break;
            }
        }
        public async Task<ActionResult> Register(RegisterViewModel model)
        {
            if (ModelState.IsValid)
            {
                var user = new CassandraUser { UserName = model.UserName, Id = CassandraUser.GenerateKey(model.UserName)};
                var result = await UserManager.CreateAsync(user, model.Password);
                if (result.Succeeded)
                {
                    await SignInAsync(user, isPersistent: false);
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    AddErrors(result);
                }
            }

            // If we got this far, something failed, redisplay form
            return View(model);
        }
Exemple #26
0
        public async Task Test_add_user_modify_password_hash_delete()
        {
            var dao = Global.TenantDao;
            await dao.EstablishConnectionAsync();

            var guidId    = Guid.NewGuid();
            var userStore = new CassandraUserStore();

            string userName = Guid.NewGuid().ToString();
            var    user     = new CassandraUser()
            {
                Email                = userName,
                UserName             = userName,
                EmailConfirmed       = false,
                PhoneNumberConfirmed = false,
                PhoneNumber          = "310.383.1111",
                LockoutEnabled       = false,
                PasswordHash         = "1234"
            };
            await userStore.CreateAsync(user);

            var foundUser = await userStore.FindByEmailAsync(userName);

            Assert.IsNotNull(foundUser);
            Assert.AreEqual(await userStore.GetPasswordHashAsync(foundUser), "1234");

            await userStore.SetPasswordHashAsync(foundUser, "abcd");

            await userStore.UpdateAsync(foundUser);

            foundUser = await userStore.FindByEmailAsync(userName);

            Assert.IsNotNull(foundUser);
            Assert.AreEqual(await userStore.GetPasswordHashAsync(foundUser), "abcd");

            await userStore.DeleteAsync(foundUser);

            foundUser = await userStore.FindByEmailAsync(userName);

            Assert.IsNull(foundUser);
        }
        public async void PhoneNumberConfirmation()
        {
            // Create a user with a phone number
            const string phone = "555-555-1212";
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(user);
            await UserManager.SetPhoneNumberAsync(user.Id, phone);

            // Should not be confirmed by default
            bool isConfirmed = await UserManager.IsPhoneNumberConfirmedAsync(user.Id);
            isConfirmed.Should().BeFalse();

            // Generate a token to verify the phone number
            string token = await UserManager.GenerateChangePhoneNumberTokenAsync(user.Id, phone);
            IdentityResult result = await UserManager.ChangePhoneNumberAsync(user.Id, phone, token);
            result.ShouldBeSuccess();

            // Phone number should now be confirmed
            isConfirmed = await UserManager.IsPhoneNumberConfirmedAsync(user.Id);
            isConfirmed.Should().BeTrue();
        }
        public async void ChangeEmail()
        {
            // Create a user and set their email address
            const string email = "*****@*****.**";
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(user);
            await UserManager.SetEmailAsync(user.Id, email);

            // Change their email address
            const string newEmail = "*****@*****.**";
            IdentityResult result = await UserManager.SetEmailAsync(user.Id, newEmail);
            result.ShouldBeSuccess();

            // Should not be able to find the user by the old email address
            CassandraUser foundUser = await UserManager.FindByEmailAsync(email);
            foundUser.Should().BeNull();

            // Should be able to find the user by the new email address
            foundUser = await UserManager.FindByEmailAsync(newEmail);
            foundUser.ShouldBeEquivalentToUser(user);
        }
Exemple #29
0
        public async Task Test_add_user_modify_phone_confirmed_delete()
        {
            var dao = Global.TenantDao;
            await dao.EstablishConnectionAsync();

            var guidId    = Guid.NewGuid();
            var userStore = new CassandraUserStore();

            string userName = Guid.NewGuid().ToString();
            var    user     = new CassandraUser()
            {
                Email                = userName,
                UserName             = userName,
                EmailConfirmed       = false,
                PhoneNumberConfirmed = false
            };
            await userStore.CreateAsync(user);

            var foundUser = await userStore.FindByEmailAsync(userName);

            Assert.IsNotNull(foundUser);
            Assert.IsFalse(await userStore.GetPhoneNumberConfirmedAsync(foundUser));

            await userStore.SetPhoneNumberConfirmedAsync(foundUser, true);

            await userStore.UpdateAsync(foundUser);

            foundUser = await userStore.FindByEmailAsync(userName);

            Assert.IsNotNull(foundUser);
            Assert.IsTrue(await userStore.GetPhoneNumberConfirmedAsync(foundUser));

            await userStore.DeleteAsync(foundUser);

            foundUser = await userStore.FindByEmailAsync(userName);

            Assert.IsNull(foundUser);
        }
        public async void AddRemoveLogins()
        {
            // Create a user
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(user);

            // Should not have any logins intially
            IList<UserLoginInfo> logins = await UserManager.GetLoginsAsync(user.Id);
            logins.Should().BeEmpty();

            // Add some logins for the user and make sure we can retrieve them
            var loginsToAdd = new[]
            {
                new UserLoginInfo("facebook", Guid.NewGuid().ToString()),
                new UserLoginInfo("google", Guid.NewGuid().ToString())
            };

            IdentityResult result;
            foreach (UserLoginInfo login in loginsToAdd)
            {
                result = await UserManager.AddLoginAsync(user.Id, login);
                result.ShouldBeSuccess();
            }

            logins = await UserManager.GetLoginsAsync(user.Id);
            logins.Should().NotBeEmpty()
                  .And.HaveCount(loginsToAdd.Length);
            logins.ShouldAllBeEquivalentTo(loginsToAdd);

            // Now remove one of the logins from the user
            result = await UserManager.RemoveLoginAsync(user.Id, loginsToAdd[0]);
            result.ShouldBeSuccess();

            logins = await UserManager.GetLoginsAsync(user.Id);
            logins.Should().NotBeEmpty()
                  .And.HaveCount(loginsToAdd.Length - 1);
            logins.ShouldAllBeEquivalentTo(loginsToAdd.Where((_, idx) => idx != 0));
        }
        public async void AddRemoveClaims()
        {
            // Create a user
            var user = new CassandraUser(Guid.NewGuid()) {UserName = "******"};
            await UserManager.CreateAsync(user);

            // User should not have any claims initially
            IList<Claim> claims = await UserManager.GetClaimsAsync(user.Id);
            claims.Should().BeEmpty();

            // Should be able to add claims to user and retrieve them
            var claimsToAdd = new[]
            {
                new Claim("hometown", "Cincinnati, OH"),
                new Claim("dob", "4/16/1983")
            };

            IdentityResult result;
            foreach (Claim claim in claimsToAdd)
            {
                result = await UserManager.AddClaimAsync(user.Id, claim);
                result.ShouldBeSuccess();
            }

            claims = await UserManager.GetClaimsAsync(user.Id);
            claims.Should().NotBeEmpty()
                  .And.HaveCount(claimsToAdd.Length);
            claims.ShouldAllBeEquivalentTo(claimsToAdd);
            
            // Should be able to remove a claim and get the correct claims back
            result = await UserManager.RemoveClaimAsync(user.Id, claimsToAdd[0]);
            result.ShouldBeSuccess();

            claims = await UserManager.GetClaimsAsync(user.Id);
            claims.Should().NotBeEmpty()
                .And.HaveCount(claimsToAdd.Length - 1);
            claims.ShouldAllBeEquivalentTo(claimsToAdd.Where((_, idx) => idx != 0));
        }
        public async Task UpsertUserAsync(CassandraUser user,
                                          CancellationToken cancellationToken = default(CancellationToken))
        {
            if (user == null)
            {
                throw new ArgumentNullException("user");
            }
            if (string.IsNullOrEmpty(user.UserName))
            {
                throw new ArgumentNullException("user", "user.UserName cannot be null or empty");
            }

            var now = DateTimeOffset.UtcNow;

            var foundUserResult = await FindUserByEmailAsync(user.Email, cancellationToken);

            var foundUserList = foundUserResult.ToList();

            if (foundUserList.Any())
            {
                // we have an update, and not a create.
                // we don't let you update the username/email.  That is done by ChangeUserNameAsync
                var foundUser = foundUserList[0];
                user.Email    = foundUser.Email;
                user.UserName = foundUser.UserName;
            }
            else
            {
                // We have a brand new user,
                // we want to make the Id and user record immutable.
                // This allows us to change out the email address, which is the only thing we will allow for what looks like a username.
                user.Id      = Guid.NewGuid();
                user.Created = now;
            }

            user.Modified = now;

            var batch = new BatchStatement();

            var prepared = await _createUserByUserName;
            var bound    = prepared.Bind(user.UserName, user.Id, user.PasswordHash, user.SecurityStamp,
                                         user.TwoFactorEnabled, user.AccessFailedCount,
                                         user.LockoutEnabled, user.LockoutEndDate, user.PhoneNumber, user.PhoneNumberConfirmed,
                                         user.Email,
                                         user.EmailConfirmed, user.Created, user.Modified, user.Enabled, user.Source, user.SourceId);

            batch.Add(bound);

            prepared = await _createUserByEmail;
            bound    = prepared.Bind(user.UserName, user.Id, user.PasswordHash, user.SecurityStamp,
                                     user.TwoFactorEnabled, user.AccessFailedCount,
                                     user.LockoutEnabled, user.LockoutEndDate, user.PhoneNumber, user.PhoneNumberConfirmed,
                                     user.Email,
                                     user.EmailConfirmed, user.Created, user.Modified, user.Enabled, user.Source, user.SourceId);
            batch.Add(bound);

            prepared = await _createUserById;
            bound    = prepared.Bind(user.UserName, user.Id, user.PasswordHash, user.SecurityStamp,
                                     user.TwoFactorEnabled, user.AccessFailedCount,
                                     user.LockoutEnabled, user.LockoutEndDate, user.PhoneNumber, user.PhoneNumberConfirmed,
                                     user.Email,
                                     user.EmailConfirmed, user.Created, user.Modified, user.Enabled, user.Source, user.SourceId);
            batch.Add(bound);


            cancellationToken.ThrowIfCancellationRequested();

            await CassandraSession.ExecuteAsync(batch).ConfigureAwait(false);
        }
        public async void EmailConfirmation()
        {
            // Create a user and set their email address
            const string email = "*****@*****.**";
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(user);
            await UserManager.SetEmailAsync(user.Id, email);

            // Email should NOT be confirmed by default
            bool confirmed = await UserManager.IsEmailConfirmedAsync(user.Id);
            confirmed.Should().BeFalse();

            // Generate a token and confirm the email
            string token = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
            IdentityResult result = await UserManager.ConfirmEmailAsync(user.Id, token);
            result.ShouldBeSuccess();

            // Email should now be confirmed
            confirmed = await UserManager.IsEmailConfirmedAsync(user.Id);
            confirmed.Should().BeTrue();
        }
        public async void ResetPassword()
        {
            // Create a user with a password
            var user = new CassandraUser(Guid.NewGuid()) { UserName = "******" };
            await UserManager.CreateAsync(user, "somePassword");

            // Generate a reset token and then reset the password should succeed
            string token = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
            IdentityResult result = await UserManager.ResetPasswordAsync(user.Id, token, "someNewPassword");
            result.ShouldBeSuccess();

            // Should now be able to authenticate with new password
            user = await UserManager.FindByIdAsync(user.Id);
            bool authenticated = await UserManager.CheckPasswordAsync(user, "someNewPassword");
            authenticated.Should().BeTrue();

            // Should not be able to authenticate with old password
            authenticated = await UserManager.CheckPasswordAsync(user, "somePassword");
            authenticated.Should().BeFalse();
        }
        public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
        {
            if (User.Identity.IsAuthenticated)
            {
                return RedirectToAction("Manage");
            }

            if (ModelState.IsValid)
            {
                // Get the information about the user from the external login provider
                var info = await AuthenticationManager.GetExternalLoginInfoAsync();
                if (info == null)
                {
                    return View("ExternalLoginFailure");
                }
                var user = new CassandraUser { UserName = model.UserName, Id = CassandraUser.GenerateKey(model.UserName)};
                var result = await UserManager.CreateAsync(user);
                if (result.Succeeded)
                {
                    result = await UserManager.AddLoginAsync(user.Id, info.Login);
                    if (result.Succeeded)
                    {
                        await SignInAsync(user, isPersistent: false);
                        return RedirectToLocal(returnUrl);
                    }
                }
                AddErrors(result);
            }

            ViewBag.ReturnUrl = returnUrl;
            return View(model);
        }
 private async Task SignInAsync(CassandraUser user, bool isPersistent)
 {
     AuthenticationManager.SignOut(DefaultAuthenticationTypes.ExternalCookie);
     var identity = await UserManager.CreateIdentityAsync(user, DefaultAuthenticationTypes.ApplicationCookie);
     AuthenticationManager.SignIn(new AuthenticationProperties() { IsPersistent = isPersistent }, identity);
 }
 /// <summary>
 /// Asserts that the user should have the same Id and UserName as the other user.
 /// </summary>
 public static void ShouldBeEquivalentToUser(this CassandraUser user, CassandraUser otherUser)
 {
     user.ShouldBeEquivalentTo(otherUser, opt => opt.Including(u => u.Id).Including(u => u.UserName));
 }
Exemple #38
0
        public async Task <ActionResult> ExternalLoginCallback(string returnUrl)
        {
            var confirmEmailViewModel = Session[WellKnown.ConfirmEmailViewModelClaim] as ConfirmEmailViewModel;

            Session[WellKnown.ConfirmEmailViewModelClaim] = null;

            var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();

            if (loginInfo == null)
            {
                return(RedirectToAction("Login"));
            }
            CassandraUser user = await UserManager.FindAsync(loginInfo.Login);

            // Try an auto association.  If this login provider provides and email, than try a match
            if (user == null && !string.IsNullOrEmpty(loginInfo.Email))
            {
                user = await UserManager.FindByEmailAsync(loginInfo.Email);

                if (user != null)
                {
                    // got a match. lets auto associate
                    await UserManager.AddLoginAsync(user.Id, loginInfo.Login);
                }
            }

            if (user != null && !user.EmailConfirmed)
            {
                if (confirmEmailViewModel != null &&
                    string.Compare(user.Email, confirmEmailViewModel.Email, StringComparison.OrdinalIgnoreCase) == 0)
                {
                    user.EmailConfirmed = true;
                    await UserManager.UpdateAsync(user);
                }
                else
                {
                    return
                        (await
                         SendEmailConfirmationCode(new ConfirmEmailViewModel()
                    {
                        ConfirmEmailPurpose = ConfirmEmailPurpose.ConfirmEmailPurpose_CreateExternalAccount, Email = user.Email, UserId = user.Id.ToString()
                    }));
                }
            }

            // PreVerified Email Address Create/Association
            if (user == null && confirmEmailViewModel != null)
            {
                user = new ApplicationUser
                {
                    UserName       = confirmEmailViewModel.Email,
                    Email          = confirmEmailViewModel.Email,
                    EmailConfirmed = true
                };
                var resultCreate = await UserManager.CreateAsync(user);

                if (resultCreate.Succeeded)
                {
                    resultCreate = await UserManager.AddLoginAsync(user.Id, loginInfo.Login);
                }
                Session[WellKnown.ConfirmEmailViewModelClaim] = null;
            }

            // Sign in the user with this external login provider if the user already has a login
            var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent : false);


            switch (result)
            {
            case SignInStatus.Success:
                return(RedirectToLocal(returnUrl));

            case SignInStatus.LockedOut:
                return(View("Lockout"));

            case SignInStatus.RequiresVerification:
                return(RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }));

            case SignInStatus.Failure:
            default:

                // If the user does not have an account, then prompt the user to create an account
                ViewBag.ReturnUrl        = returnUrl;
                ViewBag.LoginProvider    = loginInfo.Login.LoginProvider;
                Session["UserLoginInfo"] = loginInfo.Login;
                return(View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel {
                    Email = loginInfo.Email
                }));
            }
        }
        public async Task Test_add_many_users_page_delete()
        {
            var dao = Global.TenantDao;
            await dao.EstablishConnectionAsync();

            var guidId        = Guid.NewGuid();
            var insertedUsers = new List <CassandraUser>();

            var role = new CassandraRole()
            {
                Name     = Guid.NewGuid().ToString(),
                IsGlobal = false,
            };


            var roleStore = Global.TanantCassandraRoleStore;
            var userStore = Global.TanantCassandraUserStore;

            await roleStore.CreateAsync(role);

            int nCount = 100;

            for (int i = 0; i < nCount; ++i)
            {
                string userName = Guid.NewGuid().ToString();
                var    user     = new CassandraUser()
                {
                    Email    = userName,
                    UserName = userName
                };
                insertedUsers.Add(user);
                await userStore.CreateAsync(user);

                var providerLoginHandle = new ProviderLoginHandle()
                {
                    LoginProvider = Guid.NewGuid().ToString(),
                    ProviderKey   = Guid.NewGuid().ToString(),
                    UserId        = user.Id
                };
                await
                userStore.AddLoginAsync(user,
                                        new UserLoginInfo(providerLoginHandle.LoginProvider, providerLoginHandle.ProviderKey));


                var claimHandle = new ClaimHandle()
                {
                    Type   = "Type:" + guidId,
                    UserId = user.Id,
                    Value  = "Value:" + guidId
                };
                await userStore.AddClaimAsync(user, new Claim(claimHandle.Type, claimHandle.Value));

                await userStore.AddToRoleAsync(user, role.Name);
            }

            byte[] pageState = null;
            int    pageSize  = 9;
            var    result    = await userStore.PageUsersAsync(pageSize, pageState);

            pageState = result.PagingState;
            int nCounter = result.Count;

            while (pageState != null)
            {
                result = await userStore.PageUsersAsync(pageSize, pageState);

                pageState = result.PagingState;
                nCounter += result.Count;
            }
            Assert.AreEqual(nCounter, nCount);


            foreach (var testUser in insertedUsers)
            {
                await dao.DeleteUserAsync(testUser);

                var foundUserResult = await dao.FindUserByEmailAsync(testUser.Email);

                Assert.IsNotNull(foundUserResult);
                var foundUserList = foundUserResult.ToList();
                Assert.IsFalse(foundUserList.Any());
                Assert.AreEqual(foundUserList.Count, 0);

                var roleResult = await dao.FindRoleNamesByUserIdAsync(testUser.Id);

                Assert.IsNotNull(roleResult);
                var roleResultList = roleResult.ToList();
                Assert.IsFalse(roleResultList.Any());

                var claimResult = await dao.FindClaimHandleByUserIdAsync(testUser.Id);

                Assert.IsNotNull(claimResult);
                var claimResultList = claimResult.ToList();
                Assert.IsFalse(claimResultList.Any());
            }
            await roleStore.DeleteAsync(role);

            var findDeletedRole = await roleStore.FindByNameAsync(role.Name);

            Assert.IsNull(findDeletedRole);
        }
        public async Task Test_Add_Full_User_Find_by_email_Delete_User_Async()
        {
            var dao = Global.TenantDao;
            await dao.EstablishConnectionAsync();

            var guidId        = Guid.NewGuid();
            var insertedUsers = new List <CassandraUser>();

            var role = new CassandraRole()
            {
                Name     = Guid.NewGuid().ToString(),
                IsGlobal = false,
            };
            await dao.CreateRoleAsync(role);

            var roleNameResult = await dao.FindRoleByNameAsync(role.Name);

            Assert.IsNotNull(roleNameResult);
            var foundRoleNameResult = roleNameResult.ToList();

            Assert.IsTrue(foundRoleNameResult.Any());
            Assert.AreEqual(role.Name, foundRoleNameResult[0].Name);

            int nCount = 1;

            for (int i = 0; i < nCount; ++i)
            {
                string userName = Guid.NewGuid().ToString();
                var    user     = new CassandraUser()
                {
                    Email    = userName,
                    UserName = userName
                };
                insertedUsers.Add(user);
                await dao.UpsertUserAsync(user);


                var providerLoginHandle = new ProviderLoginHandle()
                {
                    LoginProvider = Guid.NewGuid().ToString(),
                    ProviderKey   = Guid.NewGuid().ToString(),
                    UserId        = user.Id
                };
                await dao.UpsertLoginsAsync(providerLoginHandle);

                var claimHandle = new ClaimHandle()
                {
                    Type   = "Type:" + guidId,
                    UserId = user.Id,
                    Value  = "Value:" + guidId
                };
                await dao.CreateClaimAsync(claimHandle);

                await dao.AddToRoleAsync(user.Id, role.Name);
            }


            foreach (var testUser in insertedUsers)
            {
                testUser.TenantId = dao.TenantId;
                var foundUserResult = await dao.FindUserByEmailAsync(testUser.Email);

                Assert.IsNotNull(foundUserResult);
                var foundUserList = foundUserResult.ToList();
                Assert.IsTrue(foundUserList.Any());
                Assert.AreEqual(foundUserList.Count, 1);
                var foundUser = foundUserList[0];
                Assert.IsTrue(CassandraUserComparer.ShallowComparer.Equals(foundUser, testUser));

                var roleResult = await dao.FindRoleNamesByUserIdAsync(testUser.Id);

                Assert.IsNotNull(roleResult);
                var roleResultList = roleResult.ToList();
                Assert.AreEqual(1, roleResultList.Count());
                var foundRole = roleResultList[0];
                Assert.AreEqual(foundRole, role.Name);

                var claimResult = await dao.FindClaimHandleByUserIdAsync(testUser.Id);

                Assert.IsNotNull(claimResult);
                var claimResultList = claimResult.ToList();
                Assert.AreEqual(1, claimResultList.Count());
                var foundClaim = claimResultList[0];

                var claimHandle = new ClaimHandle()
                {
                    Type   = "Type:" + guidId,
                    UserId = testUser.Id,
                    Value  = "Value:" + guidId
                };
                Assert.IsTrue(ClaimHandleComparer.Comparer.Equals(foundClaim, claimHandle));
            }

            foreach (var testUser in insertedUsers)
            {
                await dao.DeleteUserAsync(testUser);

                var foundUserResult = await dao.FindUserByEmailAsync(testUser.Email);

                Assert.IsNotNull(foundUserResult);
                var foundUserList = foundUserResult.ToList();
                Assert.IsFalse(foundUserList.Any());
                Assert.AreEqual(foundUserList.Count, 0);

                var roleResult = await dao.FindRoleNamesByUserIdAsync(testUser.Id);

                Assert.IsNotNull(roleResult);
                var roleResultList = roleResult.ToList();
                Assert.IsFalse(roleResultList.Any());

                var claimResult = await dao.FindClaimHandleByUserIdAsync(testUser.Id);

                Assert.IsNotNull(claimResult);
                var claimResultList = claimResult.ToList();
                Assert.IsFalse(claimResultList.Any());
            }
            await dao.DeleteRoleAsync(role);

            roleNameResult = await dao.FindRoleByNameAsync(role.Name);

            Assert.IsNotNull(roleNameResult);
            foundRoleNameResult = roleNameResult.ToList();
            Assert.IsFalse(foundRoleNameResult.Any());
        }
 public async Task UpdateUserAsync(CassandraUser user)
 {
     var fullUserStore = UserManager.FullUserStore;
     await fullUserStore.UpdateAsync(user);
 }