public static bool CheckUser(MembershipAccount user, IQueryable<MembershipRole> roles, IQueryable<MembershipPermission> permissionsQuery, string[] currentPermissions)
        {
            List<MembershipPermission> allPermissions = permissionsQuery.ToList();
            List<string> permissions = new List<string>();

            if (user == null)
            {
                var role = roles.FirstOrDefault(x => x.RoleName == DefaultRoles.Anonymous);
                if (role != null)
                    permissions = role.Permissions;
            }
            else
            {
                permissions = user
                    .Roles
                    .SelectMany(x => x.Permissions)
                    .ToList();
                permissions.AddRange(user.Permissions);
            }

            var currentPermissionEntities = allPermissions.Where(x => currentPermissions.Any(y => y == x.Name)).ToList();
            if (permissions.Any(x => currentPermissionEntities.FirstOrDefault(y => y.Name == x) != null))
            {
                return true;
            }
            else
            {
                return false;
            }
        }
        //[ValidateAntiForgeryToken]
        public HttpStatusCodeResult NewMembershipAccount(int CustomerId, int MembershipTypeId)
        {
            try
            {
                using (PharmAssistantContext db = new PharmAssistantContext())
                {
                    MembershipAccount membershipAccount = new MembershipAccount {
                        CustomerId = CustomerId, MembershipTypeId = MembershipTypeId, JoiningDate = DateTime.Now
                    };
                    db.MembershipAccounts.Add(membershipAccount);
                    db.SaveChanges();

                    Customer customer = db.Customers.Where(c => c.CustomerId == CustomerId).FirstOrDefault();
                    customer.MembershipId = db.MembershipAccounts.Where(ma => ma.CustomerId == CustomerId).FirstOrDefault().MembershipId;

                    db.Customers.Attach(customer);
                    db.Entry(customer).State = EntityState.Modified;

                    db.SaveChanges();
                }

                return(new HttpStatusCodeResult(HttpStatusCode.OK));
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);
                return(new HttpStatusCodeResult(HttpStatusCode.BadRequest));
            }
        }
        public void ConfirmAccountReturnsFalseIfNoConfirmationTokenFromMultipleListMatchesInCase()
        {
            // Arrange
            MembershipAccount recordA = new MembershipAccount
            {
                UserId = 98,
                ConfirmationToken = "Foo"
            };
            MembershipAccount recordB = new MembershipAccount
            {
                UserId = 99,
                ConfirmationToken = "fOo"
            };

            _database.Setup(d => d.Users)
                .Returns(new MembershipAccount[] { recordA, recordB }.AsQueryable());
            _database.Setup(x => x.Update<MembershipAccount>(null))
            .Callback(() => { });

            // Act
            bool result = _simpleMembershipProvider.ConfirmAccount("foo");

            // Assert
            Assert.False(result);
        }
        private bool CheckPassword(MembershipAccount user, string password)
        {
            if (user == null || string.IsNullOrWhiteSpace(password))
            {
                return(false);
            }

            var verificationSucceeded = Crypto.VerifyHashedPassword(user.Password, password + user.PasswordSalt);

            if (verificationSucceeded)
            {
                // Reset password failure count if applicable
                if (user.PasswordFailuresSinceLastSuccess > 0)
                {
                    user.PasswordFailuresSinceLastSuccess = 0;
                    _context.Save(user);
                }
            }
            else
            {
                user.PasswordFailuresSinceLastSuccess = user.PasswordFailuresSinceLastSuccess + 1;
                user.LastPasswordFailureDate          = DateTime.UtcNow;
                _context.Save(user);
            }

            return(verificationSucceeded);
        }
Esempio n. 5
0
        private static string GetCollectionName <T>()
        {
            var t = typeof(T);

            if (t == typeof(MembershipAccount))
            {
                return(MembershipAccount.GetCollectionName());
            }

            if (t == typeof(Role))
            {
                return(Role.GetCollectionName());
            }

            if (t == typeof(OAuthToken))
            {
                return(OAuthToken.GetCollectionName());
            }

            if (t == typeof(OAuthMembership))
            {
                return(OAuthMembership.GetCollectionName());
            }

            return(string.Empty);
        }
        public void ConfirmAccountUpdatesIsConfirmedFieldIfAnyOneOfReturnRecordConfirmationTokenMatches()
        {
            // Arrange
            MembershipAccount recordA = new MembershipAccount
            {
                UserId            = 100,
                ConfirmationToken = "Foo"
            };
            MembershipAccount recordB = new MembershipAccount
            {
                UserId            = 101,
                ConfirmationToken = "foo"
            };
            MembershipAccount recordC = new MembershipAccount
            {
                UserId            = 102,
                ConfirmationToken = "fOo"
            };

            _database.Setup(d => d.Users)
            .Returns(new MembershipAccount[] { recordA, recordB, recordC }.AsQueryable())
            .Verifiable();
            _database.Setup(x => x.Update <MembershipAccount>(recordB))
            .Callback(() => { })
            .Verifiable();

            // Act
            bool result = _simpleMembershipProvider.ConfirmAccount("foo");

            // Assert
            Assert.True(result);
            _database.Verify();
        }
Esempio n. 7
0
        public static bool CheckUser(MembershipAccount user, IQueryable <MembershipRole> roles, IQueryable <MembershipPermission> permissionsQuery, string[] currentPermissions)
        {
            List <MembershipPermission> allPermissions = permissionsQuery.ToList();
            List <string> permissions = new List <string>();

            if (user == null)
            {
                var role = roles.FirstOrDefault(x => x.RoleName == DefaultRoles.Anonymous);
                if (role != null)
                {
                    permissions = role.Permissions;
                }
            }
            else
            {
                permissions = user
                              .Roles
                              .SelectMany(x => x.Permissions)
                              .ToList();
                permissions.AddRange(user.Permissions);
            }

            var currentPermissionEntities = allPermissions.Where(x => currentPermissions.Any(y => y == x.Name)).ToList();

            if (permissions.Any(x => currentPermissionEntities.FirstOrDefault(y => y.Name == x) != null))
            {
                return(true);
            }
            else
            {
                return(false);
            }
        }
        public void ConfirmAccountReturnsFalseIfNoConfirmationTokenFromMultipleListMatchesInCase()
        {
            // Arrange
            MembershipAccount recordA = new MembershipAccount
            {
                UserId            = 98,
                ConfirmationToken = "Foo"
            };
            MembershipAccount recordB = new MembershipAccount
            {
                UserId            = 99,
                ConfirmationToken = "fOo"
            };

            _database.Setup(d => d.Users)
            .Returns(new MembershipAccount[] { recordA, recordB }.AsQueryable());
            _database.Setup(x => x.Update <MembershipAccount>(null))
            .Callback(() => { });

            // Act
            bool result = _simpleMembershipProvider.ConfirmAccount("foo");

            // Assert
            Assert.False(result);
        }
        public override void CreateOrUpdateOAuthAccount(string provider, string providerUserId, string userName)
        {
            VerifyInitialized();

            if (string.IsNullOrWhiteSpace(userName))
            {
                throw new MembershipCreateUserException(MembershipCreateStatus.InvalidUserName);
            }

            if (string.IsNullOrWhiteSpace(providerUserId))
            {
                throw new MembershipCreateUserException(MembershipCreateStatus.InvalidProviderUserKey);     // not really the right status ??
            }
            var user = _context.GetUser(userName);

            if (user == null)
            {
                // create a non-local account
                user = new MembershipAccount(userName)
                {
                    IsConfirmed    = true,
                    IsLocalAccount = false
                };

                try
                {
                    _context.Save(user);
                }
                catch (Exception ex)
                {
                    Trace.TraceError("MongoSimpleMembershipProvider.CreateOrUpdateOAuthAccount() ERROR : {0}", ex.ToString());
                    throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);
                }
            }

            var oam = _context.GetOAuthMembership(provider, providerUserId);

            if (oam == null)
            {
                // account doesn't exist, create a new one.
                oam = new OAuthMembership(provider, providerUserId, user.UserId);
            }
            else
            {
                // account already exist, update it
                oam.UserId = user.UserId;
            }

            try
            {
                _context.Save(oam);
            }
            catch (Exception ex)
            {
                Trace.TraceError("MongoSimpleMembershipProvider.CreateOrUpdateOAuthAccount() ERROR : {0}", ex.ToString());
                throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);
            }
        }
Esempio n. 10
0
 public bool GetDateTimeCondition(MembershipAccount n)
 {
     if ((EndTime == DateTime.MinValue) || (EndTime < StartTime))
     {
         EndTime = DateTime.MaxValue;
     }
     if (EndTime < DateTime.MaxValue)
     {
         EndTime = EndTime.AddDays(1);
     }
     return(n.CreationDate >= StartTime && n.CreationDate < EndTime);
 }
        private MembershipUser GetUser(MembershipAccount user)
        {
            if (user == null)
            {
                return(null);
            }

            var lastLogin          = user.LastLoginDate.HasValue ? user.LastLoginDate.Value : DateTime.MinValue;
            var lastPasswordChange = user.PasswordChangedDate.HasValue ? user.PasswordChangedDate.Value : DateTime.MinValue;

            // NOTE: This requires a valid system.web/membership section in config with matching provider name
            return(new MembershipUser(_providerName, user.UserName, user.UserId, null, null, null, user.IsConfirmed /* isApproved */, false, user.CreateDate, lastLogin, DateTime.MinValue, lastPasswordChange, DateTime.MinValue));
        }
Esempio n. 12
0
        private void SeedData(MongoDatabase db)
        {
            if (db == null)
            {
                throw new ArgumentNullException("db");
            }

            // Reset db
            db.GetCollection("IDSequence").Drop();

            _usersCol = db.GetCollection <MembershipAccount>(MembershipAccount.GetCollectionName());
            _usersCol.Drop();

            var salt = Crypto.GenerateSalt();

            var user1 = new MembershipAccount("User1")
            {
                PasswordSalt = salt,
                Password     = Crypto.HashPassword("p@ssword" + salt),
                IsConfirmed  = false
            };

            var user2 = new MembershipAccount("NonLocalUser")
            {
                IsLocalAccount = false,
                IsConfirmed    = true
            };

            _usersCol.InsertBatch(new[] { user1, user2 });

            var oAuthTokenCol = db.GetCollection <OAuthToken>(OAuthToken.GetCollectionName());

            oAuthTokenCol.Drop();
            oAuthTokenCol.Insert(new OAuthToken("Tok3n", "tok3nSecret"));

            var oAuthMembershipCol = db.GetCollection <OAuthMembership>(OAuthMembership.GetCollectionName());

            oAuthMembershipCol.Drop();
            oAuthMembershipCol.Insert(new OAuthMembership("Test", "User1@Test", 1));

            Users            = _usersCol.AsQueryable();
            OAuthTokens      = oAuthTokenCol.AsQueryable();
            OAuthMemberships = oAuthMembershipCol.AsQueryable();
        }
        private void SeedData(MongoDatabase db)
        {
            if (db == null)
            {
                throw new ArgumentNullException("db");
            }

            // Reset db
            db.GetCollection("IDSequence").Drop();

            var rolesCol = db.GetCollection <Role>(Role.GetCollectionName());

            rolesCol.Drop();        // clear 1st

            var roles = new List <Role>
            {
                new Role("Admin"),
                new Role("User"),
                new Role("Guest")
            };

            rolesCol.InsertBatch(roles);


            var usersCol = db.GetCollection <MembershipAccount>(MembershipAccount.GetCollectionName());

            usersCol.Drop();

            var user1 = new MembershipAccount("User1");

            user1.Roles.Add("Admin");  // this user is an Admin

            var users = new List <MembershipAccount>
            {
                user1,
                new MembershipAccount("User2"),
                new MembershipAccount("User3")
            };

            usersCol.InsertBatch(users);

            Roles = rolesCol.AsQueryable();
            Users = usersCol.AsQueryable();
        }
        private bool SetPassword(MembershipAccount user, string newPassword, bool clearVerificationToken = false)
        {
            if (user == null || string.IsNullOrWhiteSpace(newPassword))
            {
                return(false);
            }

            var salt = Crypto.GenerateSalt();

            user.PasswordSalt        = salt;
            user.Password            = Crypto.HashPassword(newPassword + salt);
            user.PasswordChangedDate = DateTime.UtcNow;

            if (clearVerificationToken)
            {
                user.PasswordVerificationToken = null;
                user.PasswordVerificationTokenExpirationDate = null;
            }

            return(_context.Save(user));
        }
Esempio n. 15
0
        public MongoDataContext(string connectionNameOrString)
        {
            Contract.Requires <ArgumentNullException>(!string.IsNullOrWhiteSpace(connectionNameOrString));

            // If it's a name, we lookup config setting
            var connSettings = ConfigurationManager.ConnectionStrings[connectionNameOrString];

            if (connSettings != null && !string.IsNullOrWhiteSpace(connSettings.ConnectionString))
            {
                connectionNameOrString = connSettings.ConnectionString;
            }

            _db = GetDatase(connectionNameOrString);

            _roleCol            = _db.GetCollection <Role>(Role.GetCollectionName());
            _userCol            = _db.GetCollection <MembershipAccount>(MembershipAccount.GetCollectionName());
            _oAuthTokenCol      = _db.GetCollection <OAuthToken>(OAuthToken.GetCollectionName());
            _oAuthMembershipCol = _db.GetCollection <OAuthMembership>(OAuthMembership.GetCollectionName());

            // Check that we can connect to MongoDB server -- will throw an exception that should be caught in provider init
            _roleCol.EnsureUniqueIndex(x => x.RoleName);
        }
        public void Register_GetByUsrName_Delete()
        {
            var email   = Guid.NewGuid().ToString("N") + "@somewhere.com";
            var repos   = new RavenDbAccountRepository(_session);
            var account = new MembershipAccount
            {
                Email           = email,
                UserName        = email,
                Password        = "******",
                ProviderUserKey = "ten"
            };

            repos.Register(account);
            _session.SaveChanges();

            var user = repos.Get(email);

            Assert.NotNull(user);

            repos.Delete(email, true);
            _session.SaveChanges();
        }
        public void ConfirmAccountUpdatesIsConfirmedFieldIfAnyOneOfReturnRecordConfirmationTokenMatches()
        {
            // Arrange
            MembershipAccount recordA = new MembershipAccount
            {
                UserId = 100,
                ConfirmationToken = "Foo"
            };
            MembershipAccount recordB = new MembershipAccount
            {
                UserId = 101,
                ConfirmationToken = "foo"
            };
            MembershipAccount recordC = new MembershipAccount
            {
                UserId = 102,
                ConfirmationToken = "fOo"
            };

            _database.Setup(d => d.Users)
                .Returns(new MembershipAccount[] { recordA, recordB, recordC }.AsQueryable())
                .Verifiable();
            _database.Setup(x => x.Update<MembershipAccount>(recordB))
            .Callback(() => { })
            .Verifiable();

            // Act
            bool result = _simpleMembershipProvider.ConfirmAccount("foo");

            // Assert
            Assert.True(result);
            _database.Verify();
        }
        public override string CreateUserAndAccount(string userName, string password, bool requireConfirmation, IDictionary <string, object> values)
        {
            VerifyInitialized();

            if (string.IsNullOrWhiteSpace(userName))
            {
                throw new MembershipCreateUserException(MembershipCreateStatus.InvalidUserName);
            }

            if (string.IsNullOrWhiteSpace(password))
            {
                throw new MembershipCreateUserException(MembershipCreateStatus.InvalidPassword);
            }

            var user = _context.GetUser(userName);

            // existing local accounts are duplicates
            if (user != null && user.IsLocalAccount)
            {
                throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateUserName);
            }

            var salt           = Crypto.GenerateSalt();
            var hashedPassword = Crypto.HashPassword(password + salt);

            if (hashedPassword.Length > 128)
            {
                throw new MembershipCreateUserException(MembershipCreateStatus.InvalidPassword);
            }

            // create a new local account
            if (user == null)
            {
                user = new MembershipAccount(userName)
                {
                    PasswordSalt = salt,
                    Password     = hashedPassword,
                    IsConfirmed  = !requireConfirmation
                };
            }
            else
            {
                // convert a non-local account
                user.IsLocalAccount                   = true;
                user.PasswordSalt                     = salt;
                user.Password                         = hashedPassword;
                user.IsConfirmed                      = !requireConfirmation; // should already be confirmed
                user.PasswordChangedDate              = DateTime.UtcNow;
                user.LastPasswordFailureDate          = null;
                user.PasswordFailuresSinceLastSuccess = 0;
            }

            if (values != null)
            {
                user.ExtraData = values.ToJson();
            }

            try
            {
                _context.Save(user);
            }
            catch (Exception ex)
            {
                Trace.TraceError("MongoSimpleMembershipProvider.CreateUserAndAccount() ERROR: {0}", ex.ToString());
                throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);
            }

            return(requireConfirmation ? user.ConfirmationToken : null);
        }
Esempio n. 19
0
 public void SaveUser(MembershipAccount user)
 {
     _usersCol.Save(user);
 }