Почему у метода IsInRole не работает кастомный RoleProvider asp.net mvc? - PullRequest
1 голос
/ 20 января 2012

Я реализовал пользовательское членство. Вот мой пользовательский MembershipProvidet и мой пользовательский RoleProvide

public class FinkaynMembershipProvider : MembershipProvider
{

    BLL.GestionUserAccount gestionUserAccount = new BLL.GestionUserAccount();
    #region Unimplemented MembershipProvider Methods
    public override string ApplicationName
    {
        get
        {
           return  "FinKayn";
        }
        set
        {
            throw new NotImplementedException();
        }

    }
    public override bool ChangePassword(string username, string oldPassword, string newPassword)
    {
        throw new NotImplementedException();
    }
    public override bool ChangePasswordQuestionAndAnswer(string username, string password, string newPasswordQuestion, string newPasswordAnswer)
    {
        throw new NotImplementedException();
    }
    public override MembershipUser CreateUser(string username, string password, string email, string passwordQuestion, string passwordAnswer, bool isApproved, object providerUserKey, out MembershipCreateStatus status)
    {
        throw new NotImplementedException();
    }

    public override bool DeleteUser(string username, bool deleteAllRelatedData)
    {
        throw new NotImplementedException();
    }
    public override bool EnablePasswordReset
    {
        get { throw new NotImplementedException(); }
    }
    public override bool EnablePasswordRetrieval
    {
        get { throw new NotImplementedException(); }
    }
    public override MembershipUserCollection FindUsersByEmail(string emailToMatch, int pageIndex, int pageSize, out int totalRecords)
    {
        throw new NotImplementedException();
    }
    public override MembershipUserCollection FindUsersByName(string usernameToMatch, int pageIndex, int pageSize, out int totalRecords)
    {
        throw new NotImplementedException();
    }
    public override MembershipUserCollection GetAllUsers(int pageIndex, int pageSize, out int totalRecords)
    {
        throw new NotImplementedException();
    }
    public override int GetNumberOfUsersOnline()
    {
        throw new NotImplementedException();
    }
    public override string GetPassword(string username, string answer)
    {
        throw new NotImplementedException();
    }




   public override MembershipUser GetUser(object providerUserKey, bool userIsOnline)
    {
          throw new NotImplementedException();
   }

   public static long FinKaynUserId
   {
       //long FinKaynUserId = 0;
       get
       {
           if (HttpContext.Current.Session["FinKaynUserId"] != null && Convert.ToInt64(HttpContext.Current.Session["FinKaynUserId"]) != 0)
               return Convert.ToInt64(HttpContext.Current.Session["FinKaynUserId"]);
           else
           {
               HttpCookie myCookie = HttpContext.Current.Request.Cookies["FinKaynUserId"];
               if (myCookie != null)
               {
                   HttpContext.Current.Session["FinKaynUserId"] = Convert.ToInt64(myCookie.Value);
                   // Session["User"] = (new UserManager()).GetUser(Convert.ToInt64(Session["UserId"]));
                   return  Convert.ToInt64(HttpContext.Current.Session["FinKaynUserId"]);
               }
               else
                  return 0;
           }
       }
       set
       {
           HttpCookie cookie = new HttpCookie("FinKaynUserId");
           cookie.Value = value.ToString();
           cookie.Secure = false;
           cookie.Expires = DateTime.Now.AddDays(3);
           HttpContext.Current.Request.Cookies.Add(cookie);
           HttpContext.Current.Session["FinKaynUserId"] = value;
       }

   }

   public  MembershipUser GetUser(string userId)
   {
       throw new NotImplementedException();
   }
   public override MembershipUser GetUser(string username, bool userIsOnline)
   {
         //MembershipUser   userRep = new MembershipUser();
          entities.UserAccount user = gestionUserAccount.getUserAccount(username);
          if (user != null)
          {
              MembershipUser memUser = new MembershipUser("FinkaynMembershipProvider", username, user.IdUser, user.Email,
                                                          string.Empty, string.Empty,
                                                          true, false, DateTime.MinValue,
                                                          DateTime.MinValue,
                                                          DateTime.MinValue,
                                                          DateTime.Now, DateTime.Now);
              return memUser;
          }
          return null;
    }
    public override string GetUserNameByEmail(string email)
    {
        throw new NotImplementedException();
    }
    public override int MaxInvalidPasswordAttempts
    {
        get { throw new NotImplementedException(); }
    }
    public override int MinRequiredNonAlphanumericCharacters
    {
        get { throw new NotImplementedException(); }
    }
    public override int MinRequiredPasswordLength
    {
        get { return 6; }
    }
    public override int PasswordAttemptWindow
    {
        get { throw new NotImplementedException(); }
    }
    public override MembershipPasswordFormat PasswordFormat
    {
        get { throw new NotImplementedException(); }
    }
    public override string PasswordStrengthRegularExpression
    {
        get { throw new NotImplementedException(); }
    }
    public override bool RequiresQuestionAndAnswer
    {
        get { throw new NotImplementedException(); }
    }
    public override bool RequiresUniqueEmail
    {
        get { return true; }
    }
    public override string ResetPassword(string username, string answer)
    {
        throw new NotImplementedException();
    }
    public override bool UnlockUser(string userName)
    {
        throw new NotImplementedException();
    }
    public override void UpdateUser(MembershipUser user)
    {
        throw new NotImplementedException();
    }

    #endregion





    public override bool ValidateUser(string email, string password)
    {
        if (string.IsNullOrEmpty(password.Trim()) || string.IsNullOrEmpty(email.Trim())) return false;
       // password=(new CryptoEngine()).Encrypt(password);
        entities.UserAccount user = gestionUserAccount.authentifier(email, password);



        if (user == null)
        {
           // User = new UserAccount();
            return false;
        }
        if (user.IdUser>0)
        {
           // User = user;
            return true;
        }
        return false;
    }




}

public class FinKaynRoleProvider : RoleProvider
{

     GestionRole gestionRole = new GestionRole();
     GestionUserAccount gestionUserAccount = new GestionUserAccount();

    public FinKaynRoleProvider()
    {

    }

   public override string ApplicationName
   {
       get
       {
           return "finkayn";
       }
       set
       {
           throw new NotImplementedException();
       }
   }

   public override void Initialize(string name, NameValueCollection config)
   {
       base.Initialize(name, config);

       //IUnityContainer container = new UnityContainerFactory().Create();
      // accountRepository = container.Resolve<IAccountRepository>();
   }
   public override void AddUsersToRoles(string[] usernames, string[] roleNames)
   {
        throw new NotImplementedException();
    }
   public override void RemoveUsersFromRoles(string[] usernames, string[] roleNames)
   {
       throw new NotImplementedException();
   }
   public override void CreateRole(string roleName)
   {
       throw new NotImplementedException();
   }
   public override bool DeleteRole(string roleName, bool throwOnPopulatedRole)
   {
       throw new NotImplementedException();
   }

    /// <summary>
    /// roles of a user ,acutually it's userName =email in our case
    /// </summary>
    /// <param name="email"></param>
    /// <returns></returns>
   public override string[] GetRolesForUser(string email)
   {

       return gestionUserAccount.GetRolesForUser(email);

  }

   public override bool IsUserInRole(string email, string roleName)
   {
       string[] userRoles = this.GetRolesForUser(email);

       return userRoles.Contains(roleName);
   }
   public override string[] GetUsersInRole(string roleName)
   {
       throw new NotImplementedException();
   }
   public override bool RoleExists(string roleName)
   {
       return (new GestionRole()).RoleExists(roleName);
   }
   public override string[] FindUsersInRole(string roleName, string usernameToMatch)
   {
       throw new NotImplementedException();
   }
   public override string[] GetAllRoles()
   {
       return (new GestionRole ()).GetAllRoles();
   }

}

В представлении главной страницы: у меня есть ссылка, которая видна только по роли (роли хранятся в таблице Роль, пользователь может иметь много ролей)

         <a>
         <%if (HttpContext.Current.User.IsInRole("admin")){%>
            <%=Html.ActionLink("Places", "Places", "Places")%>
        <%} %>
        </a>

По этому вопросу: custom RoleProvider

GetRolesForUser должен выполняться при вызове IsInRole. Я установил на нем точку останова, но ничего не происходит. В чем проблема?

Я также добавил ролевой провайдер в web.config:

      <authentication mode="Forms">
  <forms loginUrl="../Auth/signin" timeout="2880" path="/" />
</authentication>
<membership defaultProvider="FinkaynMembershipProvider">
  <providers>
    <clear/>
    <add name="FinkaynMembershipProvider" type="FinkaynMembershipProvider"
         connectionStringName="FinKaynConnectionString"
         enablePasswordRetrieval="false"
         enablePasswordReset="true"
         requiresQuestionAndAnswer="false"
         requiresUniqueEmail="false"
         maxInvalidPasswordAttempts="5"
         minRequiredPasswordLength="6"
         minRequiredNonalphanumericCharacters="0"
         passwordAttemptWindow="10"
         applicationName="/" />
  </providers>

</membership>
<roleManager defaultProvider="FinKaynRoleProvider" enabled="true" cacheRolesInCookie="true"   >
  <providers>
    <clear/>
    <add name="FinKaynRoleProvider" type="FinKaynRoleProvider"/>
  </providers>
</roleManager>

1 Ответ

0 голосов
/ 20 января 2012

Вы пытались полностью квалифицировать своего поставщика ролей в своем файле web.config. Атрибут type должен содержать пространство имен типов.

Также измените имя параметра вашего метода GetRolesForUser обратно на имя пользователя

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...