Ejemplo n.º 1
0
        public override bool RoleExists(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();

                    return(role != null);
                }
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 2
0
        // authorization

        static public bool IsUserInRole(string username, string roleName)
        {
            if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc) && HttpContext.Current != null)
            {
                EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_BEGIN, HttpContext.Current.WorkerRequest);
            }

            EnsureEnabled();
            bool isUserInRole    = false;
            bool isRolePrincipal = false;

            try {
                SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName");
                SecUtility.CheckParameter(ref username, true, false, true, 0, "username");
                if (username.Length < 1)
                {
                    return(false);
                }
                IPrincipal user = GetCurrentUser();
                if (user != null && user is RolePrincipal && ((RolePrincipal)user).ProviderName == Provider.Name && StringUtil.EqualsIgnoreCase(username, user.Identity.Name))
                {
                    isUserInRole = user.IsInRole(roleName);
                }
                else
                {
                    isUserInRole = Provider.IsUserInRole(username, roleName);
                }
                return(isUserInRole);
            } finally {
                if (HostingEnvironment.IsHosted && EtwTrace.IsTraceEnabled(EtwTraceLevel.Information, EtwTraceFlags.AppSvc) && HttpContext.Current != null)
                {
                    if (EtwTrace.IsTraceEnabled(EtwTraceLevel.Verbose, EtwTraceFlags.AppSvc))
                    {
                        string status = SR.Resources.GetString(isUserInRole ? SR.Etw_Success : SR.Etw_Failure, CultureInfo.InstalledUICulture);
                        EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_IS_USER_IN_ROLE, HttpContext.Current.WorkerRequest, isRolePrincipal ? "RolePrincipal" : Provider.GetType().FullName, username, roleName, status);
                    }

                    EtwTrace.Trace(EtwTraceType.ETW_TYPE_ROLE_END, HttpContext.Current.WorkerRequest, isRolePrincipal ? "RolePrincipal" : Provider.GetType().FullName, username);
                }
            }
        }
Ejemplo n.º 3
0
        public override bool IsUserInRole(string username, string roleName)
        {
            SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName");
            SecUtility.CheckParameter(ref username, true, false, true, 256, "username");
            if (username.Length < 1)
            {
                return(false);
            }

            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(false);
                    }

                    if (user.Roles == null)
                    {
                        return(false);
                    }

                    if (user.Roles.Where(r => r.RoleName == roleName).Any())
                    {
                        return(true);
                    }

                    return(false);
                }
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 4
0
        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////
        public static int DeleteProfiles(ProfileInfoCollection profiles)
        {
            if (profiles == null)
            {
                throw new ArgumentNullException("profiles");
            }

            if (profiles.Count < 1)
            {
                throw new ArgumentException(
                          SR.GetString(SR.Parameter_collection_empty,
                                       "profiles"),
                          "profiles");
            }

            foreach (ProfileInfo pi in profiles)
            {
                string username = pi.UserName;
                SecUtility.CheckParameter(ref username, true, true, true, 0, "UserName");
            }
            return(Provider.DeleteProfiles(profiles));
        }
Ejemplo n.º 5
0
        public static void AssignPermissionsToRole(string roleName, params string[] permissionsArray)
        {
            SecUtility.CheckArrayParameter(ref permissionsArray, true, true, true, 256, "permissions");
            SecUtility.CheckParameter(ref roleName, true, false, true, 256, "roleName");

            try
            {
                var role        = _session.Roles.FirstOrDefault(x => x.RoleName == roleName);
                var usersInRole = _session.Users.Where(x => x.Roles.Any(y => y.RoleName == roleName)).ToList();

                var permissions = (from p in _session.Permissions
                                   where permissionsArray.Contains(p.Name)
                                   select p).ToList();


                ProcessActionPermissionsToRole(permissions, role, usersInRole, (array, id) => { array.Add(id); return(array); });
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 6
0
        static public void RemoveUserFromRoles(string username, string[] roleNames)
        {
            EnsureEnabled();

            SecUtility.CheckParameter(ref username, true, true, true, 0, "username");

            SecUtility.CheckArrayParameter(ref roleNames,
                                           true,
                                           true,
                                           true,
                                           0,
                                           "roleNames");

            Provider.RemoveUsersFromRoles(new string [] { username }, roleNames);
            try
            {
                RolePrincipal user = GetCurrentUser() as RolePrincipal;
                if (user != null && user.ProviderName == Provider.Name && user.IsRoleListCached && StringUtil.EqualsIgnoreCase(user.Identity.Name, username))
                {
                    user.SetDirty();
                }
            }
            catch { }
        }
        public Oper  GetUser2(string username, bool userIsOnline)
        {
            SecUtility.CheckParameter(
                ref username,
                true,
                false,
                true,
                256,
                "username");
            DataTable dt = SqlHelper.ExecuteDataTable(CommandType.Text, "select * from tbOper where cnvcOperName='" + username + "'");

            if (dt.Rows.Count == 0)
            {
                throw new BusinessException("查找操作员", "操作员没找到");
            }
            Oper oper = new Oper(dt);

            if (userIsOnline)
            {
                oper.LastActivityDate = DateTime.Now;
                EntityMapping.Update(oper);
            }
            return(oper);
        }
Ejemplo n.º 8
0
        public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
        {
            SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName");
            try
            {
                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())
                {
                    if (throwOnPopulatedRole)
                    {
                        throw new ProviderException(StringResources.GetString(StringResources.Role_is_not_empty));
                    }
                    else
                    {
                        return(false);
                    }
                }

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

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

            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.UserName == usernameToMatch &&
                                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.º 10
0
        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////
        //////////////////////////////////////////////////////////////////////
        public override string[] FindUsersInRole(string roleName, string usernameToMatch)
        {
            SecUtility.CheckParameter(ref roleName, true, true, true, 256, "roleName");
            SecUtility.CheckParameter(ref usernameToMatch, true, true, false, 256, "usernameToMatch");

            try {
                SqlConnectionHolder holder = null;

                try {
                    holder = SqlConnectionHelper.GetConnection(_sqlConnectionString, true);
                    CheckSchemaVersion(holder.Connection);

                    SqlCommand       cmd    = new SqlCommand("dbo.aspnet_UsersInRoles_FindUsersInRole", holder.Connection);
                    SqlDataReader    reader = null;
                    SqlParameter     p      = new SqlParameter("@ReturnValue", SqlDbType.Int);
                    StringCollection sc     = new StringCollection();

                    cmd.CommandType    = CommandType.StoredProcedure;
                    cmd.CommandTimeout = CommandTimeout;

                    p.Direction = ParameterDirection.ReturnValue;
                    cmd.Parameters.Add(p);
                    cmd.Parameters.Add(CreateInputParam("@ApplicationName", SqlDbType.NVarChar, ApplicationName));
                    cmd.Parameters.Add(CreateInputParam("@RoleName", SqlDbType.NVarChar, roleName));
                    cmd.Parameters.Add(CreateInputParam("@UserNameToMatch", SqlDbType.NVarChar, usernameToMatch));
                    try {
                        reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
                        while (reader.Read())
                        {
                            sc.Add(reader.GetString(0));
                        }
                    }
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                    if (sc.Count < 1)
                    {
                        switch (GetReturnValue(cmd))
                        {
                        case 0:
                            return(new string[0]);

                        case 1:
                            throw new ProviderException(SR.GetString(SR.Provider_role_not_found, roleName));

                        default:
                            throw new ProviderException(SR.GetString(SR.Provider_unknown_failure));
                        }
                    }
                    String[] strReturn = new String[sc.Count];
                    sc.CopyTo(strReturn, 0);
                    return(strReturn);
                }
                finally
                {
                    if (holder != null)
                    {
                        holder.Close();
                        holder = null;
                    }
                }
            }
            catch
            {
                throw;
            }
        }
Ejemplo n.º 11
0
        /// <summary>
        /// Changes a users password after checking that they know their old password
        /// </summary>
        /// <param name="username">Username</param>
        /// <param name="oldPassword">The old password in the system</param>
        /// <param name="newPassword">The desired new password</param>
        /// <returns>True if the change succeeds, otherwise false</returns>
        public override bool ChangePassword(string username, string oldPassword, string newPassword)
        {
            SecUtility.CheckParameter(ref username, true, true, true, 256, "username");
            SecUtility.CheckParameter(ref oldPassword, true, true, false, 128, "oldPassword");
            SecUtility.CheckParameter(ref newPassword, true, true, false, 128, "newPassword");

            int status;

            //Return false if the old password is not correct
            if (!CheckPassword(username, oldPassword, out status))
            {
                return(false);
            }

            //Make sure the new password meets password length requirements
            if (newPassword.Length < MinRequiredPasswordLength)
            {
                throw new ArgumentException();
            }

            int count = 0;

            //Check the number of non-alpha numeric chars
            for (int i = 0; i < newPassword.Length; i++)
            {
                if (!char.IsLetterOrDigit(newPassword, i))
                {
                    count++;
                }
            }

            if (count < MinRequiredNonAlphanumericCharacters)
            {
                throw new ArgumentException();
            }

            //If we are using a regular expression, make sure the password passes
            if (PasswordStrengthRegularExpression.Length > 0)
            {
                if (!Regex.IsMatch(newPassword, PasswordStrengthRegularExpression))
                {
                    throw new ArgumentException();
                }
            }

            string salt = GenerateSalt();

            //Encode password using new salt and password format settings
            string pass = EncodePassword(newPassword, (int)_PasswordFormat, salt);

            if (pass.Length > 128)
            {
                throw new ArgumentException();
            }

            //Raise the OnValidatingPassword() function so someone can hook into it if they want
            ValidatePasswordEventArgs e = new ValidatePasswordEventArgs(username, newPassword, false);

            OnValidatingPassword(e);

            if (e.Cancel)
            {
                if (e.FailureInformation != null)
                {
                    throw e.FailureInformation;
                }
                else
                {
                    throw new ArgumentException();
                }
            }

            _dops.ResetDops();
            _dops.Sproc = "usp_ChangePassword";

            _dops.SetParameter("@Email", username, "IN");
            _dops.SetParameter("@NewPassword", pass, "IN");
            _dops.SetParameter("@PasswordFormat", (int)_PasswordFormat, "IN");
            _dops.SetParameter("@PasswordSalt", salt, "IN");
            _dops.SetParameter("RETURN_VALUE", string.Empty, "RETURN");

            try
            {
                _dops.Execute_Sql();
            }
            catch (SqlException ex)
            {
                throw new ProviderException(ex.Message, ex);
            }

            int result = (int)_dops.GetOutputVariable("RETURN_VALUE");

            //Check to see if there is a problem
            if (result != 0)
            {
                throw new MembershipPasswordException(); //If there is a problem, throw the exception
            }

            return(true);
        }
Ejemplo n.º 12
0
        /// <summary>
        /// Resets a user's password if they have the correct answer to the passwordQuestion
        /// </summary>
        /// <param name="username">Username</param>
        /// <param name="answer">Answer to the users question</param>
        /// <returns>New password as a string</returns>
        public override string ResetPassword(string username, string passwordAnswer)
        {
            if (!EnablePasswordReset)
            {
                throw new NotSupportedException();
            }

            SecUtility.CheckParameter(ref username, true, true, true, 256, "username");

            string salt;
            int    passwordFormat;
            int    status;
            bool   isApproved;

            GetPasswordWithFormat(username, out passwordFormat, out status, out salt, out isApproved);

            //Check to see if there were any problems (may expand later to involve more specific errors)
            if (status != 0) //problem occurred
            {
                throw new ProviderException();
            }

            //We will do encoding of passwords later, will require changes to createUser, ValidateUser, and others
            //string encodedPasswordAnswer;

            //if (!string.IsNullOrEmpty(passwordAnswer))
            //    encodedPasswordAnswer = EncodePassword(passwordAnswer.ToLower(), passwordFormat, salt);
            //else
            //    encodedPasswordAnswer = passwordAnswer;

            if (passwordAnswer != null)
            {
                passwordAnswer = passwordAnswer.Trim();
            }

            SecUtility.CheckParameter(ref passwordAnswer, RequiresQuestionAndAnswer, RequiresQuestionAndAnswer, false, 128, "passwordAnswer");

            string newPassword = GeneratePassword();

            ValidatePasswordEventArgs eventArgs = new ValidatePasswordEventArgs(username, newPassword, false);

            OnValidatingPassword(eventArgs);

            if (eventArgs.Cancel)
            {
                if (eventArgs.FailureInformation != null)
                {
                    throw eventArgs.FailureInformation;
                }
                else
                {
                    throw new ProviderException();
                }
            }

            _dops.ResetDops();
            _dops.Sproc = "usp_ResetPassword";

            _dops.SetParameter("@Email", username, "IN");
            _dops.SetParameter("@NewPassword", EncodePassword(newPassword, (int)passwordFormat, salt), "IN");
            _dops.SetParameter("@PasswordFormat", passwordFormat, "IN");
            _dops.SetParameter("@PasswordSalt", salt, "IN");
            _dops.SetParameter("@PasswordAnswer", passwordAnswer, "IN");
            _dops.SetParameter("RETURN_VALUE", string.Empty, "RETURN");

            _dops.Execute_Sql();

            int success = 1;

            try
            {
                success = (int)_dops.GetOutputVariable("RETURN_VALUE");
            }
            catch (SqlException ex)
            {
                throw new ProviderException(ex.Message, ex);
            }

            //Check to see if there is a problem
            if (success != 0)
            {
                throw new MembershipPasswordException(); //If there is a problem, throw the exception
            }

            return(newPassword);
        }
Ejemplo n.º 13
0
 static public bool RoleExists(string roleName)
 {
     EnsureEnabled();
     SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName");
     return(Provider.RoleExists(roleName));
 }
Ejemplo n.º 14
0
 public static string GetUserNameByEmail(string emailToMatch)
 {
     SecUtility.CheckParameter(ref emailToMatch, false, false, false, 0, "emailToMatch");
     return(Provider.GetUserNameByEmail(emailToMatch));
 }
Ejemplo n.º 15
0
 //////////////////////////////////////////////////////////////////////
 //////////////////////////////////////////////////////////////////////
 //////////////////////////////////////////////////////////////////////
 public static bool DeleteProfile(string username)
 {
     SecUtility.CheckParameter(ref username, true, true, true, 0, "username");
     return(Provider.DeleteProfiles(new string [] { username }) != 0);
 }
Ejemplo n.º 16
0
        public override string[] GetUsersInRole(string roleName)
        {
            string[] strArray2;
            SecUtility.CheckParameter(ref roleName, true, true, true, 0x100, "roleName");
            try
            {
                SqlConnectionHolder connection = null;
                try
                {
                    connection = SqlConnectionHelper.GetConnection(this._sqlConnectionString, true);
                    this.CheckSchemaVersion(connection.Connection);
                    SqlCommand       cmd       = new SqlCommand("dbo.aspnet_UsersInRoles_GetUsersInRoles", connection.Connection);
                    SqlDataReader    reader    = null;
                    SqlParameter     parameter = new SqlParameter("@ReturnValue", SqlDbType.Int);
                    StringCollection strings   = new StringCollection();
                    cmd.CommandType     = CommandType.StoredProcedure;
                    cmd.CommandTimeout  = this.CommandTimeout;
                    parameter.Direction = ParameterDirection.ReturnValue;
                    cmd.Parameters.Add(parameter);
                    cmd.Parameters.Add(this.CreateInputParam("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName));
                    cmd.Parameters.Add(this.CreateInputParam("@RoleName", SqlDbType.NVarChar, roleName));
                    try
                    {
                        reader = cmd.ExecuteReader(CommandBehavior.SequentialAccess);
                        while (reader.Read())
                        {
                            strings.Add(reader.GetString(0));
                        }
                    }
                    catch
                    {
                        throw;
                    }
                    finally
                    {
                        if (reader != null)
                        {
                            reader.Close();
                        }
                    }
                    if (strings.Count < 1)
                    {
                        switch (this.GetReturnValue(cmd))
                        {
                        case 0:
                            return(new string[0]);

                        case 1:
                            throw new ProviderException(System.Web.SR.GetString("Provider_role_not_found", new object[] { roleName }));
                        }
                        throw new ProviderException(System.Web.SR.GetString("Provider_unknown_failure"));
                    }
                    string[] array = new string[strings.Count];
                    strings.CopyTo(array, 0);
                    strArray2 = array;
                }
                finally
                {
                    if (connection != null)
                    {
                        connection.Close();
                        connection = null;
                    }
                }
            }
            catch
            {
                throw;
            }
            return(strArray2);
        }
Ejemplo n.º 17
0
 public static bool DeleteUser(string username, bool deleteAllRelatedData)
 {
     SecUtility.CheckParameter(ref username, true, true, true, 0, "username");
     return(Provider.DeleteUser(username, deleteAllRelatedData));
 }
Ejemplo n.º 18
0
 public static bool DeleteUser(string username)
 {
     SecUtility.CheckParameter(ref username, true, true, true, 0, "username");
     return(Provider.DeleteUser(username, true));
 }
Ejemplo n.º 19
0
        public static MembershipUser GetUser(string username, bool userIsOnline)
        {
            SecUtility.CheckParameter(ref username, true, false, true, 0, "username");

            return(Provider.GetUser(username, userIsOnline));
        }
Ejemplo n.º 20
0
        // role administration
        //

        static public string[] GetUsersInRole(string roleName)
        {
            EnsureEnabled();
            SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName");
            return(Provider.GetUsersInRole(roleName));
        }
Ejemplo n.º 21
0
 static public void CreateRole(string roleName)
 {
     EnsureEnabled();
     SecUtility.CheckParameter(ref roleName, true, true, true, 0, "roleName");
     Provider.CreateRole(roleName);
 }
Ejemplo n.º 22
0
        public override bool IsUserInRole(string username, string roleName)
        {
            bool flag;

            SecUtility.CheckParameter(ref roleName, true, true, true, 0x100, "roleName");
            SecUtility.CheckParameter(ref username, true, false, true, 0x100, "username");
            if (username.Length < 1)
            {
                return(false);
            }
            try
            {
                SqlConnectionHolder connection = null;
                try
                {
                    connection = SqlConnectionHelper.GetConnection(this._sqlConnectionString, true);
                    this.CheckSchemaVersion(connection.Connection);
                    SqlCommand cmd = new SqlCommand("dbo.aspnet_UsersInRoles_IsUserInRole", connection.Connection)
                    {
                        CommandType    = CommandType.StoredProcedure,
                        CommandTimeout = this.CommandTimeout
                    };
                    SqlParameter parameter = new SqlParameter("@ReturnValue", SqlDbType.Int)
                    {
                        Direction = ParameterDirection.ReturnValue
                    };
                    cmd.Parameters.Add(parameter);
                    cmd.Parameters.Add(this.CreateInputParam("@ApplicationName", SqlDbType.NVarChar, this.ApplicationName));
                    cmd.Parameters.Add(this.CreateInputParam("@UserName", SqlDbType.NVarChar, username));
                    cmd.Parameters.Add(this.CreateInputParam("@RoleName", SqlDbType.NVarChar, roleName));
                    cmd.ExecuteNonQuery();
                    switch (this.GetReturnValue(cmd))
                    {
                    case 0:
                        return(false);

                    case 1:
                        return(true);

                    case 2:
                        return(false);

                    case 3:
                        return(false);
                    }
                    throw new ProviderException(System.Web.SR.GetString("Provider_unknown_failure"));
                }
                finally
                {
                    if (connection != null)
                    {
                        connection.Close();
                        connection = null;
                    }
                }
            }
            catch
            {
                throw;
            }
            return(flag);
        }
Ejemplo n.º 23
0
 public override ProfileInfoCollection FindProfilesByUserName(ProfileAuthenticationOption authenticationOption, string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
 {
     SecUtility.CheckParameter(ref usernameToMatch, true, true, false, 0x100, "username");
     SqlParameter[] args = new SqlParameter[] { this.CreateInputParam("@UserNameToMatch", SqlDbType.NVarChar, usernameToMatch) };
     return(this.GetProfilesForQuery(args, authenticationOption, pageIndex, pageSize, out totalRecords));
 }