예제 #1
0
        public static void RemoveAllPermissionsFromRole(Guid roleId)
        {
            try
            {
                var role        = _session.Roles.FirstOrDefault(x => x.RoleId == roleId);
                var usersInRole = _session.Users.Where(x => x.Roles.Any(y => y.RoleId == roleId)).ToList();

                role.Permissions.Clear();
                foreach (var user in usersInRole)
                {
                    var roleToChange = user.Roles.FirstOrDefault(x => x.RoleName == role.RoleName);
                    roleToChange.Permissions.Clear();
                }

                _session.Save(role);
                foreach (var user in usersInRole)
                {
                    _session.Save(user);
                }
            }
            catch
            {
                throw;
            }
        }
예제 #2
0
        // Inherited from MembershipProvider ==> Forwarded to previous provider if this provider hasn't been initialized
        public override bool DeleteUser(string username, bool deleteAllRelatedData)
        {
            if (!InitializeCalled)
            {
                return(PreviousProvider.DeleteUser(username, deleteAllRelatedData));
            }

            MembershipAccount user;

            try
            {
                user = GetUser(username);
            }
            catch (Exception)
            {
                return(false);
            }
            user.CatchAll = null;
            bool returnValue = false;

            try
            {
                _session.Save(user);
                returnValue = true;
            }
            catch (Exception)
            {
            }

            //if (deleteAllRelatedData) {
            // REVIEW: do we really want to delete from the user table?
            //}
            return(returnValue);
        }
예제 #3
0
        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method
        public override string GeneratePasswordResetToken(string userName, int tokenExpirationInMinutesFromNow)
        {
            VerifyInitialized();
            if (string.IsNullOrEmpty(userName))
            {
                throw new ArgumentException("Argument_Cannot_Be_Null_Or_Empty", "userName");
            }
            using (var session = new MongoSession(_connectionString))
            {
                var user = VerifyUserNameHasConfirmedAccount(session, userName, throwException: true);

                if (user == null)
                {
                    throw new InvalidOperationException(String.Format("No user found was found that has the name \"{0}\".", userName));
                }


                if (user.PasswordVerificationToken == null || (user.PasswordVerificationToken != null && user.PasswordVerificationTokenExpirationDate > DateTime.UtcNow))
                {
                    user.PasswordVerificationToken = GenerateToken();
                }

                try
                {
                    user.PasswordVerificationTokenExpirationDate = DateTime.UtcNow.AddMinutes(tokenExpirationInMinutesFromNow);
                    session.Save(user);
                }
                catch (Exception)
                {
                    throw new ProviderException("Database operation failed.");
                }

                return(user.PasswordVerificationToken);
            }
        }
예제 #4
0
        public static void InitializeRoles(Type r, string connectionString)
        {
            var session = new MongoSession(connectionString);
            List <MembershipRole>       roles       = new List <MembershipRole>();
            List <MembershipPermission> permissions = session.Permissions.ToList();
            List <string> dbRoles = session.Roles.Select(x => x.RoleName).ToList();

            foreach (FieldInfo field in r.GetFields(BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public))
            {
                string value = field.GetRawConstantValue().ToString();
                if (!dbRoles.Contains(value))
                {
                    MembershipRole role = new MembershipRole {
                        RoleName = value
                    };

                    if (value == DefaultRoles.Admin)
                    {
                        foreach (var p in permissions)
                        {
                            role.Permissions.Add(p.Name);
                        }
                    }

                    session.Save(role);
                }
            }
        }
예제 #5
0
        public override void CreateOrUpdateOAuthAccount(string provider, string providerUserId, string userName)
        {
            VerifyInitialized();

            if (string.IsNullOrEmpty(userName))
            {
                throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);
            }

            var user = GetUser(userName);

            var oldUserId = GetUserIdFromOAuth(provider, providerUserId);

            using (var session = new MongoSession(_connectionString))
            {
                if (oldUserId == -1)
                {
                    // account doesn't exist. create a new one.
                    user.OAuthData.Add(new OAuthAccountDataEmbedded(provider, providerUserId));
                    try
                    {
                        session.Save(user);
                    }
                    catch (Exception)
                    {
                        throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);
                    }
                }
                else
                {
                    // account already exist. update it
                    var oldUser = session.Users.Where(y => y.OAuthData.Any(x => x.ProviderUserId == providerUserId && x.Provider == provider)).FirstOrDefault();
                    var data    = oldUser.OAuthData.FirstOrDefault(x => x.ProviderUserId == providerUserId && x.Provider == provider);
                    oldUser.OAuthData.Remove(data);
                    user.OAuthData.Add(data);
                    try
                    {
                        session.Save(oldUser);
                        session.Save(user);
                    }
                    catch (Exception)
                    {
                        throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);
                    }
                }
            }
        }
예제 #6
0
        public override void AddUsersToRoles(string[] usernames, string[] roleNames)
        {
            SecUtility.CheckArrayParameter(ref roleNames, true, true, true, 256, "roleNames");
            SecUtility.CheckArrayParameter(ref usernames, true, true, true, 256, "usernames");

            try
            {
                List <string> _usernames = usernames.ToList();
                List <string> _roleNames = roleNames.ToList();

                var users = (from u in _session.Users
                             where _usernames.Contains(u.UserName)
                             select u).ToList();

                var roles = (from r in _session.Roles
                             where _roleNames.Contains(r.RoleName)
                             select r).ToList();

                foreach (var userEntity in users)
                {
                    if (userEntity.Roles.Any())
                    {
                        var newRoles = roles.Except(userEntity.Roles);
                        userEntity.Roles.AddRange(newRoles);
                    }
                    else
                    {
                        userEntity.Roles.AddRange(roles);
                    }

                    _session.Save(userEntity);
                }
            }
            catch
            {
                throw;
            }
        }
예제 #7
0
        public override void StoreOAuthRequestToken(string requestToken, string requestTokenSecret)
        {
            VerifyInitialized();

            OAuthToken existingSecret;

            using (var session = new MongoSession(_connectionString))
            {
                existingSecret = session.OAuthTokens.FirstOrDefault(x => x.Token == requestToken);
            }
            if (existingSecret != null)
            {
                if (existingSecret.Secret == requestTokenSecret)
                {
                    // the record already exists
                    return;
                }

                using (var session = new MongoSession(_connectionString))
                {
                    // the token exists with old secret, update it to new secret
                    existingSecret.Secret = requestTokenSecret;
                    session.Save(existingSecret);
                }
            }
            else
            {
                using (var session = new MongoSession(_connectionString))
                {
                    // insert new record
                    OAuthToken newOAuthToken = new OAuthToken
                    {
                        Secret = requestTokenSecret,
                        Token  = requestToken
                    };
                    try
                    {
                        session.Save(newOAuthToken);
                    }
                    catch (Exception)
                    {
                        throw new ProviderException("Failed to store OAuth token to database.");
                    }
                }
            }
        }
예제 #8
0
        public static void InitializePermissions(Type p, string connectionString)
        {
            var session = new MongoSession(connectionString);
            List <MembershipPermission> permissions = new List <MembershipPermission>();
            List <string> dbPermission = session.Permissions.Select(x => x.Name).ToList();

            foreach (FieldInfo field in p.GetFields(BindingFlags.Static | BindingFlags.FlattenHierarchy | BindingFlags.Public))
            {
                string value = field.GetRawConstantValue().ToString();
                if (!dbPermission.Contains(value))
                {
                    session.Save(new MembershipPermission {
                        Name = value
                    });
                }
            }
        }
예제 #9
0
        public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
        {
            SecUtility.CheckArrayParameter(ref roleNames, true, true, true, 256, "roleNames");
            SecUtility.CheckArrayParameter(ref usernames, true, true, true, 256, "usernames");

            try
            {
                List <string> _usernames = usernames.ToList();
                List <string> _roleNames = roleNames.ToList();

                using (var session = new MongoSession(_connectionString))
                {
                    var users = (from u in session.Users
                                 where _usernames.Contains(u.UserName)
                                 select u).ToList();

                    var roles = (from r in session.Roles
                                 where _roleNames.Contains(r.RoleName)
                                 select r).ToList();

                    foreach (var userEntity in users)
                    {
                        if (userEntity.Roles.Any())
                        {
                            int oldCount     = userEntity.Roles.Count;
                            var matchedRoles = roles.Intersect(userEntity.Roles, new RoleComparer());

                            foreach (var matchedRole in matchedRoles)
                            {
                                userEntity.Roles.Remove(matchedRole);
                            }

                            if (oldCount != userEntity.Roles.Count)
                            {
                                session.Save(userEntity);
                            }
                        }
                    }
                }
            }
            catch
            {
                throw;
            }
        }
예제 #10
0
        public override void DeleteOAuthAccount(string provider, string providerUserId)
        {
            VerifyInitialized();

            using (var session = new MongoSession(_connectionString))
            {
                var user = session.Users.FirstOrDefault(y => y.OAuthData.Any(x => x.ProviderUserId == providerUserId && x.Provider == provider));
                var data = user.OAuthData.FirstOrDefault(x => x.ProviderUserId == providerUserId && x.Provider == provider);
                user.OAuthData.Remove(data);
                try
                {
                    session.Save(user);
                }
                catch (Exception)
                {
                    throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);
                }
            }
        }
예제 #11
0
        public void AddUsersToRoles(string[] usernames, params Guid[] roleIds)
        {
            SecUtility.CheckArrayParameter(ref usernames, true, true, true, 256, "usernames");
            var session = new MongoSession(MongoMembershipProvider.ConnectionString);

            try
            {
                List <string> _usernames = usernames.ToList();
                List <Guid>   _roleNames = roleIds.ToList();

                var users = (from u in session.Users
                             where _usernames.Contains(u.UserName)
                             select u).ToList();

                var roles = (from r in session.Roles
                             where _roleNames.Contains(r.RoleId)
                             select r).ToList();

                foreach (var userEntity in users)
                {
                    if (userEntity.Roles.Any())
                    {
                        var newRoles = roles.Except(userEntity.Roles);
                        userEntity.Roles.AddRange(newRoles);
                    }
                    else
                    {
                        userEntity.Roles.AddRange(roles);
                    }

                    session.Save(userEntity);
                }
            }
            catch
            {
                throw;
            }
        }
예제 #12
0
        private bool CheckPassword(MongoSession session, int userId, string password)
        {
            string hashedPassword        = GetHashedPassword(session, userId);
            var    user                  = session.Users.FirstOrDefault(x => x.UserId == userId);
            bool   verificationSucceeded = (hashedPassword != null && Crypto.VerifyHashedPassword(hashedPassword, password));

            if (verificationSucceeded)
            {
                // Reset password failure count on successful credential check
                user.PasswordFailuresSinceLastSuccess = 0;
            }
            else
            {
                int failures = GetPasswordFailuresSinceLastSuccess(session, userId);
                if (failures != -1)
                {
                    user.PasswordFailuresSinceLastSuccess = failures + 1;
                    user.LastPasswordFailureDate          = DateTime.UtcNow;
                }
            }

            session.Save(user);
            return(verificationSucceeded);
        }