Esempio n. 1
0
def verify(request, template=None):
    """Verify BrowserID assertion, and return whether a user is registered."""
    log.debug("Verify BrowserID assertion.")

    if request.method != "POST":
        raise Http404

    assertion = request.POST["assertion"]
    if assertion is None:
        return HttpResponseBadRequest()

    verification = browserid_verify(assertion, get_audience(request))
    if not verification:
        return HttpResponseForbidden()

    response_data = {"registered": False, "browserid": verification}
    user = auth.authenticate(assertion=assertion, audience=get_audience(request))
    if user is not None:
        auth.login(request, user)
        response_data = {
            "registered": True,
            "browserid": verification,
            "manager": user.has_perm("base.can_manage"),
            "localizer": user.has_perm("base.can_localize"),
        }

    return HttpResponse(json.dumps(response_data), mimetype="application/json")
Esempio n. 2
0
def verify(request, template=None):
    """Verify BrowserID assertion, and return whether a user is registered."""
    log.debug("Verify BrowserID assertion.")

    if request.method != 'POST':
        raise Http404

    assertion = request.POST['assertion']
    if assertion is None:
        return HttpResponseBadRequest()

    verification = browserid_verify(assertion, get_audience(request))
    if not verification:
        return HttpResponseForbidden()

    response = 'error'
    user = auth.authenticate(assertion=assertion, audience=get_audience(request))
    if user is not None:
        auth.login(request, user)
        response = {'browserid': verification,
            'manager': user.has_perm('base.can_manage'),
            'localizer': user.has_perm('base.can_localize')
        }

    return HttpResponse(json.dumps(response), mimetype='application/json')
Esempio n. 3
0
def verify(request, template=None):
    """Verify BrowserID assertion, and return whether a user is registered."""
    log.debug("Verify BrowserID assertion.")

    if request.method != 'POST':
        log.error("Non-POST request")
        raise Http404

    assertion = request.POST['assertion']
    if assertion is None:
        return HttpResponseBadRequest()

    verification = browserid_verify(assertion, get_audience(request))
    if not verification:
        return HttpResponseForbidden()

    response = "error"
    user = authenticate(assertion=assertion, audience=get_audience(request))

    if user is not None:
        login(request, user)

        # Check for permission to localize if not granted on every login
        if not user.has_perm('base.can_localize'):
            user = User.objects.get(username=user)
            utils.add_can_localize(user)

        response = {
            'browserid': verification,
            'manager': user.has_perm('base.can_manage'),
        }

    return HttpResponse(json.dumps(response), mimetype='application/json')
Esempio n. 4
0
def verify(request, template=None):
    """Verify BrowserID assertion, and return whether a user is registered."""
    log.debug("Verify BrowserID assertion.")

    if request.method != 'POST':
        log.error("Non-POST request")
        raise Http404

    assertion = request.POST['assertion']
    if assertion is None:
        return HttpResponseBadRequest()

    verification = browserid_verify(assertion, get_audience(request))
    if not verification:
        return HttpResponseForbidden()

    response = "error"
    user = authenticate(assertion=assertion, audience=get_audience(request))

    if user is not None:
        login(request, user)

        # Check for permission to localize if not granted on every login
        if not user.has_perm('base.can_localize'):
            user = User.objects.get(username=user)
            utils.add_can_localize(user)

        response = {
            'browserid': verification,
            'manager': user.has_perm('base.can_manage'),
        }

    return HttpResponse(json.dumps(response), mimetype='application/json')
Esempio n. 5
0
def reverify(request):
    form = BrowserIDForm(data=request.POST)
    if form.is_valid():
        url = settings.BROWSERID_VERIFICATION_URL
        audience = get_audience(request)
        extra_params = {
            'experimental_forceIssuer': settings.BROWSERID_UNVERIFIED_ISSUER,
            'experimental_forceAuthentication': 'true',
            'experimental_allowUnverified': 'true'
        }

        log.info('Re-verifying Persona assertion. url: %s, audience: %s, '
                 'extra_params: %s' % (url, audience, extra_params))
        result = verify_assertion(form.cleaned_data['assertion'], audience,
                                  extra_params)

        log.info('Reverify got result: %s' % result)
        if result:
            logged_user = request.session.get('uuid')
            email = result.get('unverified-email', result.get('email'))
            reverified_user = get_uuid(email)
            if logged_user and logged_user != reverified_user:
                # TODO: Should we try to support this?
                raise ValueError('User %r tried to reverify as '
                                 'new email: %s' % (logged_user, email))
            request.session['was_reverified'] = True

            return {'user_hash': reverified_user}

        log.error('Persona assertion failed.')

    request.session.clear()
    return http.HttpResponseBadRequest()
Esempio n. 6
0
def verify(request):
    form = BrowserIDForm(data=request.POST)
    if form.is_valid():
        url = settings.BROWSERID_VERIFICATION_URL
        audience = get_audience(request)
        extra_params = {
            'experimental_forceIssuer': settings.BROWSERID_UNVERIFIED_ISSUER,
            'experimental_allowUnverified': 'true'
        }
        assertion = form.cleaned_data['assertion']

        log.info('verifying Persona assertion. url: %s, audience: %s, '
                 'extra_params: %s, assertion: %s' %
                 (url, audience, extra_params, assertion))
        result = verify_assertion(assertion, audience, extra_params)
        if result:
            log.info('Persona assertion ok: %s' % result)
            email = result.get('unverified-email', result.get('email'))
            user_hash = set_user(request, email)
            redirect_url = check_pin_status(request)
            return {
                'needs_redirect': redirect_url is not None,
                'redirect_url': redirect_url,
                'user_hash': user_hash
            }

        log.error('Persona assertion failed.')

    request.session.flush()
    return http.HttpResponseBadRequest()
Esempio n. 7
0
def verify(request):
    form = BrowserIDForm(data=request.POST)
    if form.is_valid():
        url = settings.BROWSERID_VERIFICATION_URL
        audience = get_audience(request)
        extra_params = {'forceIssuer': settings.BROWSERID_UNVERIFIED_ISSUER,
                        'allowUnverified': 'true'}
        assertion = form.cleaned_data['assertion']

        log.info('verifying Persona assertion. url: %s, audience: %s, '
                 'extra_params: %s, assertion: %s' % (url, audience,
                                                      extra_params, assertion))
        result = verify_assertion(assertion, audience, extra_params)
        if result:
            log.info('Persona assertion ok: %s' % result)
            email = result.get('unverified-email', result.get('email'))
            user_hash = set_user(request, email)
            return {'has_pin': request.session.get('uuid_has_pin'),
                    'pin_create': reverse('pin.create'),
                    'user_hash': user_hash}

        log.error('Persona assertion failed.')

    request.session.clear()
    return http.HttpResponseBadRequest()
Esempio n. 8
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)
Esempio n. 9
0
def verify(request):
    form = BrowserIDForm(data=request.POST)
    if form.is_valid():
        url = settings.BROWSERID_VERIFICATION_URL
        audience = get_audience(request)
        extra_params = {'experimental_forceIssuer': settings.BROWSERID_UNVERIFIED_ISSUER,
                        'experimental_allowUnverified': 'true'}
        assertion = form.cleaned_data['assertion']

        log.info('verifying Persona assertion. url: %s, audience: %s, '
                 'extra_params: %s, assertion: %s' % (url, audience,
                                                      extra_params, assertion))
        result = verify_assertion(assertion, audience, extra_params)
        if result:
            log.info('Persona assertion ok: %s' % result)
            email = result.get('unverified-email', result.get('email'))
            user_hash = set_user(request, email)
            redirect_url = check_pin_status(request)
            return {
                'needs_redirect': redirect_url is not None,
                'redirect_url': redirect_url,
                'user_hash': user_hash
            }

        log.error('Persona assertion failed.')

    request.session.flush()
    return http.HttpResponseBadRequest()
Esempio n. 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():
                # 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)
Esempio n. 11
0
def login(request):
    assertion = request.POST.get('assertion')
    if assertion is not None:
        audience = get_audience(request)
        user = auth.authenticate(assertion=assertion, audience=audience)
        if user and user.is_active:
            auth.login(request, user)
    return get_user(request)
Esempio n. 12
0
def verify(request, assertion=None):
    """Verifies a BrowserID assertion and caches it in the user's session."""
    if assertion:
        verification = browserid_verify(assertion, get_audience(request))
        request.session[SESSION_VERIFY] = verification
    else:
        verification = request.session.get(SESSION_VERIFY)

    return verification or None
Esempio n. 13
0
File: views.py Progetto: seocam/remo
    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()
Esempio n. 14
0
def verify(request, template=None):
    """Verify BrowserID assertion, and return whether a user is registered."""
    log.debug("Verify BrowserID assertion.")

    assertion = request.POST['assertion']
    if assertion is None:
        return HttpResponseBadRequest()

    verification = browserid_verify(assertion, get_audience(request))
    if not verification:
        return HttpResponseForbidden()

    response_data = {'registered': False, 'browserid': verification}
    user = auth.authenticate(assertion=assertion, audience=get_audience(request))
    if user is not None:
        auth.login(request, user)
        response_data = {'registered': True, 'browserid': verification}

    return HttpResponse(json.dumps(response_data), mimetype='application/json')
Esempio n. 15
0
def verify(request):
    form = BrowserIDForm(data=request.POST)
    if form.is_valid():
        log.info("verifying assertion")
        result = verify_assertion(form.cleaned_data["assertion"], get_audience(request))
        if result:
            log.info("assertion ok: %s" % result)
            return http.HttpResponse("ok")

    return http.HttpResponseBadRequest()
Esempio n. 16
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()
Esempio n. 17
0
def verify(request, template=None):
    """Verify BrowserID assertion, and return whether a user is registered."""
    log.debug("Verify BrowserID assertion.")

    assertion = request.POST['assertion']
    if assertion is None:
        return HttpResponseBadRequest()

    verification = browserid_verify(assertion, get_audience(request))
    if not verification:
        return HttpResponseForbidden()

    response_data = {'registered': False, 'browserid': verification}
    user = auth.authenticate(assertion=assertion,
                             audience=get_audience(request))
    if user is not None:
        auth.login(request, user)
        response_data = {'registered': True, 'browserid': verification}

    return HttpResponse(json.dumps(response_data), mimetype='application/json')
Esempio n. 18
0
def verify(request):
    form = BrowserIDForm(data=request.POST)
    if form.is_valid():
        log.info('verifying assertion')
        result = verify_assertion(form.cleaned_data['assertion'],
                                  get_audience(request))
        if result:
            log.info('assertion ok: %s' % result)
            set_user(request, result['email'])
            return {'has_pin': request.session['uuid_has_pin'],
                    'pin_create': reverse('pin.create')}

    request.session.clear()
    return http.HttpResponseBadRequest()
Esempio n. 19
0
    def form_valid(self, form):
        """Handles the return post request from the browserID form and puts
        interesting variables into the class. If everything checks out, then
        we call handle_user to decide how to handle a valid user
        """
        self.assertion = form.cleaned_data['assertion']
        self.audience = django_browserid.get_audience(self.request)
        self.user = auth.authenticate(browserid_assertion=self.assertion, browserid_audience=self.audience, request=self.request)
        assert self.user.is_authenticated()

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

        return self.login_failure()
Esempio n. 20
0
    def form_valid(self, form):
        """Handles the return post request from the browserID form and puts
        interesting variables into the class. If everything checks out, then
        we call handle_user to decide how to handle a valid user
        """
        self.assertion = form.cleaned_data['assertion']
        self.audience = django_browserid.get_audience(self.request)
        self.user = auth.authenticate(browserid_assertion=self.assertion,
                                      browserid_audience=self.audience,
                                      request=self.request)
        assert self.user.is_authenticated()

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

        return self.login_failure()
Esempio n. 21
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()
Esempio n. 22
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)
Esempio n. 23
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()
Esempio n. 24
0
File: views.py Progetto: giallu/remo
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)
Esempio n. 25
0
    def create_action(self, request, serializer):
        with statsd.timer('auth.browserid.verify'):
            profile, msg = browserid_authenticate(
                request,
                serializer.data['assertion'],
                browserid_audience=serializer.data['audience']
                or get_audience(request),
                is_mobile=serializer.data['is_mobile'],
            )
        if profile is None:
            # Authentication failure.
            log.info('No profile: %s' % (msg or ''))
            raise AuthenticationFailed('No profile.')

        request.user = profile
        request.groups = profile.groups.all()

        auth.login(request, profile)
        profile.log_login_attempt(True)  # TODO: move this to the signal.
        user_logged_in.send(sender=profile.__class__,
                            request=request,
                            user=profile)

        # We want to return completely custom data, not the serializer's.
        data = {
            'error': None,
            'token': commonplace_token(request.user.email),
            'settings': {
                'display_name': request.user.display_name,
                'email': request.user.email,
                'enable_recommendations': request.user.enable_recommendations,
            }
        }
        # Serializers give up if they aren't passed an instance, so we
        # do that here despite PermissionsSerializer not needing one
        # really.
        permissions = PermissionsSerializer(context={'request': request},
                                            instance=True)
        data.update(permissions.data)

        # Add ids of installed/purchased/developed apps.
        data['apps'] = user_relevant_apps(profile)

        return data
Esempio n. 26
0
def browserid_login(request, browserid_audience=None):
    msg = ''
    if request.user.is_authenticated():
        # If username is different, maybe sign in as new user?
        return http.HttpResponse(status=200)
    try:
        is_mobile = bool(int(request.POST.get('is_mobile', 0)))
    except ValueError:
        is_mobile = False
    with statsd.timer('auth.browserid.verify'):
        profile, msg = browserid_authenticate(
            request, request.POST.get('assertion'),
            is_mobile=is_mobile,
            browserid_audience=browserid_audience or get_audience(request))
    if profile is not None:
        auth.login(request, profile)
        profile.log_login_attempt(True)
        return http.HttpResponse(status=200)
    return http.HttpResponse(msg, status=401)
Esempio n. 27
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('/')
Esempio n. 28
0
def browserid_login(request, browserid_audience=None):
    msg = ''
    if request.user.is_authenticated():
        # If username is different, maybe sign in as new user?
        return http.HttpResponse(status=200)
    try:
        is_mobile = bool(int(request.POST.get('is_mobile', 0)))
    except ValueError:
        is_mobile = False
    with statsd.timer('auth.browserid.verify'):
        profile, msg = browserid_authenticate(
            request, request.POST.get('assertion'),
            is_mobile=is_mobile,
            browserid_audience=browserid_audience or get_audience(request))
    if profile is not None:
        auth.login(request, profile)
        profile.log_login_attempt(True)
        return http.HttpResponse(status=200)
    return http.HttpResponse(msg, status=401)
Esempio n. 29
0
    def create_action(self, request, serializer):
        with statsd.timer('auth.browserid.verify'):
            profile, msg = browserid_authenticate(
                request, serializer.data['assertion'],
                browserid_audience=serializer.data['audience'] or
                                   get_audience(request),
                is_mobile=serializer.data['is_mobile'],
            )
        if profile is None:
            # Authentication failure.
            log.info('No profile: %s' % (msg or ''))
            raise AuthenticationFailed('No profile.')

        request.user = profile
        request.groups = profile.groups.all()

        auth.login(request, profile)
        profile.log_login_attempt(True)  # TODO: move this to the signal.
        user_logged_in.send(sender=profile.__class__, request=request,
                            user=profile)

        # We want to return completely custom data, not the serializer's.
        data = {
            'error': None,
            'token': commonplace_token(request.user.email),
            'settings': {
                'display_name': request.user.display_name,
                'email': request.user.email,
                'enable_recommendations': request.user.enable_recommendations,
            }
        }
        # Serializers give up if they aren't passed an instance, so we
        # do that here despite PermissionsSerializer not needing one
        # really.
        permissions = PermissionsSerializer(context={'request': request},
                                            instance=True)
        data.update(permissions.data)

        # Add ids of installed/purchased/developed apps.
        data['apps'] = user_relevant_apps(profile)

        return data
Esempio n. 30
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)
Esempio n. 31
0
def reverify(request):
    form = BrowserIDForm(data=request.POST)
    if form.is_valid():
        url = settings.BROWSERID_VERIFICATION_URL
        audience = get_audience(request)
        # TODO: when we want to require a forced-auth login across the
        # entire site then how do we do it?
        # See bug 836060.
        extra_params = {
            'experimental_forceIssuer': settings.BROWSERID_UNVERIFIED_ISSUER,
            # TODO: how do we make sure this is a proper forced
            #       auth assertion?
            # This can also be addressed in bug 836060
            'experimental_forceAuthentication': 'true',
            'experimental_allowUnverified': 'true'
        }

        log.info('Re-verifying Persona assertion. url: %s, audience: %s, '
                 'extra_params: %s' % (url, audience, extra_params))
        result = verify_assertion(form.cleaned_data['assertion'], audience,
                                  extra_params)

        log.info('Reverify got result: %s')
        if result:
            logged_user = request.session.get('uuid')
            email = result.get('unverified-email', result.get('email'))
            reverified_user = get_uuid(email)
            if logged_user and logged_user != reverified_user:
                # TODO: Should we try to support this?
                raise ValueError('A user tried to reverify herself with a '
                                 'new email: %s' % email)

            return {'user_hash': reverified_user}

        log.error('Persona assertion failed.')

    request.session.clear()
    return http.HttpResponseBadRequest()
Esempio n. 32
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)
Esempio n. 33
0
def reverify(request):
    form = BrowserIDForm(data=request.POST)
    if form.is_valid():
        url = settings.BROWSERID_VERIFICATION_URL
        audience = get_audience(request)
        # TODO: when we want to require a forced-auth login across the
        # entire site then how do we do it?
        # See bug 836060.
        extra_params = {'forceIssuer': settings.BROWSERID_UNVERIFIED_ISSUER,
                        # TODO: how do we make sure this is a proper forced
                        #       auth assertion?
                        # This can also be addressed in bug 836060
                        'forceAuthentication': 'true',
                        'allowUnverified': 'true'}

        log.info('Re-verifying Persona assertion. url: %s, audience: %s, '
                 'extra_params: %s' % (url, audience, extra_params))
        result = verify_assertion(form.cleaned_data['assertion'], audience,
                                  extra_params)

        log.info('Reverify got result: %s')
        if result:
            logged_user = request.session.get('uuid')
            email = result.get('unverified-email', result.get('email'))
            reverified_user = get_uuid(email)
            if logged_user and logged_user != reverified_user:
                # TODO: Should we try to support this?
                raise ValueError('A user tried to reverify herself with a '
                                 'new email: %s' % email)

            return {'user_hash': reverified_user}

        log.error('Persona assertion failed.')

    request.session.clear()
    return http.HttpResponseBadRequest()
Esempio n. 34
0
def browserid_login(request, browserid_audience=None):
    msg = ""
    if waffle.switch_is_active("browserid-login"):
        if request.user.is_authenticated():
            # If username is different, maybe sign in as new user?
            return http.HttpResponse(status=200)
        try:
            is_mobile = bool(int(request.POST.get("is_mobile", 0)))
        except ValueError:
            is_mobile = False
        with statsd.timer("auth.browserid.verify"):
            profile, msg = browserid_authenticate(
                request,
                request.POST["assertion"],
                is_mobile=is_mobile,
                browserid_audience=browserid_audience or get_audience(request),
            )
        if profile is not None:
            auth.login(request, profile.user)
            profile.log_login_attempt(True)
            return http.HttpResponse(status=200)
    else:
        msg = "browserid-login waffle switch is not enabled"
    return http.HttpResponse(msg, status=401)
Esempio n. 35
0
    def create_action(self, request, serializer):
        with statsd.timer("auth.browserid.verify"):
            profile, msg = browserid_authenticate(
                request,
                serializer.data["assertion"],
                browserid_audience=serializer.data["audience"] or get_audience(request),
                is_mobile=serializer.data["is_mobile"],
            )
        if profile is None:
            # Authentication failure.
            log.info("No profile: %s" % (msg or ""))
            raise AuthenticationFailed("No profile.")

        request.user, request.amo_user = profile, profile
        request.groups = profile.groups.all()

        auth.login(request, profile)
        profile.log_login_attempt(True)  # TODO: move this to the signal.
        user_logged_in.send(sender=profile.__class__, request=request, user=profile)

        # We want to return completely custom data, not the serializer's.
        data = {
            "error": None,
            "token": commonplace_token(request.amo_user.email),
            "settings": {"display_name": request.amo_user.display_name, "email": request.amo_user.email},
        }
        # Serializers give up if they aren't passed an instance, so we
        # do that here despite PermissionsSerializer not needing one
        # really.
        permissions = PermissionsSerializer(context={"request": request}, instance=True)
        data.update(permissions.data)

        # Add ids of installed/purchased/developed apps.
        data["apps"] = user_relevant_apps(profile)

        return data
Esempio n. 36
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