Beispiel #1
0
def browserid_verify(request):
    next = request.REQUEST.get('next')
    redirect_to = next or getattr(settings, 'LOGIN_REDIRECT_URL', '/')
    redirect_to_failure = getattr(settings, 'LOGIN_REDIRECT_URL_FAILURE', '/')

    form = BrowserIDForm(data=request.POST)

    if form.is_valid():
        result = verify(form.cleaned_data['assertion'], get_audience(request))
        if result:
            if request.user.is_authenticated():
                # User is already signed in so they must want an email change
                request.user.email = result['email']
                request.user.save()
                return redirect(reverse('users.edit_profile'))
            else:
                # Verified so log in
                email = result['email']
                user = User.objects.filter(email=email)

                if len(user) == 0:
                    form = BrowserIDSignupForm()
                    request.session['browserid-email'] = email
                    return render(request, 'users/browserid_signup.html',
                                  {'email': email, 'next': next, 'form': form})
                else:
                    user = user[0]
                    user.backend = 'django_browserid.auth.BrowserIDBackend'
                    auth.login(request, user)
                    return redirect(redirect_to)

    return redirect(redirect_to_failure)
Beispiel #2
0
def browserid_verify(request):
    next = request.REQUEST.get("next")
    redirect_to = next or getattr(settings, "LOGIN_REDIRECT_URL", "/")
    redirect_to_failure = getattr(settings, "LOGIN_REDIRECT_URL_FAILURE", "/")

    form = BrowserIDForm(data=request.POST)

    if form.is_valid():
        result = verify(form.cleaned_data["assertion"], get_audience(request))
        if result:
            if request.user.is_authenticated():
                # User is already signed in so they must want an email change
                request.user.email = result["email"]
                request.user.save()
                return redirect(reverse("users.edit_profile"))
            else:
                # Verified so log in
                email = result["email"]
                user = User.objects.filter(email=email)

                if len(user) == 0:
                    form = BrowserIDSignupForm()
                    request.session["browserid-email"] = email
                    return render(request, "users/browserid_signup.html", {"email": email, "next": next, "form": form})
                else:
                    user = user[0]
                    user.backend = "django_browserid.auth.BrowserIDBackend"
                    auth.login(request, user)
                    return redirect(redirect_to)

    return redirect(redirect_to_failure)
Beispiel #3
0
    def form_valid(self, form):
        """
        Custom BrowserID verifier for ReMo users
        and vouched mozillians.
        """
        self.assertion = form.cleaned_data['assertion']
        self.audience = get_audience(self.request)
        result = verify(self.assertion, self.audience)
        _is_valid_login = False

        if result:
            if User.objects.filter(email=result['email']).exists():
                _is_valid_login = True
            else:
                try:
                    data = is_vouched(result['email'])
                except BadStatusCodeError:
                    msg = ('Email (%s) authenticated but unable to '
                           'connect to Mozillians to see if you are vouched' %
                           result['email'])
                    return self.login_failure(message=msg)

                if data and data['is_vouched']:
                    _is_valid_login = True
                    user = User.objects.create_user(
                        username=USERNAME_ALGO(data['email']),
                        email=data['email'])
                    # Due to privacy settings, this might be missing
                    if 'full_name' not in data:
                        data['full_name'] = 'Anonymous Mozillian'
                    else:
                        user.userprofile.mozillian_username = data['username']
                        user.userprofile.save()

                    first_name, last_name = (
                        data['full_name'].split(' ', 1)
                        if ' ' in data['full_name']
                        else ('', data['full_name']))
                    user.first_name = first_name
                    user.last_name = last_name
                    user.save()
                    user.groups.add(
                        Group.objects.get(name='Mozillians'))

            if _is_valid_login:
                try:
                    self.user = auth.authenticate(assertion=self.assertion,
                                                  audience=self.audience)
                    auth.login(self.request, self.user)
                except BrowserIDException as e:
                    return self.login_failure(error=e)

                if self.request.user and self.request.user.is_active:
                    return self.login_success()

        return self.login_failure()
Beispiel #4
0
    def form_valid(self, form):
        """
        Custom BrowserID verifier for ReMo users
        and vouched mozillians.
        """
        self.assertion = form.cleaned_data['assertion']
        self.audience = get_audience(self.request)
        result = verify(self.assertion, self.audience)
        _is_valid_login = False

        if result:
            if User.objects.filter(email=result['email']).exists():
                _is_valid_login = True
            else:
                try:
                    data = is_vouched(result['email'])
                except BadStatusCodeError:
                    msg = ('Email (%s) authenticated but unable to '
                           'connect to Mozillians to see if you are vouched' %
                           result['email'])
                    return self.login_failure(message=msg)

                if data and data['is_vouched']:
                    _is_valid_login = True
                    user = User.objects.create_user(username=USERNAME_ALGO(
                        data['email']),
                                                    email=data['email'])
                    # Due to privacy settings, this might be missing
                    if not 'full_name' in data:
                        data['full_name'] = 'Anonymous Mozillian'
                    else:
                        user.userprofile.mozillian_username = data['username']
                        user.userprofile.save()

                    first_name, last_name = (data['full_name'].split(' ', 1)
                                             if ' ' in data['full_name'] else
                                             ('', data['full_name']))
                    user.first_name = first_name
                    user.last_name = last_name
                    user.save()
                    user.groups.add(Group.objects.get(name='Mozillians'))

            if _is_valid_login:
                try:
                    self.user = auth.authenticate(assertion=self.assertion,
                                                  audience=self.audience)
                    auth.login(self.request, self.user)
                except BrowserIDException as e:
                    return self.login_failure(error=e)

                if self.request.user and self.request.user.is_active:
                    return self.login_success()

        return self.login_failure()
Beispiel #5
0
    def form_valid(self, form):
        """Custom mozillians login form validation"""
        self.assertion = form.cleaned_data['assertion']
        self.audience = get_audience(self.request)
        result = verify(self.assertion, self.audience)

        try:
            _is_valid_login = False
            if result:
                if User.objects.filter(email=result['email']).exists():
                    _is_valid_login = True
                else:
                    data = is_vouched(result['email'])
                    if data and data['is_vouched']:
                        _is_valid_login = True
                        user = User.objects.create_user(
                            username=default_username_algo(data['email']),
                            email=data['email'])
                        profile = user.userprofile
                        profile.username = data['username']
                        profile.avatar_url = data['photo']
                        profile.save()

            if _is_valid_login:
                try:
                    self.user = auth.authenticate(assertion=self.assertion,
                                                  audience=self.audience)
                    auth.login(self.request, self.user)

                except BrowserIDException as e:
                    return self.login_failure(e)

                if self.user and self.user.is_active:
                    return self.login_success()

        except BadStatusCodeError:
            msg = ('Email (%s) authenticated but unable to '
                   'connect to Mozillians to see if you are vouched'
                   % result['email'])
            messages.warning(self.request, msg)
            return self.login_failure()

        messages.error(self.request, ('Login failed. Make sure you are using '
                                      'a valid email address and you are '
                                      'a vouched Mozillian.'))
        return self.login_failure()
Beispiel #6
0
def mozilla_browserid_verify(request):
    """
    Custom BrowserID verifier for ReMo users
    and vouched mozillians.
    """
    form = BrowserIDForm(request.POST)
    if form.is_valid():
        assertion = form.cleaned_data['assertion']
        audience = get_audience(request)
        result = verify(assertion, audience)
        try:
            _is_valid_login = False
            if result:
                if User.objects.filter(email=result['email']).exists():
                    _is_valid_login = True
                else:
                    data = is_vouched(result['email'])
                    if data and data['is_vouched']:
                        _is_valid_login = True
                        user = User.objects.create_user(
                            username=USERNAME_ALGO(data['email']),
                            email=data['email'])

                        first_name, last_name = (
                            data['full_name'].split(' ', 1)
                            if ' ' in data['full_name']
                            else ('', data['full_name']))
                        user.first_name = first_name
                        user.last_name = last_name
                        user.save()
                        user.groups.add(Group.objects.get(name='Mozillians'))

            if _is_valid_login:
                user = auth.authenticate(assertion=assertion,
                                         audience=audience)
                auth.login(request, user)
                return redirect('dashboard')

        except BadStatusCodeError:
            message = ('Email (%s) authenticated but unable to '
                       'connect to Mozillians to see if you are vouched' %
                       result['email'])
            return login_failed(request, message)

    return redirect(settings.LOGIN_REDIRECT_URL_FAILURE)
Beispiel #7
0
def mozilla_browserid_verify(request):
    """
    Custom BrowserID verifier for ReMo users
    and vouched mozillians.
    """
    form = BrowserIDForm(request.POST)
    if form.is_valid():
        assertion = form.cleaned_data['assertion']
        audience = get_audience(request)
        result = verify(assertion, audience)
        try:
            _is_valid_login = False
            if result:
                if User.objects.filter(email=result['email']).exists():
                    _is_valid_login = True
                else:
                    data = is_vouched(result['email'])
                    if data and data['is_vouched']:
                        _is_valid_login = True
                        user = User.objects.create_user(username=USERNAME_ALGO(
                            data['email']),
                                                        email=data['email'])

                        first_name, last_name = (data['full_name'].split(
                            ' ', 1) if ' ' in data['full_name'] else
                                                 ('', data['full_name']))
                        user.first_name = first_name
                        user.last_name = last_name
                        user.save()
                        user.groups.add(Group.objects.get(name='Mozillians'))

            if _is_valid_login:
                user = auth.authenticate(assertion=assertion,
                                         audience=audience)
                auth.login(request, user)
                return redirect('dashboard')

        except BadStatusCodeError:
            message = ('Email (%s) authenticated but unable to '
                       'connect to Mozillians to see if you are vouched' %
                       result['email'])
            return login_failed(request, message)

    return redirect(settings.LOGIN_REDIRECT_URL_FAILURE)
Beispiel #8
0
    def form_valid(self, form):
        """Custom mozillians login form validation"""
        self.assertion = form.cleaned_data["assertion"]
        self.audience = get_audience(self.request)
        result = verify(self.assertion, self.audience)

        try:
            _is_valid_login = False
            if result:
                if User.objects.filter(email=result["email"]).exists():
                    _is_valid_login = True
                else:
                    data = is_vouched(result["email"])
                    if data and data["is_vouched"]:
                        _is_valid_login = True
                        user = User.objects.create_user(
                            username=default_username_algo(data["email"]), email=data["email"]
                        )
                        MozillianProfile.objects.create(user=user, username=data["username"], avatar_url=data["photo"])

            if _is_valid_login:
                try:
                    self.user = auth.authenticate(assertion=self.assertion, audience=self.audience)
                    auth.login(self.request, self.user)

                except BrowserIDException as e:
                    return self.login_failure(e)

                if self.user and self.user.is_active:
                    return self.login_success()

        except BadStatusCodeError:
            msg = (
                "Email (%s) authenticated but unable to "
                "connect to Mozillians to see if you are vouched" % result["email"]
            )
            messages.warning(self.request, msg)
            return self.login_failure()

        messages.error(
            self.request,
            ("Login failed. Make sure you are using " "a valid email address and you are " "a vouched Mozillian."),
        )
        return self.login_failure()
Beispiel #9
0
def personaregister(request):
    if request.method == "POST":
        form = BrowserIDForm(data=request.POST)
        user = request.user
        # I've taken the - not - from the docs out of the next line
        if form.is_valid():
            result = verify(form.cleaned_data['assertion'], get_audience(request))
            if result:
                if is_lazy_user(user):
                    if User.objects.filter(email=result[u'email']):
                        existinguser = User.objects.get(email=result[u'email'])
                        existinguser.backend = 'django_browserid.auth.BrowserIDBackend' 
                        login(request, existinguser)
                    else:
                        foo = LazyUser.objects.get(user=user)
                        foo.delete()
                        user.email = result[u'email']
                        user.save()
    return redirect('/')
Beispiel #10
0
def browserid_verify(request):
    next = request.REQUEST.get('next')
    redirect_to = next or getattr(settings, 'LOGIN_REDIRECT_URL', '/')
    redirect_to_failure = getattr(settings, 'LOGIN_REDIRECT_URL_FAILURE', '/')

    form = BrowserIDForm(data=request.POST)

    if form.is_valid():
        result = verify(form.cleaned_data['assertion'], get_audience(request))
        if result:
            if request.user.is_authenticated() and request.user.email != result['email']:
                # User is already signed and wants to change their email.
                request.user.email = result['email']
                request.user.save()
                return redirect(reverse('users.edit_profile'))
            else:
                # Verified so log in
                email = result['email']
                user = User.objects.filter(email=email)
                contributor = 'contributor' in request.POST

                if len(user) == 0:
                    # Add the email to the session and redirect to signup
                    request.session['browserid-email'] = email
                    signup_url = reverse('users.browserid_signup')
                    return redirect('%s?%s' % (signup_url,
                                               urlencode({'next': next})))
                else:
                    user = user[0]
                    user.backend = 'django_browserid.auth.BrowserIDBackend'

                    if contributor:
                        add_to_contributors(request, user)

                    auth.login(request, user)
                    return redirect(redirect_to)

    return redirect(redirect_to_failure)
Beispiel #11
0
def browserid_verify(request):
    next = request.REQUEST.get("next")
    redirect_to = next or getattr(settings, "LOGIN_REDIRECT_URL", "/")
    redirect_to_failure = getattr(settings, "LOGIN_REDIRECT_URL_FAILURE", "/")

    form = BrowserIDForm(data=request.POST)

    if form.is_valid():
        result = verify(form.cleaned_data["assertion"], get_audience(request))
        if result:
            if request.user.is_authenticated():
                # User is already signed in so they must want an email change
                request.user.email = result["email"]
                request.user.save()
                return redirect(reverse("users.edit_profile"))
            else:
                # Verified so log in
                email = result["email"]
                user = User.objects.filter(email=email)
                contributor = "contributor" in request.POST

                if len(user) == 0:
                    # Add the email to the session and redirect to signup
                    request.session["browserid-email"] = email
                    signup_url = reverse("users.browserid_signup")
                    return redirect("%s?%s" % (signup_url, urlencode({"next": next})))
                else:
                    user = user[0]
                    user.backend = "django_browserid.auth.BrowserIDBackend"

                    if contributor:
                        add_to_contributors(request, user)

                    auth.login(request, user)
                    return redirect(redirect_to)

    return redirect(redirect_to_failure)
Beispiel #12
0
def browserid_authenticate(request, assertion, is_native=False,
                           browserid_audience=get_audience):
    """
    Verify a BrowserID login attempt. If the BrowserID assertion is
    good, but no account exists, create one.

    """
    url = settings.BROWSERID_VERIFICATION_URL

    # We must always force the Firefox OS identity provider. This is because
    # we are sometimes allowing unverified assertions and you can't mix that
    # feature with bridged IdPs. See bug 910938.
    extra_params = {}
    if settings.UNVERIFIED_ISSUER:
        extra_params['experimental_forceIssuer'] = settings.UNVERIFIED_ISSUER

    if is_native:
        # When persona is running native on B2G then we can allow unverified
        # assertions.
        url = settings.NATIVE_BROWSERID_VERIFICATION_URL
        extra_params['experimental_allowUnverified'] = 'true'

    log.debug('Verifying Persona at %s, audience: %s, '
              'extra_params: %s' % (url, browserid_audience, extra_params))
    result = verify(assertion, browserid_audience,
                    url=url, extra_params=extra_params)
    if not result:
        return None, _('Persona authentication failure.')

    if 'unverified-email' in result:
        email = result['unverified-email']
        verified = False
    else:
        email = result['email']
        verified = True

    try:
        profile = UserProfile.objects.filter(email=email)[0]
    except IndexError:
        profile = None

    if profile:
        # Added due to bug 905984. It's possible to have a UserProfile
        # that has no corresponding User object.
        if profile.user is None:
            profile.create_django_user(
                backend='django_browserid.auth.BrowserIDBackend')
        if profile.is_verified and not verified:
            # An attempt to log in to a verified address with an unverified
            # assertion is a very bad thing. However, the same email address
            # can legitimately be used on the site on desktop and be verified
            # whilst be used on b2g and be unverified. We are forcing the
            # issuer, so this shouldn't be an issue.
            #
            # Blame kumar. Or cvan. Or deal with it.
            log.debug('Verified user %s attempted to log in with an '
                      'unverified assertion!' % profile)
        else:
            profile.is_verified = verified
            profile.save()

        backend = 'django_browserid.auth.BrowserIDBackend'
        if getattr(profile.user, 'backend', None) != backend:
            profile.user.backend = backend
            profile.user.save()

        return profile, None

    username = autocreate_username(email.partition('@')[0])
    source = (amo.LOGIN_SOURCE_MMO_BROWSERID if settings.MARKETPLACE else
              amo.LOGIN_SOURCE_AMO_BROWSERID)
    profile = UserProfile.objects.create(username=username, email=email,
                                         source=source, display_name=username,
                                         is_verified=verified)
    profile.create_django_user(
        backend='django_browserid.auth.BrowserIDBackend')
    log_cef('New Account', 5, request, username=username,
            signature='AUTHNOTICE',
            msg='User created a new account (from Persona)')
    record_action('new-user', request)
    return profile, None
Beispiel #13
0
def browserid_authenticate(request, assertion, is_native=False):
    """
    Verify a BrowserID login attempt. If the BrowserID assertion is
    good, but no account exists, create one.

    """
    url = settings.BROWSERID_VERIFICATION_URL
    extra_params = None
    if is_native:
        # When persona is running native on B2G then we need to
        # verify assertions with the right service.
        # We also need to force the appropriate issuer
        # for potentially unverified emails.
        url = settings.NATIVE_BROWSERID_VERIFICATION_URL
        extra_params = {'issuer': settings.UNVERIFIED_ISSUER,
                        'allowUnverified': 'true'}

    audience = get_audience(request)
    log.debug('Verifying Persona at %s, audience: %s, '
              'extra_params: %s' % (url, audience, extra_params))
    result = verify(assertion, audience,
                    url=url, extra_params=extra_params)
    if not result:
        return None, _('Persona authentication failure.')

    if 'unverified-email' in result:
        email = result['unverified-email']
        verified = False
    else:
        email = result['email']
        verified = True

    try:
        profile = UserProfile.objects.filter(email=email)[0]
    except IndexError:
        profile = None

    if profile:
        if profile.is_verified and not verified:
            # An attempt to log in to a verified address with an unverified
            # assertion is a very bad thing. However, the same email address
            # can legitimately be used on the site on desktop and be verified
            # whilst be used on b2g and be unverified. We are forcing the
            # issuer, so this shouldn't be an issue.
            #
            # Blame kumar. Or cvan. Or deal with it.
            log.debug('Verified user %s attempted to log in with an '
                      'unverified assertion!' % profile)
        else:
            profile.is_verified = verified
            profile.save()

        backend = 'django_browserid.auth.BrowserIDBackend'
        if getattr(profile.user, 'backend', None) != backend:
            profile.user.backend = backend
            profile.user.save()

        return profile, None

    username = autocreate_username(email.partition('@')[0])
    source = (amo.LOGIN_SOURCE_MMO_BROWSERID if settings.MARKETPLACE else
              amo.LOGIN_SOURCE_AMO_BROWSERID)
    profile = UserProfile.objects.create(username=username, email=email,
                                         source=source, display_name=username,
                                         is_verified=verified)
    profile.create_django_user(
        backend='django_browserid.auth.BrowserIDBackend')
    log_cef('New Account', 5, request, username=username,
            signature='AUTHNOTICE',
            msg='User created a new account (from Persona)')
    return profile, None
Beispiel #14
0
def browserid_authenticate(request, assertion, is_mobile=False, browserid_audience=get_audience):
    """
    Verify a BrowserID login attempt. If the BrowserID assertion is
    good, but no account exists, create one.

    """
    url = settings.BROWSERID_VERIFICATION_URL

    # We must always force the Firefox OS identity provider. This is because
    # we are sometimes allowing unverified assertions and you can't mix that
    # feature with bridged IdPs. See bug 910938.
    extra_params = {}
    if settings.UNVERIFIED_ISSUER:
        extra_params["experimental_forceIssuer"] = settings.UNVERIFIED_ISSUER

    if is_mobile:
        # When persona is running in a mobile OS then we can allow unverified
        # assertions.
        url = settings.NATIVE_BROWSERID_VERIFICATION_URL
        extra_params["experimental_allowUnverified"] = "true"

    log.debug("Verifying Persona at %s, audience: %s, " "extra_params: %s" % (url, browserid_audience, extra_params))
    result = verify(assertion, browserid_audience, url=url, extra_params=extra_params)
    if not result:
        return None, _("Persona authentication failure.")

    if "unverified-email" in result:
        email = result["unverified-email"]
        verified = False
    else:
        email = result["email"]
        verified = True

    try:
        profile = UserProfile.objects.filter(email=email)[0]
    except IndexError:
        profile = None

    if profile:
        # Added due to bug 905984. It's possible to have a UserProfile
        # that has no corresponding User object.
        if profile.user is None:
            profile.create_django_user(backend="django_browserid.auth.BrowserIDBackend")
        if profile.is_verified and not verified:
            # An attempt to log in to a verified address with an unverified
            # assertion is a very bad thing. Don't let that happen.
            log.debug("Verified user %s attempted to log in with an " "unverified assertion!" % profile)
            return None, _("Please use the verified email for this account.")
        else:
            profile.is_verified = verified
            profile.save()

        backend = "django_browserid.auth.BrowserIDBackend"
        if getattr(profile.user, "backend", None) != backend:
            profile.user.backend = backend
            profile.user.save()

        return profile, None

    username = autocreate_username(email.partition("@")[0])
    source = amo.LOGIN_SOURCE_MMO_BROWSERID if settings.MARKETPLACE else amo.LOGIN_SOURCE_AMO_BROWSERID
    profile = UserProfile.objects.create(
        username=username, email=email, source=source, display_name=username, is_verified=verified
    )
    profile.create_django_user(backend="django_browserid.auth.BrowserIDBackend")
    log_cef(
        "New Account",
        5,
        request,
        username=username,
        signature="AUTHNOTICE",
        msg="User created a new account (from Persona)",
    )
    if settings.MARKETPLACE:
        record_action("new-user", request)
    return profile, None
Beispiel #15
0
def browserid_authenticate(request,
                           assertion,
                           is_mobile=False,
                           browserid_audience=get_audience):
    """
    Verify a BrowserID login attempt. If the BrowserID assertion is
    good, but no account exists, create one.

    """
    url = settings.BROWSERID_VERIFICATION_URL

    # We must always force the Firefox OS identity provider. This is because
    # we are sometimes allowing unverified assertions and you can't mix that
    # feature with bridged IdPs. See bug 910938.
    extra_params = {}
    if settings.UNVERIFIED_ISSUER:
        extra_params['experimental_forceIssuer'] = settings.UNVERIFIED_ISSUER

    if is_mobile:
        # When persona is running in a mobile OS then we can allow unverified
        # assertions.
        url = settings.NATIVE_BROWSERID_VERIFICATION_URL
        extra_params['experimental_allowUnverified'] = 'true'

    log.debug('Verifying Persona at %s, audience: %s, '
              'extra_params: %s' % (url, browserid_audience, extra_params))
    result = verify(assertion,
                    browserid_audience,
                    url=url,
                    extra_params=extra_params)
    if not result:
        return None, _('Persona authentication failure.')

    if 'unverified-email' in result:
        email = result['unverified-email']
        verified = False
    else:
        email = result['email']
        verified = True

    try:
        profile = UserProfile.objects.filter(email=email)[0]
    except IndexError:
        profile = None

    if profile:
        if profile.is_verified and not verified:
            # An attempt to log in to a verified address with an unverified
            # assertion is a very bad thing. Don't let that happen.
            log.debug('Verified user %s attempted to log in with an '
                      'unverified assertion!' % profile)
            return None, _('Please use the verified email for this account.')
        else:
            profile.is_verified = verified
            profile.save()

        return profile, None

    username = autocreate_username(email.partition('@')[0])
    source = amo.LOGIN_SOURCE_AMO_BROWSERID
    profile = UserProfile.objects.create(username=username,
                                         email=email,
                                         source=source,
                                         display_name=username,
                                         is_verified=verified)
    log_cef('New Account',
            5,
            request,
            username=username,
            signature='AUTHNOTICE',
            msg='User created a new account (from Persona)')
    return profile, None
Beispiel #16
0
def browserid_authenticate(request,
                           assertion,
                           is_native=False,
                           browserid_audience=get_audience):
    """
    Verify a BrowserID login attempt. If the BrowserID assertion is
    good, but no account exists, create one.

    """
    url = settings.BROWSERID_VERIFICATION_URL
    extra_params = None
    if is_native:
        # When persona is running native on B2G then we need to
        # verify assertions with the right service.
        # We also need to force the appropriate issuer
        # for potentially unverified emails.
        url = settings.NATIVE_BROWSERID_VERIFICATION_URL
        extra_params = {
            'experimental_forceIssuer': settings.UNVERIFIED_ISSUER or False,
            'experimental_allowUnverified': 'true'
        }

    log.debug('Verifying Persona at %s, audience: %s, '
              'extra_params: %s' % (url, browserid_audience, extra_params))
    result = verify(assertion,
                    browserid_audience,
                    url=url,
                    extra_params=extra_params)
    if not result:
        return None, _('Persona authentication failure.')

    if 'unverified-email' in result:
        email = result['unverified-email']
        verified = False
    else:
        email = result['email']
        verified = True

    try:
        profile = UserProfile.objects.filter(email=email)[0]
    except IndexError:
        profile = None

    if profile:
        if profile.is_verified and not verified:
            # An attempt to log in to a verified address with an unverified
            # assertion is a very bad thing. However, the same email address
            # can legitimately be used on the site on desktop and be verified
            # whilst be used on b2g and be unverified. We are forcing the
            # issuer, so this shouldn't be an issue.
            #
            # Blame kumar. Or cvan. Or deal with it.
            log.debug('Verified user %s attempted to log in with an '
                      'unverified assertion!' % profile)
        else:
            profile.is_verified = verified
            profile.save()

        backend = 'django_browserid.auth.BrowserIDBackend'
        if getattr(profile.user, 'backend', None) != backend:
            profile.user.backend = backend
            profile.user.save()

        return profile, None

    username = autocreate_username(email.partition('@')[0])
    source = (amo.LOGIN_SOURCE_MMO_BROWSERID
              if settings.MARKETPLACE else amo.LOGIN_SOURCE_AMO_BROWSERID)
    profile = UserProfile.objects.create(username=username,
                                         email=email,
                                         source=source,
                                         display_name=username,
                                         is_verified=verified)
    profile.create_django_user(
        backend='django_browserid.auth.BrowserIDBackend')
    log_cef('New Account',
            5,
            request,
            username=username,
            signature='AUTHNOTICE',
            msg='User created a new account (from Persona)')
    record_action('new-user', request)
    return profile, None
Beispiel #17
0
def browserid_authenticate(request,
                           assertion,
                           is_mobile=False,
                           browserid_audience=get_audience):
    """
    Verify a BrowserID login attempt. If the BrowserID assertion is
    good, but no account exists, create one.

    """
    url = settings.BROWSERID_VERIFICATION_URL

    # We must always force the Firefox OS identity provider. This is because
    # we are sometimes allowing unverified assertions and you can't mix that
    # feature with bridged IdPs. See bug 910938.
    extra_params = {}
    if settings.UNVERIFIED_ISSUER:
        extra_params['experimental_forceIssuer'] = settings.UNVERIFIED_ISSUER

    if is_mobile:
        # When persona is running in a mobile OS then we can allow unverified
        # assertions.
        url = settings.NATIVE_BROWSERID_VERIFICATION_URL
        extra_params['experimental_allowUnverified'] = 'true'

    log.debug('Verifying Persona at %s, audience: %s, '
              'extra_params: %s' % (url, browserid_audience, extra_params))
    result = verify(assertion,
                    browserid_audience,
                    url=url,
                    extra_params=extra_params)
    if not result:
        return None, _('Persona authentication failure.')

    if 'unverified-email' in result:
        email = result['unverified-email']
        verified = False
    else:
        email = result['email']
        verified = True

    try:
        profile = UserProfile.objects.filter(email=email)[0]
    except IndexError:
        profile = None

    if profile:
        # Added due to bug 905984. It's possible to have a UserProfile
        # that has no corresponding User object.
        if profile.user is None:
            profile.create_django_user(
                backend='django_browserid.auth.BrowserIDBackend')
        if profile.is_verified and not verified:
            # An attempt to log in to a verified address with an unverified
            # assertion is a very bad thing. However, the same email address
            # can legitimately be used on the site on desktop and be verified
            # whilst be used on b2g and be unverified. We are forcing the
            # issuer, so this shouldn't be an issue.
            #
            # Blame kumar. Or cvan. Or deal with it.
            log.debug('Verified user %s attempted to log in with an '
                      'unverified assertion!' % profile)
        else:
            profile.is_verified = verified
            profile.save()

        backend = 'django_browserid.auth.BrowserIDBackend'
        if getattr(profile.user, 'backend', None) != backend:
            profile.user.backend = backend
            profile.user.save()

        return profile, None

    username = autocreate_username(email.partition('@')[0])
    source = (amo.LOGIN_SOURCE_MMO_BROWSERID
              if settings.MARKETPLACE else amo.LOGIN_SOURCE_AMO_BROWSERID)
    profile = UserProfile.objects.create(username=username,
                                         email=email,
                                         source=source,
                                         display_name=username,
                                         is_verified=verified)
    profile.create_django_user(
        backend='django_browserid.auth.BrowserIDBackend')
    log_cef('New Account',
            5,
            request,
            username=username,
            signature='AUTHNOTICE',
            msg='User created a new account (from Persona)')
    record_action('new-user', request)
    return profile, None
Beispiel #18
0
def browserid_authenticate(request, assertion, is_mobile=False,
                           browserid_audience=get_audience):
    """
    Verify a BrowserID login attempt. If the BrowserID assertion is
    good, but no account exists, create one.

    """
    url = settings.BROWSERID_VERIFICATION_URL

    # We must always force the Firefox OS identity provider. This is because
    # we are sometimes allowing unverified assertions and you can't mix that
    # feature with bridged IdPs. See bug 910938.
    extra_params = {}
    if settings.UNVERIFIED_ISSUER:
        extra_params['experimental_forceIssuer'] = settings.UNVERIFIED_ISSUER

    if is_mobile:
        # When persona is running in a mobile OS then we can allow unverified
        # assertions.
        url = settings.NATIVE_BROWSERID_VERIFICATION_URL
        extra_params['experimental_allowUnverified'] = 'true'

    log.debug('Verifying Persona at %s, audience: %s, '
              'extra_params: %s' % (url, browserid_audience, extra_params))
    result = verify(assertion, browserid_audience,
                    url=url, extra_params=extra_params)
    if not result:
        return None, _('Persona authentication failure.')

    if 'unverified-email' in result:
        email = result['unverified-email']
        verified = False
    else:
        email = result['email']
        verified = True

    try:
        profile = UserProfile.objects.filter(email=email)[0]
    except IndexError:
        profile = None

    if profile:
        if profile.is_verified and not verified:
            # An attempt to log in to a verified address with an unverified
            # assertion is a very bad thing. Don't let that happen.
            log.debug('Verified user %s attempted to log in with an '
                      'unverified assertion!' % profile)
            return None, _('Please use the verified email for this account.')
        else:
            profile.is_verified = verified
            profile.save()

        return profile, None

    username = autocreate_username(email.partition('@')[0])
    source = amo.LOGIN_SOURCE_MMO_BROWSERID
    profile = UserProfile.objects.create(username=username, email=email,
                                         source=source, display_name=username,
                                         is_verified=verified)
    log_cef('New Account', 5, request, username=username,
            signature='AUTHNOTICE',
            msg='User created a new account (from Persona)')
    record_action('new-user', request)

    return profile, None