ЧленствоПоставщик и ТребованиеВопрос и Ответ - PullRequest
1 голос
/ 12 апреля 2011

Мы предоставляем нашим клиентам шаблон веб-сайта для использования в качестве основы для своих веб-сайтов. На нашем сайте есть пользовательский поставщик.

У нас возникла проблема с одним клиентом. Клиент рассылает приглашения потенциальным участникам по электронной почте с URL-адресом для входа в систему участника. Во время регистрации они задали секретный вопрос / ответ.

Однако иногда потенциальный участник теряет электронную почту (и, следовательно, свой пароль), но все равно пытается присоединиться к сайту.

Клиент потребовал, чтобы участник мог сбросить свой пароль без обычного секретного вопроса / ответа, когда регистрация не была завершена.

К сожалению, MembershipProvider не предоставляет имя пользователя при запросе, требуются ли вопрос / ответ. Однако он вызывает GetUser () как раз перед.

Чтобы эта функция работала, я добавил метод (StartingPasswordRecovery) в свой MembershipProvider, чтобы отметить, что сброс пароля активен, вызывая его из события OnVerifyingUser на странице PasswordRecovery.

Хотя этот код работает, я не уверен, что он очень надежный.

Может кто-нибудь указать мне на лучшее решение.

Вот соответствующий код, который я добавил своему провайдеру членства.

Private _hasUserDefinedQuestionAndAnswer As Boolean
Private _isResettingPassword As Boolean

Public Overloads Overrides Function GetUser(ByVal username As String, ByVal userIsOnline As Boolean) As System.Web.Security.MembershipUser
    ...
    _hasUserDefinedQuestionAndAnswer = ...
    ... 
End Function

Public Overrides ReadOnly Property RequiresQuestionAndAnswer() As Boolean
    Get
        If Me._isResettingPassword Then
            Me._isResettingPassword = False
            Return Me.pRequiresQuestionAndAnswer And Me._hasUserDefinedQuestionAndAnswer
        End If

        Return Me.pRequiresQuestionAndAnswer
    End Get
End Property

Public Sub StartingPasswordRecovery()
    Me._isResettingPassword = True
End Sub

1 Ответ

1 голос
/ 13 апреля 2011

Я не уверен, правильно ли я вас понял, но не могли бы вы использовать профиль пользователя 1002 *, чтобы определить, требуется ли пользователю вопрос и ответ или нет?

web.config:

<profile defaultProvider="YourProfileProvider">
    <providers>
        <clear/>
        <add name="YourProfileProvider" type="System.Web.Profile.SqlProfileProvider"  connectionStringName="ConnectionStringToDB" applicationName="/YourApp"></add>
    </providers>
    <properties>
        <add name="RequiresQuestionAndAnswer" defaultValue="false" />
    </properties>
</profile>

Пользовательское членство провайдера:

Public Overrides ReadOnly Property RequiresQuestionAndAnswer As Boolean
    Get
        If HttpContext.Current.User.Identity.IsAuthenticated Then
            Dim userRequiresQuestionAndAnswer = _
                CType(HttpContext.Current.Profile.GetPropertyValue("RequiresQuestionAndAnswer"), Boolean)
            Return userRequiresQuestionAndAnswer
        Else
            Return MyBase.RequiresQuestionAndAnswer 
        End If
    End Get
End Property

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

HttpContext.Current.Profile.SetPropertyValue("RequiresQuestionAndAnswer", userRequiresQuestionAndAnswer)
HttpContext.Current.Profile.Save()

Редактировать

согласно вашему комментарию, я немного изменил код. Я надеюсь, что это поможет заставить это работать:

в пользовательском членстве-провайдере:

Public Overloads Overrides ReadOnly Property RequiresQuestionAndAnswer As Boolean
    Get
        If HttpContext.Current.User.Identity.IsAuthenticated Then
            Return RequiresQuestionAndAnswer(Membership.GetUser.UserName)
        Else
            Return MyBase.RequiresQuestionAndAnswer
        End If
    End Get
End Property

Public Overloads ReadOnly Property RequiresQuestionAndAnswer(ByVal userName As String) As Boolean
    Get
        Dim profile As ProfileBase = ProfileBase.Create(userName)
        If Not profile Is Nothing Then
            Dim userRequiresQuestionAndAnswer = _
                CType(profile.GetPropertyValue("RequiresQuestionAndAnswer"), Boolean)
            Return userRequiresQuestionAndAnswer
        Else
            Return MyBase.RequiresQuestionAndAnswer
        End If
    End Get
End Property

где ваш PasswordRecovery-Control:

Protected Sub VerifyingUser(ByVal sender As Object, ByVal e As LoginCancelEventArgs)
    Dim login As WebControls.Login = DirectCast(Me.LoginView1.FindControl("Login1"), WebControls.Login)
    Dim userName = DirectCast(login.FindControl("PwdRecovery"), PasswordRecovery).UserName
    Dim RequiresQuestionAndAnswer = DirectCast(Membership.Provider, YourMembershipProvider).RequiresQuestionAndAnswer(userName)
    '....'
End Sub

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