Ejemplo n.º 1
0
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName");
            try
            {
                using (var session = new MongoSession(_connectionString))
                {
                    var role = (from r in session.Roles
                                where r.RoleName == roleName
                                select r).SingleOrDefault();


                    var users = session.Users
                                .Where(u => u.Roles != null)
                                .Where(u => u.Roles.Any(r => r.RoleName == roleName));


                    if (users.Any() && throwOnPopulatedRole)
                    {
                        throw new ProviderException(StringResources.GetString(StringResources.Role_is_not_empty));
                    }

                    session.DeleteById <MembershipRole>(role.RoleId);

                    return(true);
                }
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 2
0
        public override string[] GetUsersInRole(string roleName)
        {
            SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName");

            try
            {
                using (var session = new MongoSession(_connectionString))
                {
                    var role = (from r in session.Roles
                                where r.RoleName == roleName
                                select r).SingleOrDefault();

                    if (role == null)
                    {
                        throw new ProviderException(StringResources.GetString(StringResources.Provider_role_not_found, roleName));
                    }

                    var users = from u in session.Users
                                where u.Roles.Any(r => r.RoleName == roleName)
                                select u;

                    if (users == null || !users.Any())
                    {
                        return(new string[0]);
                    }

                    return(users.Select(u => u.UserName).ToArray());
                }
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 3
0
        public override void CreateRole(string roleName)
        {
            SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName");
            try
            {
                using (var session = new MongoSession(_connectionString))
                {
                    var roles = from r in session.Roles
                                where r.RoleName == roleName
                                select r;

                    if (roles.Any())
                    {
                        throw new ProviderException(StringResources.GetString(StringResources.Provider_role_already_exists, roleName));
                    }


                    var role = new MembershipRole
                    {
                        RoleName        = roleName,
                        LoweredRoleName = roleName.ToLowerInvariant()
                    };

                    session.Add(role);
                }
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 4
0
 // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method
 public override bool ResetPasswordWithToken(string token, string newPassword)
 {
     VerifyInitialized();
     if (string.IsNullOrEmpty(newPassword))
     {
         throw new ArgumentException("Argument_Cannot_Be_Null_Or_Empty", "newPassword");
     }
     using (var session = new MongoSession(_connectionString))
     {
         var user = session.Users.FirstOrDefault(x => x.PasswordVerificationToken == token && x.PasswordVerificationTokenExpirationDate > DateTime.UtcNow);
         if (user != null)
         {
             bool success = SetPassword(session, user, newPassword);
             if (success)
             {
                 // Clear the Token on success
                 user.PasswordVerificationToken = null;
                 user.PasswordVerificationTokenExpirationDate = null;
                 try
                 {
                     session.Update(user);
                 }
                 catch (Exception)
                 {
                     throw new ProviderException("Database operation failed.");
                 }
             }
             return(success);
         }
         else
         {
             return(false);
         }
     }
 }
Ejemplo n.º 5
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);
                }
            }
        }
Ejemplo n.º 6
0
        /// <summary>
        /// Sets the confirmed flag for the username if it is correct.
        /// </summary>
        /// <returns>True if the account could be successfully confirmed. False if the username was not found or the confirmation token is invalid.</returns>
        /// <remarks>Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method</remarks>
        public override bool ConfirmAccount(string userName, string accountConfirmationToken)
        {
            VerifyInitialized();
            using (var session = new MongoSession(_connectionString))
            {
                // We need to compare the token using a case insensitive comparison however it seems tricky to do this uniformly across databases when representing the token as a string.
                // Therefore verify the case on the client
                //session.ConfirmAccount(userTableName, userNameColumn, userIdColumn);
                var row = session.Users.FirstOrDefault(x => x.ConfirmationToken == accountConfirmationToken && x.UserName == userName);

                if (row == null)
                {
                    return(false);
                }
                string expectedToken = row.ConfirmationToken;

                if (String.Equals(accountConfirmationToken, expectedToken, StringComparison.Ordinal))
                {
                    try
                    {
                        row.IsConfirmed = true;
                        session.Update(row);
                    }
                    catch (Exception)
                    {
                        return(false);
                    }
                }
                return(false);
            }
        }
Ejemplo n.º 7
0
        // Ensures the user exists in the accounts table
        private MembershipAccount VerifyUserNameHasConfirmedAccount(MongoSession session, string userName, bool throwException)
        {
            var user = session.Users.FirstOrDefault(x => x.UserName == userName);

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

            if (!user.IsConfirmed)
            {
                if (throwException)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "No account exists for \"{0}\".", userName));
                }
                else
                {
                    return(null);
                }
            }
            return(user);
        }
Ejemplo n.º 8
0
        public override string[] GetRolesForUser(string username)
        {
            SecUtility.CheckParameter(ref username, true, false, true, 256, "username");
            if (username.Length < 1)
            {
                return(new string[0]);
            }

            try
            {
                using (var session = new MongoSession(_connectionString))
                {
                    var user = (from u in session.Users
                                where u.UserName == username
                                select u).SingleOrDefault();

                    if (user == null)
                    {
                        return(new string[0]);
                    }

                    if (user.Roles == null)
                    {
                        return(new string[0]);
                    }

                    return(user.Roles.Select(r => r.RoleName).ToArray());
                }
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 9
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);
            }
        }
Ejemplo n.º 10
0
 /// <summary>
 /// Sets the confirmed flag for the username if it is correct.
 /// </summary>
 /// <returns>True if the account could be successfully confirmed. False if the username was not found or the confirmation token is invalid.</returns>
 /// <remarks>Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method.
 /// There is a tiny possibility where this method fails to work correctly. Two or more users could be assigned the same token but specified using different cases.
 /// A workaround for this would be to use the overload that accepts both the user name and confirmation token.
 /// </remarks>
 public override bool ConfirmAccount(string accountConfirmationToken)
 {
     VerifyInitialized();
     using (var session = new MongoSession(_connectionString))
     {
         // We need to compare the token using a case insensitive comparison however it seems tricky to do this uniformly across databases when representing the token as a string.
         // Therefore verify the case on the client
         var rows = session.Users
                    .Where(x => x.ConfirmationToken == accountConfirmationToken)
                    .ToList()
                    .Where(r => ((string)r.ConfirmationToken).Equals(accountConfirmationToken, StringComparison.Ordinal))
                    .ToList();
         Debug.Assert(rows.Count < 2, "By virtue of the fact that the ConfirmationToken is random and unique, we can never have two tokens that are identical.");
         if (!rows.Any())
         {
             return(false);
         }
         var row = rows.First();
         row.IsConfirmed = true;
         try
         {
             session.Update(row);
             return(true);
         }
         catch (Exception)
         {
             return(false);
         }
     }
 }
Ejemplo n.º 11
0
 // Not an override ==> Simple Membership MUST be enabled to use this method
 public int GetUserId(string userName)
 {
     VerifyInitialized();
     using (var session = new MongoSession(_connectionString))
     {
         return(GetUserId(session, userName));
     }
 }
Ejemplo n.º 12
0
        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method
        public override string CreateUserAndAccount(string userName, string password, bool requireConfirmation, IDictionary <string, object> values)
        {
            VerifyInitialized();

            using (var session = new MongoSession(_connectionString))
            {
                CreateUserRow(session, userName, values);
                return(CreateAccount(userName, password, requireConfirmation));
            }
        }
Ejemplo n.º 13
0
        /// <summary>
        /// Determines whether there exists a local account (as opposed to OAuth account) with the specified userId.
        /// </summary>
        /// <param name="userId">The user id to check for local account.</param>
        /// <returns>
        ///   <c>true</c> if there is a local account with the specified user id]; otherwise, <c>false</c>.
        /// </returns>
        public override bool HasLocalAccount(int userId)
        {
            VerifyInitialized();

            using (var session = new MongoSession(_connectionString))
            {
                var user = session.Users.FirstOrDefault(x => x.UserId == userId);
                return(!string.IsNullOrEmpty(user.Password));
            }
        }
Ejemplo n.º 14
0
        /// <summary>
        /// Deletes the OAuth token from the backing store from the database.
        /// </summary>
        /// <param name="token">The token to be deleted.</param>
        public override void DeleteOAuthToken(string token)
        {
            VerifyInitialized();

            using (var session = new MongoSession(_connectionString))
            {
                // Note that token is case-sensitive
                session.DeleteById <OAuthToken>(token);
            }
        }
Ejemplo n.º 15
0
        private static int GetPasswordFailuresSinceLastSuccess(MongoSession session, int userId)
        {
            var failure = session.Users.FirstOrDefault(x => x.UserId == userId);

            if (failure != null)
            {
                return(failure.PasswordFailuresSinceLastSuccess);
            }
            return(-1);
        }
Ejemplo n.º 16
0
        internal static int GetUserId(MongoSession session, string userName)
        {
            var result = session.Users.FirstOrDefault(x => x.UserName == userName);

            if (result == null)
            {
                return(-1);
            }

            return(result.UserId);
        }
Ejemplo n.º 17
0
        private string GetHashedPassword(MongoSession session, int userId)
        {
            var user = session.Users.FirstOrDefault(x => x.UserId == userId);

            // REVIEW: Should get exactly one match, should we throw if we get > 1?
            if (user == null)
            {
                return(null);
            }
            return(user.Password);
        }
Ejemplo n.º 18
0
        public override string GetOAuthTokenSecret(string token)
        {
            VerifyInitialized();

            using (var session = new MongoSession(_connectionString))
            {
                // Note that token is case-sensitive
                var oauthToken = session.OAuthTokens.FirstOrDefault(x => x.Token == token);
                return(oauthToken.Secret);
            }
        }
Ejemplo n.º 19
0
        internal static Guid GetUserId(MongoSession session, string userName)
        {
            var result = session.GetUserId("Users", "UserName", userName);

            if (result == null)
            {
                return(Guid.Empty);
            }

            return(result);
        }
Ejemplo n.º 20
0
 // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method
 public override int GetUserIdFromPasswordResetToken(string token)
 {
     VerifyInitialized();
     using (var session = new MongoSession(_connectionString))
     {
         var result = session.Users.FirstOrDefault(x => x.PasswordVerificationToken == token);
         if (result != null)
         {
             return((int)result.UserId);
         }
         return(-1);
     }
 }
Ejemplo n.º 21
0
        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method
        public override int GetPasswordFailuresSinceLastSuccess(string userName)
        {
            using (var session = new MongoSession(_connectionString))
            {
                int userId = GetUserId(session, userName);
                if (userId == -1)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "No user found was found that has the name \"{0}\".", userName));
                }

                return(GetPasswordFailuresSinceLastSuccess(session, userId));
            }
        }
Ejemplo n.º 22
0
        private MembershipAccount GetUser(string userName)
        {
            VerifyInitialized();
            using (var session = new MongoSession(_connectionString))
            {
                var user = session.Users.FirstOrDefault(x => x.UserName == userName);
                if (user == null)
                {
                    throw new MembershipCreateUserException(MembershipCreateStatus.InvalidUserName);
                }

                return(user);
            }
        }
Ejemplo n.º 23
0
        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method
        public override bool IsConfirmed(string userName)
        {
            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: false);
                return(user != null);
            }
        }
Ejemplo n.º 24
0
        /// <summary>
        /// Replaces the request token with access token and secret.
        /// </summary>
        /// <param name="requestToken">The request token.</param>
        /// <param name="accessToken">The access token.</param>
        /// <param name="accessTokenSecret">The access token secret.</param>
        public override void ReplaceOAuthRequestTokenWithAccessToken(string requestToken, string accessToken, string accessTokenSecret)
        {
            VerifyInitialized();

            using (var session = new MongoSession(_connectionString))
            {
                // insert new record
                session.DeleteById <OAuthToken>(requestToken);

                // Although there are two different types of tokens, request token and access token,
                // we treat them the same in database records.
                StoreOAuthRequestToken(accessToken, accessTokenSecret);
            }
        }
Ejemplo n.º 25
0
        public override string GetUserNameFromId(int userId)
        {
            VerifyInitialized();

            using (var session = new MongoSession(_connectionString))
            {
                var user = session.Users.FirstOrDefault(x => x.UserId == userId);
                if (user == null)
                {
                    return(null);
                }
                return(user.UserName);
            }
        }
Ejemplo n.º 26
0
        public override int GetUserIdFromOAuth(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));
                if (user != null)
                {
                    return((int)user.UserId);
                }

                return(-1);
            }
        }
Ejemplo n.º 27
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);
                    }
                }
            }
        }
Ejemplo n.º 28
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.");
                    }
                }
            }
        }
Ejemplo n.º 29
0
        // Inherited from ExtendedMembershipProvider ==> Simple Membership MUST be enabled to use this method
        public override DateTime GetLastPasswordFailureDate(string userName)
        {
            using (var session = new MongoSession(_connectionString))
            {
                var user = session.Users.FirstOrDefault(x => x.UserName == userName);
                if (user == null)
                {
                    throw new InvalidOperationException(String.Format(CultureInfo.CurrentCulture, "No user found was found that has the name \"{0}\".", userName));
                }

                if (user.LastPasswordFailureDate.HasValue)
                {
                    return(user.LastPasswordFailureDate.Value);
                }
                return(DateTime.MinValue);
            }
        }
Ejemplo n.º 30
0
        private void CreateUserRow(MongoSession session, string userName, IDictionary <string, object> values)
        {
            // Make sure user doesn't exist
            int userId = GetUserId(session, userName);

            if (userId != -1)
            {
                throw new MembershipCreateUserException(MembershipCreateStatus.DuplicateUserName);
            }

            bool result = session.CreateUserRow(userName, values);

            if (!result)
            {
                throw new MembershipCreateUserException(MembershipCreateStatus.ProviderError);
            }
        }