示例#1
0
def signin(request):
    """
    signin page. It manages the legacy authentification (user/password) 
    and openid authentification
    
    url: /signin/
    
    template : authopenid/signin.htm
    """
    logging.debug('in signin view')
    on_failure = signin_failure
    email_feeds_form = askbot_forms.SimpleEmailSubscribeForm()

    #we need a special priority on where to redirect on successful login
    #here:
    #1) url parameter "next" - if explicitly set
    #2) url from django setting LOGIN_REDIRECT_URL
    #3) home page of the forum
    login_redirect_url = getattr(settings, 'LOGIN_REDIRECT_URL', None)
    next_url = get_next_url(request, default=login_redirect_url)
    logging.debug('next url is %s' % next_url)

    if askbot_settings.ALLOW_ADD_REMOVE_LOGIN_METHODS == False \
        and request.user.is_authenticated():
        return HttpResponseRedirect(next_url)

    if next_url == reverse('user_signin'):
        next_url = '%(next)s?next=%(next)s' % {'next': next_url}

    login_form = forms.LoginForm(initial={'next': next_url})

    #todo: get next url make it sticky if next is 'user_signin'
    if request.method == 'POST':

        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():

            provider_name = login_form.cleaned_data['login_provider_name']
            if login_form.cleaned_data['login_type'] == 'password':

                password_action = login_form.cleaned_data['password_action']
                if askbot_settings.USE_LDAP_FOR_PASSWORD_LOGIN:
                    assert (password_action == 'login')
                    username = login_form.cleaned_data['username']
                    password = login_form.cleaned_data['password']
                    # will be None if authentication fails
                    user = authenticate(username=username,
                                        password=password,
                                        method='ldap')
                    if user is not None:
                        login(request, user)
                        return HttpResponseRedirect(next_url)
                    else:
                        return finalize_generic_signin(
                            request=request,
                            user=user,
                            user_identifier=username,
                            login_provider_name=provider_name,
                            redirect_url=next_url)

                else:
                    if password_action == 'login':
                        user = authenticate(
                            username=login_form.cleaned_data['username'],
                            password=login_form.cleaned_data['password'],
                            provider_name=provider_name,
                            method='password')
                        if user is None:
                            login_form.set_password_login_error()
                        else:
                            login(request, user)
                            #todo: here we might need to set cookies
                            #for external login sites
                            return HttpResponseRedirect(next_url)
                    elif password_action == 'change_password':
                        if request.user.is_authenticated():
                            new_password = \
                                login_form.cleaned_data['new_password']
                            AuthBackend.set_password(
                                user=request.user,
                                password=new_password,
                                provider_name=provider_name)
                            request.user.message_set.create(
                                message=_('Your new password saved'))
                            return HttpResponseRedirect(next_url)
                    else:
                        logging.critical('unknown password action %s' %
                                         password_action)
                        raise Http404

            elif login_form.cleaned_data['login_type'] == 'openid':
                #initiate communication process
                logging.debug('processing signin with openid submission')

                #todo: make a simple-use wrapper for openid protocol

                sreg_req = sreg.SRegRequest(optional=['nickname', 'email'])
                redirect_to = "%s%s?%s" % (
                    get_url_host(request), reverse('user_complete_signin'),
                    urllib.urlencode({'next': next_url}))
                return ask_openid(request,
                                  login_form.cleaned_data['openid_url'],
                                  redirect_to,
                                  on_failure=signin_failure,
                                  sreg_request=sreg_req)

            elif login_form.cleaned_data['login_type'] == 'oauth':
                try:
                    #this url may need to have "next" piggibacked onto
                    callback_url = reverse('user_complete_oauth_signin')

                    connection = util.OAuthConnection(
                        provider_name, callback_url=callback_url)

                    connection.start()

                    request.session['oauth_token'] = connection.get_token()
                    request.session['oauth_provider_name'] = provider_name
                    request.session[
                        'next_url'] = next_url  #special case for oauth

                    oauth_url = connection.get_auth_url(login_only=False)
                    return HttpResponseRedirect(oauth_url)

                except util.OAuthError, e:
                    logging.critical(unicode(e))
                    msg = _('Unfortunately, there was some problem when '
                            'connecting to %(provider)s, please try again '
                            'or use another provider') % {
                                'provider': provider_name
                            }
                    request.user.message_set.create(message=msg)

            elif login_form.cleaned_data['login_type'] == 'facebook':
                #have to redirect for consistency
                #there is a requirement that 'complete_signin'
                try:
                    #this call may raise FacebookError
                    user_id = util.get_facebook_user_id(request)

                    user = authenticate(method='facebook',
                                        facebook_user_id=user_id)

                    return finalize_generic_signin(
                        request=request,
                        user=user,
                        user_identifier=user_id,
                        login_provider_name=provider_name,
                        redirect_url=next_url)

                except util.FacebookError, e:
                    logging.critical(unicode(e))
                    msg = _('Unfortunately, there was some problem when '
                            'connecting to %(provider)s, please try again '
                            'or use another provider') % {
                                'provider': 'Facebook'
                            }
                    request.user.message_set.create(message=msg)

            elif login_form.cleaned_data['login_type'] == 'wordpress_site':
                #here wordpress_site means for a self hosted wordpress blog not a wordpress.com blog
                wp = Client(askbot_settings.WORDPRESS_SITE_URL,
                            login_form.cleaned_data['username'],
                            login_form.cleaned_data['password'])
                try:
                    wp_user = wp.call(GetUserInfo())
                    custom_wp_openid_url = '%s?user_id=%s' % (wp.url,
                                                              wp_user.user_id)
                    user = authenticate(method='wordpress_site',
                                        wordpress_url=wp.url,
                                        wp_user_id=wp_user.user_id)
                    return finalize_generic_signin(
                        request=request,
                        user=user,
                        user_identifier=custom_wp_openid_url,
                        login_provider_name=provider_name,
                        redirect_url=next_url)
                except WpFault, e:
                    logging.critical(unicode(e))
                    msg = _('The login password combination was not correct')
                    request.user.message_set.create(message=msg)
示例#2
0
def signin(
        request,
        newquestion=False,  #todo: not needed
        newanswer=False,  #todo: not needed
):
    """
    signin page. It manages the legacy authentification (user/password) 
    and openid authentification
    
    url: /signin/
    
    template : authopenid/signin.htm
    """
    logging.debug('in signin view')
    on_failure = signin_failure
    email_feeds_form = askbot_forms.SimpleEmailSubscribeForm()

    next_url = get_next_url(request)
    logging.debug('next url is %s' % next_url)

    if next_url == reverse('user_signin'):
        next_url = '%(next)s?next=%(next)s' % {'next': next_url}

    login_form = forms.LoginForm(initial={'next': next_url})

    #todo: get next url make it sticky if next is 'user_signin'
    if request.method == 'POST':

        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():

            provider_name = login_form.cleaned_data['login_provider_name']
            if login_form.cleaned_data['login_type'] == 'password':

                password_action = login_form.cleaned_data['password_action']
                if askbot_settings.USE_LDAP_FOR_PASSWORD_LOGIN:
                    assert (password_action == 'login')
                    ldap_provider_name = askbot_settings.LDAP_PROVIDER_NAME
                    username = login_form.cleaned_data['username']
                    if util.ldap_check_password(
                            username, login_form.cleaned_data['password']):
                        user = authenticate(ldap_user_id=username,
                                            provider_name=ldap_provider_name,
                                            method='ldap')
                        if user is not None:
                            login(request, user)
                            return HttpResponseRedirect(next_url)
                        else:
                            return finalize_generic_signin(
                                request=request,
                                user=user,
                                user_identifier=username,
                                login_provider_name=ldap_provider_name,
                                redirect_url=next_url)
                else:
                    if password_action == 'login':
                        user = authenticate(
                            username=login_form.cleaned_data['username'],
                            password=login_form.cleaned_data['password'],
                            provider_name=provider_name,
                            method='password')
                        if user is None:
                            login_form.set_password_login_error()
                        else:
                            login(request, user)
                            #todo: here we might need to set cookies
                            #for external login sites
                            return HttpResponseRedirect(next_url)
                    elif password_action == 'change_password':
                        if request.user.is_authenticated():
                            new_password = \
                                login_form.cleaned_data['new_password']
                            AuthBackend.set_password(
                                user=request.user,
                                password=new_password,
                                provider_name=provider_name)
                            request.user.message_set.create(
                                message=_('Your new password saved'))
                            return HttpResponseRedirect(next_url)
                    else:
                        logging.critical('unknown password action %s' %
                                         password_action)
                        raise Http404

            elif login_form.cleaned_data['login_type'] == 'openid':
                #initiate communication process
                logging.debug('processing signin with openid submission')

                #todo: make a simple-use wrapper for openid protocol

                sreg_req = sreg.SRegRequest(optional=['nickname', 'email'])
                redirect_to = "%s%s?%s" % (
                    get_url_host(request), reverse('user_complete_signin'),
                    urllib.urlencode({'next': next_url}))
                return ask_openid(request,
                                  login_form.cleaned_data['openid_url'],
                                  redirect_to,
                                  on_failure=signin_failure,
                                  sreg_request=sreg_req)

            elif login_form.cleaned_data['login_type'] == 'oauth':
                try:
                    #this url may need to have "next" piggibacked onto
                    callback_url = reverse('user_complete_oauth_signin')

                    connection = util.OAuthConnection(
                        provider_name, callback_url=callback_url)

                    connection.start()

                    request.session['oauth_token'] = connection.get_token()
                    request.session['oauth_provider_name'] = provider_name
                    request.session[
                        'next_url'] = next_url  #special case for oauth

                    oauth_url = connection.get_auth_url(login_only=False)
                    return HttpResponseRedirect(oauth_url)

                except util.OAuthError, e:
                    logging.critical(unicode(e))
                    msg = _('Unfortunately, there was some problem when '
                            'connecting to %(provider)s, please try again '
                            'or use another provider') % {
                                'provider': provider_name
                            }
                    request.user.message_set.create(message=msg)

            elif login_form.cleaned_data['login_type'] == 'facebook':
                #have to redirect for consistency
                #there is a requirement that 'complete_signin'
                try:
                    #this call may raise FacebookError
                    user_id = util.get_facebook_user_id(request)

                    user = authenticate(method='facebook',
                                        facebook_user_id=user_id)

                    return finalize_generic_signin(
                        request=request,
                        user=user,
                        user_identifier=user_id,
                        login_provider_name=provider_name,
                        redirect_url=next_url)

                except util.FacebookError, e:
                    logging.critical(unicode(e))
                    msg = _('Unfortunately, there was some problem when '
                            'connecting to %(provider)s, please try again '
                            'or use another provider') % {
                                'provider': 'Facebook'
                            }
                    request.user.message_set.create(message=msg)

            else:
                #raise 500 error - unknown login type
                pass
示例#3
0
def signin(request):
    """
    signin page. It manages the legacy authentification (user/password) 
    and openid authentification
    
    url: /signin/
    
    template : authopenid/signin.htm
    """
    logging.debug('in signin view')
    on_failure = signin_failure
    email_feeds_form = askbot_forms.SimpleEmailSubscribeForm()

    next_url = get_next_url(request)
    logging.debug('next url is %s' % next_url)

    if askbot_settings.ALLOW_ADD_REMOVE_LOGIN_METHODS == False \
        and request.user.is_authenticated():
        return HttpResponseRedirect(next_url)

    if next_url == reverse('user_signin'):
        next_url = '%(next)s?next=%(next)s' % {'next': next_url}

    login_form = forms.LoginForm(initial = {'next': next_url})

    #todo: get next url make it sticky if next is 'user_signin'
    if request.method == 'POST':

        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():

            provider_name = login_form.cleaned_data['login_provider_name']
            if login_form.cleaned_data['login_type'] == 'password':

                password_action = login_form.cleaned_data['password_action']
                if askbot_settings.USE_LDAP_FOR_PASSWORD_LOGIN:
                    assert(password_action == 'login')
                    ldap_provider_name = askbot_settings.LDAP_PROVIDER_NAME
                    username = login_form.cleaned_data['username']
                    if util.ldap_check_password(
                                username,
                                login_form.cleaned_data['password']
                            ):
                        user = authenticate(
                                        ldap_user_id = username,
                                        provider_name = ldap_provider_name,
                                        method = 'ldap'
                                    )
                        if user is not None:
                            login(request, user)
                            return HttpResponseRedirect(next_url)
                        else:
                            return finalize_generic_signin(
                                    request = request,
                                    user = user,
                                    user_identifier = username,
                                    login_provider_name = ldap_provider_name,
                                    redirect_url = next_url
                                )
                    else:
                        login_form.set_password_login_error() 
                else:
                    if password_action == 'login':
                        user = authenticate(
                                username = login_form.cleaned_data['username'],
                                password = login_form.cleaned_data['password'],
                                provider_name = provider_name,
                                method = 'password'
                            )
                        if user is None:
                            login_form.set_password_login_error()
                        else:
                            login(request, user)
                            #todo: here we might need to set cookies
                            #for external login sites
                            return HttpResponseRedirect(next_url)
                    elif password_action == 'change_password':
                        if request.user.is_authenticated():
                            new_password = \
                                login_form.cleaned_data['new_password']
                            AuthBackend.set_password(
                                            user=request.user,
                                            password=new_password,
                                            provider_name=provider_name
                                        )
                            request.user.message_set.create(
                                        message = _('Your new password saved')
                                    )
                            return HttpResponseRedirect(next_url)
                    else:
                        logging.critical(
                            'unknown password action %s' % password_action
                        )
                        raise Http404

            elif login_form.cleaned_data['login_type'] == 'openid':
                #initiate communication process
                logging.debug('processing signin with openid submission')

                #todo: make a simple-use wrapper for openid protocol

                sreg_req = sreg.SRegRequest(optional=['nickname', 'email'])
                redirect_to = "%s%s?%s" % (
                        get_url_host(request),
                        reverse('user_complete_signin'), 
                        urllib.urlencode({'next':next_url})
                )
                return ask_openid(
                            request, 
                            login_form.cleaned_data['openid_url'],
                            redirect_to,
                            on_failure=signin_failure,
                            sreg_request=sreg_req
                        )

            elif login_form.cleaned_data['login_type'] == 'oauth':
                try:
                    #this url may need to have "next" piggibacked onto
                    callback_url = reverse('user_complete_oauth_signin')

                    connection = util.OAuthConnection(
                                        provider_name,
                                        callback_url = callback_url
                                    )

                    connection.start()

                    request.session['oauth_token'] = connection.get_token()
                    request.session['oauth_provider_name'] = provider_name
                    request.session['next_url'] = next_url#special case for oauth

                    oauth_url = connection.get_auth_url(login_only = False)
                    return HttpResponseRedirect(oauth_url)

                except util.OAuthError, e:
                    logging.critical(unicode(e))
                    msg = _('Unfortunately, there was some problem when '
                            'connecting to %(provider)s, please try again '
                            'or use another provider'
                        ) % {'provider': provider_name}
                    request.user.message_set.create(message = msg)

            elif login_form.cleaned_data['login_type'] == 'facebook':
                #have to redirect for consistency
                #there is a requirement that 'complete_signin'
                try:
                    #this call may raise FacebookError
                    user_id = util.get_facebook_user_id(request)

                    user = authenticate(
                                method = 'facebook',
                                facebook_user_id = user_id
                            )

                    return finalize_generic_signin(
                                    request = request,
                                    user = user,
                                    user_identifier = user_id,
                                    login_provider_name = provider_name,
                                    redirect_url = next_url
                                )

                except util.FacebookError, e:
                    logging.critical(unicode(e))
                    msg = _('Unfortunately, there was some problem when '
                            'connecting to %(provider)s, please try again '
                            'or use another provider'
                        ) % {'provider': 'Facebook'}
                    request.user.message_set.create(message = msg)

            else:
                #raise 500 error - unknown login type
                pass
示例#4
0
文件: views.py 项目: reebot/Askandget
def signin(request, newquestion=False, newanswer=False):  # todo: not needed  # todo: not needed
    """
    signin page. It manages the legacy authentification (user/password) 
    and openid authentification
    
    url: /signin/
    
    template : authopenid/signin.htm
    """
    logging.debug("in signin view")
    on_failure = signin_failure
    email_feeds_form = askbot_forms.SimpleEmailSubscribeForm()

    next_url = get_next_url(request)
    logging.debug("next url is %s" % next_url)

    if next_url == reverse("user_signin"):
        next_url = "%(next)s?next=%(next)s" % {"next": next_url}

    login_form = forms.LoginForm(initial={"next": next_url})

    # todo: get next url make it sticky if next is 'user_signin'
    if request.method == "POST":

        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():

            provider_name = login_form.cleaned_data["login_provider_name"]
            if login_form.cleaned_data["login_type"] == "password":

                password_action = login_form.cleaned_data["password_action"]
                if askbot_settings.USE_LDAP_FOR_PASSWORD_LOGIN:
                    assert password_action == "login"
                    ldap_provider_name = askbot_settings.LDAP_PROVIDER_NAME
                    username = login_form.cleaned_data["username"]
                    if util.ldap_check_password(username, login_form.cleaned_data["password"]):
                        user = authenticate(ldap_user_id=username, provider_name=ldap_provider_name, method="ldap")
                        if user is not None:
                            login(request, user)
                            return HttpResponseRedirect(next_url)
                        else:
                            return finalize_generic_signin(
                                request=request,
                                user=user,
                                user_identifier=username,
                                login_provider_name=ldap_provider_name,
                                redirect_url=next_url,
                            )
                else:
                    if password_action == "login":
                        user = authenticate(
                            username=login_form.cleaned_data["username"],
                            password=login_form.cleaned_data["password"],
                            provider_name=provider_name,
                            method="password",
                        )
                        if user is None:
                            login_form.set_password_login_error()
                        else:
                            login(request, user)
                            # todo: here we might need to set cookies
                            # for external login sites
                            return HttpResponseRedirect(next_url)
                    elif password_action == "change_password":
                        if request.user.is_authenticated():
                            new_password = login_form.cleaned_data["new_password"]
                            AuthBackend.set_password(
                                user=request.user, password=new_password, provider_name=provider_name
                            )
                            request.user.message_set.create(message=_("Your new password saved"))
                            return HttpResponseRedirect(next_url)
                    else:
                        logging.critical("unknown password action %s" % password_action)
                        raise Http404

            elif login_form.cleaned_data["login_type"] == "openid":
                # initiate communication process
                logging.debug("processing signin with openid submission")

                # todo: make a simple-use wrapper for openid protocol

                sreg_req = sreg.SRegRequest(optional=["nickname", "email"])
                redirect_to = "%s%s?%s" % (
                    get_url_host(request),
                    reverse("user_complete_signin"),
                    urllib.urlencode({"next": next_url}),
                )
                return ask_openid(
                    request,
                    login_form.cleaned_data["openid_url"],
                    redirect_to,
                    on_failure=signin_failure,
                    sreg_request=sreg_req,
                )

            elif login_form.cleaned_data["login_type"] == "oauth":
                try:
                    # this url may need to have "next" piggibacked onto
                    callback_url = reverse("user_complete_oauth_signin")

                    connection = util.OAuthConnection(provider_name, callback_url=callback_url)

                    connection.start()

                    request.session["oauth_token"] = connection.get_token()
                    request.session["oauth_provider_name"] = provider_name
                    request.session["next_url"] = next_url  # special case for oauth

                    oauth_url = connection.get_auth_url(login_only=False)
                    return HttpResponseRedirect(oauth_url)

                except util.OAuthError, e:
                    logging.critical(unicode(e))
                    msg = _(
                        "Unfortunately, there was some problem when "
                        "connecting to %(provider)s, please try again "
                        "or use another provider"
                    ) % {"provider": provider_name}
                    request.user.message_set.create(message=msg)

            elif login_form.cleaned_data["login_type"] == "facebook":
                # have to redirect for consistency
                # there is a requirement that 'complete_signin'
                try:
                    # this call may raise FacebookError
                    user_id = util.get_facebook_user_id(request)

                    user = authenticate(method="facebook", facebook_user_id=user_id)

                    return finalize_generic_signin(
                        request=request,
                        user=user,
                        user_identifier=user_id,
                        login_provider_name=provider_name,
                        redirect_url=next_url,
                    )

                except util.FacebookError, e:
                    logging.critical(unicode(e))
                    msg = _(
                        "Unfortunately, there was some problem when "
                        "connecting to %(provider)s, please try again "
                        "or use another provider"
                    ) % {"provider": "Facebook"}
                    request.user.message_set.create(message=msg)

            else:
                # raise 500 error - unknown login type
                pass
示例#5
0
def signin(request):
    """
    signin page. It manages the legacy authentification (user/password) 
    and openid authentification
    
    url: /signin/
    
    template : authopenid/signin.htm
    """
    logging.debug("in signin view")
    on_failure = signin_failure
    email_feeds_form = askbot_forms.SimpleEmailSubscribeForm()

    # we need a special priority on where to redirect on successful login
    # here:
    # 1) url parameter "next" - if explicitly set
    # 2) url from django setting LOGIN_REDIRECT_URL
    # 3) home page of the forum
    login_redirect_url = getattr(settings, "LOGIN_REDIRECT_URL", None)
    next_url = get_next_url(request, default=login_redirect_url)
    logging.debug("next url is %s" % next_url)

    if askbot_settings.ALLOW_ADD_REMOVE_LOGIN_METHODS == False and request.user.is_authenticated():
        return HttpResponseRedirect(next_url)

    if next_url == reverse("user_signin"):
        next_url = "%(next)s?next=%(next)s" % {"next": next_url}

    login_form = forms.LoginForm(initial={"next": next_url})

    # todo: get next url make it sticky if next is 'user_signin'
    if request.method == "POST":

        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():

            provider_name = login_form.cleaned_data["login_provider_name"]
            if login_form.cleaned_data["login_type"] == "password":

                password_action = login_form.cleaned_data["password_action"]
                if askbot_settings.USE_LDAP_FOR_PASSWORD_LOGIN:
                    assert password_action == "login"
                    ldap_provider_name = askbot_settings.LDAP_PROVIDER_NAME
                    username = login_form.cleaned_data["username"]
                    if util.ldap_check_password(username, login_form.cleaned_data["password"]):
                        user = authenticate(ldap_user_id=username, provider_name=ldap_provider_name, method="ldap")
                        if user is not None:
                            login(request, user)
                            return HttpResponseRedirect(next_url)
                        else:
                            return finalize_generic_signin(
                                request=request,
                                user=user,
                                user_identifier=username,
                                login_provider_name=ldap_provider_name,
                                redirect_url=next_url,
                            )
                    else:
                        login_form.set_password_login_error()
                else:
                    if password_action == "login":
                        user = authenticate(
                            username=login_form.cleaned_data["username"],
                            password=login_form.cleaned_data["password"],
                            provider_name=provider_name,
                            method="password",
                        )
                        if user is None:
                            login_form.set_password_login_error()
                        else:
                            login(request, user)
                            # todo: here we might need to set cookies
                            # for external login sites
                            return HttpResponseRedirect(next_url)
                    elif password_action == "change_password":
                        if request.user.is_authenticated():
                            new_password = login_form.cleaned_data["new_password"]
                            AuthBackend.set_password(
                                user=request.user, password=new_password, provider_name=provider_name
                            )
                            request.user.message_set.create(message=_("Your new password saved"))
                            return HttpResponseRedirect(next_url)
                    else:
                        logging.critical("unknown password action %s" % password_action)
                        raise Http404

            elif login_form.cleaned_data["login_type"] == "openid":
                # initiate communication process
                logging.debug("processing signin with openid submission")

                # todo: make a simple-use wrapper for openid protocol

                sreg_req = sreg.SRegRequest(optional=["nickname", "email"])
                redirect_to = "%s%s?%s" % (
                    get_url_host(request),
                    reverse("user_complete_signin"),
                    urllib.urlencode({"next": next_url}),
                )
                return ask_openid(
                    request,
                    login_form.cleaned_data["openid_url"],
                    redirect_to,
                    on_failure=signin_failure,
                    sreg_request=sreg_req,
                )

            elif login_form.cleaned_data["login_type"] == "oauth":
                try:
                    # this url may need to have "next" piggibacked onto
                    callback_url = reverse("user_complete_oauth_signin")

                    connection = util.OAuthConnection(provider_name, callback_url=callback_url)

                    connection.start()

                    request.session["oauth_token"] = connection.get_token()
                    request.session["oauth_provider_name"] = provider_name
                    request.session["next_url"] = next_url  # special case for oauth

                    oauth_url = connection.get_auth_url(login_only=False)
                    return HttpResponseRedirect(oauth_url)

                except util.OAuthError, e:
                    logging.critical(unicode(e))
                    msg = _(
                        "Unfortunately, there was some problem when "
                        "connecting to %(provider)s, please try again "
                        "or use another provider"
                    ) % {"provider": provider_name}
                    request.user.message_set.create(message=msg)

            elif login_form.cleaned_data["login_type"] == "facebook":
                # have to redirect for consistency
                # there is a requirement that 'complete_signin'
                try:
                    # this call may raise FacebookError
                    user_id = util.get_facebook_user_id(request)

                    user = authenticate(method="facebook", facebook_user_id=user_id)

                    return finalize_generic_signin(
                        request=request,
                        user=user,
                        user_identifier=user_id,
                        login_provider_name=provider_name,
                        redirect_url=next_url,
                    )

                except util.FacebookError, e:
                    logging.critical(unicode(e))
                    msg = _(
                        "Unfortunately, there was some problem when "
                        "connecting to %(provider)s, please try again "
                        "or use another provider"
                    ) % {"provider": "Facebook"}
                    request.user.message_set.create(message=msg)

            elif login_form.cleaned_data["login_type"] == "wordpress_site":
                # here wordpress_site means for a self hosted wordpress blog not a wordpress.com blog
                wp = Client(
                    askbot_settings.WORDPRESS_SITE_URL,
                    login_form.cleaned_data["username"],
                    login_form.cleaned_data["password"],
                )
                try:
                    wp_user = wp.call(GetUserInfo())
                    custom_wp_openid_url = "%s?user_id=%s" % (wp.url, wp_user.user_id)
                    user = authenticate(method="wordpress_site", wordpress_url=wp.url, wp_user_id=wp_user.user_id)
                    return finalize_generic_signin(
                        request=request,
                        user=user,
                        user_identifier=custom_wp_openid_url,
                        login_provider_name=provider_name,
                        redirect_url=next_url,
                    )
                except WpFault, e:
                    logging.critical(unicode(e))
                    msg = _("The login password combination was not correct")
                    request.user.message_set.create(message=msg)
示例#6
0
def signin(request):
    """
    signin page. It manages the legacy authentification (user/password) 
    and openid authentification
    
    url: /signin/
    
    template : authopenid/signin.htm
    """
    logging.debug('in signin view')
    on_failure = signin_failure
    email_feeds_form = askbot_forms.SimpleEmailSubscribeForm()

    #we need a special priority on where to redirect on successful login
    #here:
    #1) url parameter "next" - if explicitly set
    #2) url from django setting LOGIN_REDIRECT_URL
    #3) home page of the forum
    login_redirect_url = getattr(settings, 'LOGIN_REDIRECT_URL', None)
    next_url = get_next_url(request, default = login_redirect_url)
    logging.debug('next url is %s' % next_url)

    if askbot_settings.ALLOW_ADD_REMOVE_LOGIN_METHODS == False \
        and request.user.is_authenticated():
        return HttpResponseRedirect(next_url)

    if next_url == reverse('user_signin'):
        next_url = '%(next)s?next=%(next)s' % {'next': next_url}

    login_form = forms.LoginForm(initial = {'next': next_url})

    #todo: get next url make it sticky if next is 'user_signin'
    if request.method == 'POST':

        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():

            provider_name = login_form.cleaned_data['login_provider_name']
            if login_form.cleaned_data['login_type'] == 'password':

                password_action = login_form.cleaned_data['password_action']
                if askbot_settings.USE_LDAP_FOR_PASSWORD_LOGIN:
                    assert(password_action == 'login')
                    username = login_form.cleaned_data['username']
                    password = login_form.cleaned_data['password']
                    # will be None if authentication fails
                    user = authenticate(
                                    username=username,
                                    password=password,
                                    method = 'ldap'
                                )
                    if user is not None:
                        login(request, user)
                        return HttpResponseRedirect(next_url)
                    else:
                        request.user.message_set.create(_('Incorrect user name or password'))
                        return HttpResponseRedirect(request.path)
                else:
                    if password_action == 'login':
                        user = authenticate(
                                username = login_form.cleaned_data['username'],
                                password = login_form.cleaned_data['password'],
                                provider_name = provider_name,
                                method = 'password'
                            )
                        if user is None:
                            login_form.set_password_login_error()
                        else:
                            login(request, user)
                            #todo: here we might need to set cookies
                            #for external login sites
                            return HttpResponseRedirect(next_url)
                    elif password_action == 'change_password':
                        if request.user.is_authenticated():
                            new_password = \
                                login_form.cleaned_data['new_password']
                            AuthBackend.set_password(
                                            user=request.user,
                                            password=new_password,
                                            provider_name=provider_name
                                        )
                            request.user.message_set.create(
                                        message = _('Your new password saved')
                                    )
                            return HttpResponseRedirect(next_url)
                    else:
                        logging.critical(
                            'unknown password action %s' % password_action
                        )
                        raise Http404

            elif login_form.cleaned_data['login_type'] == 'openid':
                #initiate communication process
                logging.debug('processing signin with openid submission')

                #todo: make a simple-use wrapper for openid protocol

                sreg_req = sreg.SRegRequest(optional=['nickname', 'email'])
                redirect_to = "%s%s?%s" % (
                        get_url_host(request),
                        reverse('user_complete_signin'), 
                        urllib.urlencode({'next':next_url})
                )
                return ask_openid(
                            request, 
                            login_form.cleaned_data['openid_url'],
                            redirect_to,
                            on_failure=signin_failure,
                            sreg_request=sreg_req
                        )

            elif login_form.cleaned_data['login_type'] == 'oauth':
                try:
                    #this url may need to have "next" piggibacked onto
                    callback_url = reverse('user_complete_oauth_signin')

                    connection = util.OAuthConnection(
                                        provider_name,
                                        callback_url = callback_url
                                    )

                    connection.start()

                    request.session['oauth_token'] = connection.get_token()
                    request.session['oauth_provider_name'] = provider_name
                    request.session['next_url'] = next_url#special case for oauth

                    oauth_url = connection.get_auth_url(login_only = False)
                    return HttpResponseRedirect(oauth_url)

                except util.OAuthError, e:
                    logging.critical(unicode(e))
                    msg = _('Unfortunately, there was some problem when '
                            'connecting to %(provider)s, please try again '
                            'or use another provider'
                        ) % {'provider': provider_name}
                    request.user.message_set.create(message = msg)

            elif login_form.cleaned_data['login_type'] == 'facebook':
                #have to redirect for consistency
                #there is a requirement that 'complete_signin'
                try:
                    #this call may raise FacebookError
                    user_id = util.get_facebook_user_id(request)

                    user = authenticate(
                                method = 'facebook',
                                facebook_user_id = user_id
                            )

                    return finalize_generic_signin(
                                    request = request,
                                    user = user,
                                    user_identifier = user_id,
                                    login_provider_name = provider_name,
                                    redirect_url = next_url
                                )

                except util.FacebookError, e:
                    logging.critical(unicode(e))
                    msg = _('Unfortunately, there was some problem when '
                            'connecting to %(provider)s, please try again '
                            'or use another provider'
                        ) % {'provider': 'Facebook'}
                    request.user.message_set.create(message = msg)

            elif login_form.cleaned_data['login_type'] == 'wordpress_site':
                #here wordpress_site means for a self hosted wordpress blog not a wordpress.com blog
                wp = Client(askbot_settings.WORDPRESS_SITE_URL, login_form.cleaned_data['username'], login_form.cleaned_data['password'])
                try:
                    wp_user = wp.call(GetUserInfo())
                    custom_wp_openid_url = '%s?user_id=%s' % (wp.url, wp_user.user_id)
                    user = authenticate(
                            method = 'wordpress_site',
                            wordpress_url = wp.url,
                            wp_user_id = wp_user.user_id 
                           )
                    return finalize_generic_signin(
                                    request = request,
                                    user = user,
                                    user_identifier = custom_wp_openid_url,
                                    login_provider_name = provider_name,
                                    redirect_url = next_url
                                    )
                except WpFault, e:
                    logging.critical(unicode(e))
                    msg = _('The login password combination was not correct')
                    request.user.message_set.create(message = msg)
示例#7
0
def signin(request, template_name="authopenid/signin.html"):
    """
    signin page. It manages the legacy authentification (user/password)
    and openid authentification

    url: /signin/

    template : authopenid/signin.htm
    """
    logging.debug("in signin view")
    on_failure = signin_failure

    # we need a special priority on where to redirect on successful login
    # here:
    # 1) url parameter "next" - if explicitly set
    # 2) url from django setting LOGIN_REDIRECT_URL
    # 3) home page of the forum
    login_redirect_url = getattr(django_settings, "LOGIN_REDIRECT_URL", None)
    next_url = get_next_url(request, default=login_redirect_url)
    logging.debug("next url is %s" % next_url)

    if askbot_settings.ALLOW_ADD_REMOVE_LOGIN_METHODS == False and request.user.is_authenticated():
        return HttpResponseRedirect(next_url)

    if next_url == reverse("user_signin"):
        next_url = "%(next)s?next=%(next)s" % {"next": next_url}

    login_form = forms.LoginForm(initial={"next": next_url})

    # todo: get next url make it sticky if next is 'user_signin'
    if request.method == "POST":

        login_form = forms.LoginForm(request.POST)
        if login_form.is_valid():

            provider_name = login_form.cleaned_data["login_provider_name"]
            if login_form.cleaned_data["login_type"] == "password":

                password_action = login_form.cleaned_data["password_action"]
                if askbot_settings.USE_LDAP_FOR_PASSWORD_LOGIN:
                    assert password_action == "login"
                    username = login_form.cleaned_data["username"]
                    password = login_form.cleaned_data["password"]

                    user = authenticate(username=username, password=password, method="ldap")

                    if user:
                        login(request, user)
                        return HttpResponseRedirect(next_url)
                    else:
                        # try to login again via LDAP
                        user_info = ldap_authenticate(username, password)
                        if user_info["success"]:
                            if askbot_settings.LDAP_AUTOCREATE_USERS:
                                # create new user or
                                user = ldap_create_user(user_info).user
                                user = authenticate(method="force", user_id=user.id)
                                assert user is not None
                                login(request, user)
                                return HttpResponseRedirect(next_url)
                            else:
                                # continue with proper registration
                                ldap_username = user_info["ldap_username"]
                                request.session["email"] = user_info["email"]
                                request.session["ldap_user_info"] = user_info
                                if askbot_settings.AUTOFILL_USER_DATA:
                                    request.session["username"] = ldap_username
                                    request.session["first_name"] = user_info["first_name"]
                                    request.session["last_name"] = user_info["last_name"]
                                return finalize_generic_signin(
                                    request,
                                    login_provider_name="ldap",
                                    user_identifier=ldap_username + "@ldap",
                                    redirect_url=next_url,
                                )
                        else:
                            auth_fail_func_path = getattr(django_settings, "LDAP_AUTHENTICATE_FAILURE_FUNCTION", None)

                            if auth_fail_func_path:
                                auth_fail_func = load_module(auth_fail_func_path)
                                auth_fail_func(user_info, login_form)
                            else:
                                login_form.set_password_login_error()
                            # return HttpResponseRedirect(request.path)
                else:
                    if password_action == "login":
                        user = authenticate(
                            username=login_form.cleaned_data["username"],
                            password=login_form.cleaned_data["password"],
                            provider_name=provider_name,
                            method="password",
                        )
                        if user is None:
                            login_form.set_password_login_error()
                        else:
                            login(request, user)
                            # todo: here we might need to set cookies
                            # for external login sites
                            return HttpResponseRedirect(next_url)
                    elif password_action == "change_password":
                        if request.user.is_authenticated():
                            new_password = login_form.cleaned_data["new_password"]
                            AuthBackend.set_password(
                                user=request.user, password=new_password, provider_name=provider_name
                            )
                            request.user.message_set.create(message=_("Your new password saved"))
                            return HttpResponseRedirect(next_url)
                    else:
                        logging.critical("unknown password action %s" % password_action)
                        raise Http404

            elif login_form.cleaned_data["login_type"] == "openid":
                # initiate communication process
                logging.debug("processing signin with openid submission")

                # todo: make a simple-use wrapper for openid protocol

                sreg_req = sreg.SRegRequest(optional=["nickname", "email"])
                redirect_to = "%s%s?%s" % (
                    get_url_host(request),
                    reverse("user_complete_signin"),
                    urllib.urlencode({"next": next_url}),
                )
                return ask_openid(
                    request,
                    login_form.cleaned_data["openid_url"],
                    redirect_to,
                    on_failure=signin_failure,
                    sreg_request=sreg_req,
                )

            elif login_form.cleaned_data["login_type"] == "oauth":
                try:
                    # this url may need to have "next" piggibacked onto
                    connection = util.OAuthConnection(provider_name, callback_url=reverse("user_complete_oauth_signin"))

                    connection.start()

                    request.session["oauth_token"] = connection.get_token()
                    request.session["oauth_provider_name"] = provider_name
                    request.session["next_url"] = next_url  # special case for oauth

                    oauth_url = connection.get_auth_url(login_only=True)
                    return HttpResponseRedirect(oauth_url)

                except util.OAuthError, e:
                    logging.critical(unicode(e))
                    msg = _(
                        "Unfortunately, there was some problem when "
                        "connecting to %(provider)s, please try again "
                        "or use another provider"
                    ) % {"provider": provider_name}
                    request.user.message_set.create(message=msg)

            elif login_form.cleaned_data["login_type"] == "oauth2":
                try:
                    csrf_token = generate_random_key(length=32)
                    redirect_url = util.get_oauth2_starter_url(provider_name, csrf_token)
                    request.session["oauth2_csrf_token"] = csrf_token
                    request.session["provider_name"] = provider_name
                    return HttpResponseRedirect(redirect_url)
                except util.OAuthError, e:
                    logging.critical(unicode(e))
                    msg = _(
                        "Unfortunately, there was some problem when "
                        "connecting to %(provider)s, please try again "
                        "or use another provider"
                    ) % {"provider": provider_name}
                    request.user.message_set.create(message=msg)

            elif login_form.cleaned_data["login_type"] == "wordpress_site":
                # here wordpress_site means for a self hosted wordpress blog not a wordpress.com blog
                wp = Client(
                    askbot_settings.WORDPRESS_SITE_URL,
                    login_form.cleaned_data["username"],
                    login_form.cleaned_data["password"],
                )
                try:
                    wp_user = wp.call(GetUserInfo())
                    custom_wp_openid_url = "%s?user_id=%s" % (wp.url, wp_user.user_id)
                    user = authenticate(method="wordpress_site", wordpress_url=wp.url, wp_user_id=wp_user.user_id)
                    return finalize_generic_signin(
                        request=request,
                        user=user,
                        user_identifier=custom_wp_openid_url,
                        login_provider_name=provider_name,
                        redirect_url=next_url,
                    )
                except WpFault, e:
                    logging.critical(unicode(e))
                    msg = _("The login password combination was not correct")
                    request.user.message_set.create(message=msg)