Handle redirect back from provider

def dispatch_request(self):
        """ Handle redirect back from provider """
        if current_user.is_authenticated:
            return redirect(self.next)

        # clear previous!
        if 'social_data' in session:
            del session['social_data']

        res = self.app.authorized_response()
        if res is None:
            if self.flash: flash(self.auth_failed_msg, 'danger')
            return redirect(self.next)

        # retrieve profile
        data = self.get_profile_data(res)
        if data is None:
            if self.flash: flash(self.data_failed_msg, 'danger')
            return redirect(self.next)

        # attempt login
        try:
            ok = user_service.attempt_social_login(self.provider, data['id'])
            if ok:
                if self.flash:
                    flash(self.logged_in_msg.format(self.provider), 'success')
                return redirect(self.logged_in)
        except x.AccountLocked as locked:
            msg = self.lock_msg.format(locked.locked_until)
            if self.flash: flash(msg, 'danger')
            url = url_for(self.lock_redirect, **self.lock_redirect_params)
            return redirect(url)
        except x.EmailNotConfirmed:
            return redirect(url_for(self.unconfirmed_email_endpoint))

        # get data
        email = data.get('email')
        provider = data.get('provider')
        id = data.get('id')
        id_column = '{}_id'.format(provider)

        # user exists: add social id to profile
        user = user_service.first(email=email)
        if user:
            setattr(user, id_column, id)
            user_service.save(user)

        # no user: register
        if not user:
            cfg = current_app.config
            send_welcome = cfg.get('USER_SEND_WELCOME_MESSAGE')
            base_confirm_url = cfg.get('USER_BASE_EMAIL_CONFIRM_URL')
            if not base_confirm_url:
                endpoint = 'user.confirm.email.request'
                base_confirm_url = url_for(endpoint, _external=True)

            data = dict(email=email)
            data[id_column] = id
            user = user_service.register(
                user_data=data,
                send_welcome=send_welcome,
                base_confirm_url=base_confirm_url
            )

        # email confirmed?
        if user_service.require_confirmation and not user.email_confirmed:
            return redirect(url_for(self.ok_endpoint, **self.ok_params))

        # otherwise just login
        user_service.force_login(user)
        return redirect(self.force_login_redirect)