コード例 #1
0
ファイル: user.py プロジェクト: vinodpandey/appenlight
def handle_auth_success(request, result):
    # Hooray, we have the user!
    # OAuth 2.0 and OAuth 1.0a provide only limited user data on login,
    # We need to update the user to get more info.
    if result.user:
        result.user.update()

    social_data = {
        "user": {
            "data": result.user.data
        },
        "credentials": result.user.credentials,
    }
    # normalize data
    social_data["user"]["id"] = result.user.id
    user_name = result.user.username or ""
    # use email name as username for google
    if social_data[
            "credentials"].provider_name == "google" and result.user.email:
        user_name = result.user.email
    social_data["user"]["user_name"] = user_name
    social_data["user"]["email"] = result.user.email or ""

    request.session["zigg.social_auth"] = social_data
    # user is logged so bind his external identity with account
    if request.user:
        handle_social_data(request, request.user, social_data)
        request.session.pop("zigg.social_auth", None)
        return HTTPFound(location=request.route_url("/"))
    else:
        user = ExternalIdentityService.user_by_external_id_and_provider(
            social_data["user"]["id"],
            social_data["credentials"].provider_name)
        # fix legacy accounts with wrong google ID
        if not user and social_data["credentials"].provider_name == "google":
            user = ExternalIdentityService.user_by_external_id_and_provider(
                social_data["user"]["email"],
                social_data["credentials"].provider_name)

        # user tokens are already found in our db
        if user:
            handle_social_data(request, user, social_data)
            headers = security.remember(request, user.id)
            request.session.pop("zigg.social_auth", None)
            return HTTPFound(location=request.route_url("/"), headers=headers)
        else:
            msg = ("You need to finish registration "
                   "process to bind your external identity to your account "
                   "or sign in to existing account")
            request.session.flash(msg)
            return HTTPFound(location=request.route_url("register"))
コード例 #2
0
def handle_auth_success(request, result):
    # Hooray, we have the user!
    # OAuth 2.0 and OAuth 1.0a provide only limited user data on login,
    # We need to update the user to get more info.
    if result.user:
        result.user.update()

    social_data = {
        'user': {
            'data': result.user.data
        },
        'credentials': result.user.credentials
    }
    # normalize data
    social_data['user']['id'] = result.user.id
    user_name = result.user.username or ''
    # use email name as username for google
    if (social_data['credentials'].provider_name == 'google'
            and result.user.email):
        user_name = result.user.email
    social_data['user']['user_name'] = user_name
    social_data['user']['email'] = result.user.email or ''

    request.session['zigg.social_auth'] = social_data
    # user is logged so bind his external identity with account
    if request.user:
        handle_social_data(request, request.user, social_data)
        request.session.pop('zigg.social_auth', None)
        return HTTPFound(location=request.route_url('/'))
    else:
        user = ExternalIdentityService.user_by_external_id_and_provider(
            social_data['user']['id'],
            social_data['credentials'].provider_name)
        # fix legacy accounts with wrong google ID
        if not user and social_data['credentials'].provider_name == 'google':
            user = ExternalIdentityService.user_by_external_id_and_provider(
                social_data['user']['email'],
                social_data['credentials'].provider_name)

        # user tokens are already found in our db
        if user:
            handle_social_data(request, user, social_data)
            headers = security.remember(request, user.id)
            request.session.pop('zigg.social_auth', None)
            return HTTPFound(location=request.route_url('/'), headers=headers)
        else:
            msg = 'You need to finish registration ' \
                  'process to bind your external identity to your account ' \
                  'or sign in to existing account'
            request.session.flash(msg)
            return HTTPFound(location=request.route_url('register'))
コード例 #3
0
ファイル: login.py プロジェクト: kridsadakorn/Magpie
def login_success_external(request, external_user_name, external_id, email, provider_name):
    # type: (Request, Str, Str, Str, Str) -> HTTPException
    """
    Generates the login response in case of successful external provider identification.
    """
    # find possibly already registered user by external_id/provider
    user = ExternalIdentityService.user_by_external_id_and_provider(external_id, provider_name, request.db)
    if user is None:
        # create new user with an External Identity
        user = new_user_external(external_user_name=external_user_name, external_id=external_id,
                                 email=email, provider_name=provider_name, db_session=request.db)
    # set a header to remember user (set-cookie)
    headers = remember(request, user.id)

    # redirect to 'Homepage-Route' header only if corresponding to Magpie host
    if "homepage_route" in request.cookies:
        homepage_route = str(request.cookies["homepage_route"])
    elif "Homepage-Route" in request.headers:
        homepage_route = str(request.headers["Homepage-Route"])
    else:
        homepage_route = "/"
    header_host = urlparse(homepage_route).hostname
    magpie_host = get_magpie_url(request)
    if header_host and header_host != magpie_host:
        ax.raise_http(http_error=HTTPForbidden, detail=s.ProviderSignin_GET_ForbiddenResponseSchema.description)
    if not header_host:
        homepage_route = magpie_host + ("/" if not homepage_route.startswith("/") else "") + homepage_route
    return ax.valid_http(http_success=HTTPFound, detail=s.ProviderSignin_GET_FoundResponseSchema.description,
                         content={"homepage_route": homepage_route},
                         http_kwargs={"location": homepage_route, "headers": headers})
コード例 #4
0
def handle_social_data(event):
    social_data = event.social_data
    request = event.request

    if not social_data['user']['id']:
        request.session.flash(
            _('No external user id found? Perhaps permissions for '
              'authentication are set incorrectly'), 'error')
        return False

    extng_id = ExternalIdentityService.by_external_id_and_provider(
        social_data['user']['id'],
        social_data['credentials'].provider_name,
        db_session=request.dbsession
    )
    update_identity = False
    # if current token doesn't match what we have in db - remove old one
    if extng_id and extng_id.access_token != social_data['credentials'].token:
        extng_id.delete()
        update_identity = True

    if not extng_id or update_identity:
        if not update_identity:
            request.session.flash({'msg': _('Your external identity is now '
                                            'connected with your account'),
                                   'level': 'warning'})
        ex_identity = ExternalIdentity()
        ex_identity.external_id = social_data['user']['id']
        ex_identity.external_user_name = social_data['user']['user_name']
        ex_identity.provider_name = social_data['credentials'].provider_name
        ex_identity.access_token = social_data['credentials'].token
        ex_identity.token_secret = social_data['credentials'].token_secret
        ex_identity.alt_token = social_data['credentials'].refresh_token
        event.user.external_identities.append(ex_identity)
        request.session.pop('zigg.social_auth', None)
コード例 #5
0
ファイル: auth.py プロジェクト: peletiah/testscaffold
    def handle_auth_success(self, result):
        request = self.request
        # Hooray, we have the user!
        # OAuth 2.0 and OAuth 1.0a provide only limited user data on login,
        # We need to update the user to get more info.
        if result.user:
            result.user.update()
        social_data = {
            'user': {
                'data': result.user.data
            },
            'credentials': result.user.credentials
        }
        # normalize data
        social_data['user']['id'] = result.user.id
        user_name = result.user.username or ''
        # use email name as username for google
        if (social_data['credentials'].provider_name == 'google'
                and result.user.email):
            user_name = result.user.email
        social_data['user']['user_name'] = user_name
        social_data['user']['email'] = result.user.email or ''

        request.session['zigg.social_auth'] = social_data
        # user is logged so bind his external identity with account
        if request.user:
            log.info('social_auth', extra={'user_found': True})
            request.registry.notify(
                SocialAuthEvent(request, request.user, social_data))
            request.session.pop('zigg.social_auth', None)
            return HTTPFound(location=request.route_url('/'))
        else:
            log.info('social_auth', extra={'user_found': False})

            user = ExternalIdentityService.user_by_external_id_and_provider(
                social_data['user']['id'],
                social_data['credentials'].provider_name,
                db_session=request.dbsession)
            # user tokens are already found in our db
            if user:
                request.registry.notify(
                    SocialAuthEvent(request, user, social_data))
                headers = remember(request, user.id)
                request.session.pop('zigg.social_auth', None)
                return self.shared_sign_in(user, headers)
            else:
                msg = {
                    'msg':
                    self.translate(
                        _('You need to finish registration '
                          'process to bind your external '
                          'identity to your account or sign in to '
                          'existing account')),
                    'level':
                    'warning'
                }
                request.session.flash(msg)
                return HTTPFound(location=request.route_url('register'))
コード例 #6
0
 def test_user_by_external_id_and_provider(self, db_session):
     user = add_user(db_session)
     identity = ExternalIdentity(external_user_name="foo",
                                 external_id="foo",
                                 provider_name="facebook")
     user.external_identities.append(identity)
     # db_session.flush()
     found = ExternalIdentityService.user_by_external_id_and_provider(
         provider_name="facebook", external_id="foo", db_session=db_session)
     assert user == found
コード例 #7
0
 def test_by_external_id_and_provider(self, db_session):
     user = add_user(db_session)
     identity = ExternalIdentity(external_user_name='foo',
                                 external_id='foo',
                                 provider_name='facebook')
     user.external_identities.append(identity)
     # db_session.flush()
     found = ExternalIdentityService.by_external_id_and_provider(
         provider_name='facebook', external_id='foo', db_session=db_session)
     assert identity == found
コード例 #8
0
 def test_user_by_external_id_and_provider(self, db_session):
     user = add_user(db_session)
     identity = ExternalIdentity(
         external_user_name="foo", external_id="foo", provider_name="facebook"
     )
     user.external_identities.append(identity)
     # db_session.flush()
     found = ExternalIdentityService.user_by_external_id_and_provider(
         provider_name="facebook", external_id="foo", db_session=db_session
     )
     assert user == found
コード例 #9
0
 def test_get(self, db_session):
     user = add_user(db_session)
     identity = ExternalIdentity(external_user_name='foo',
                                 external_id='foo',
                                 provider_name='facebook')
     user.external_identities.append(identity)
     db_session.flush()
     found = ExternalIdentityService.get(provider_name='facebook',
                                         external_id='foo',
                                         local_user_id=user.id,
                                         db_session=db_session)
     assert identity == found
コード例 #10
0
 def test_by_external_id_and_provider(self, db_session):
     user = add_user(db_session)
     identity = ExternalIdentity(external_user_name='foo',
                                 external_id='foo',
                                 provider_name='facebook')
     user.external_identities.append(identity)
     # db_session.flush()
     found = ExternalIdentityService.by_external_id_and_provider(
         provider_name='facebook',
         external_id='foo',
         db_session=db_session)
     assert identity == found
コード例 #11
0
ファイル: social.py プロジェクト: vinodpandey/appenlight
def handle_social_data(request, user, social_data):
    social_data = social_data
    update_identity = False

    extng_id = ExternalIdentityService.by_external_id_and_provider(
        social_data["user"]["id"], social_data["credentials"].provider_name
    )

    # fix legacy accounts with wrong google ID
    if not extng_id and social_data["credentials"].provider_name == "google":
        extng_id = ExternalIdentityService.by_external_id_and_provider(
            social_data["user"]["email"], social_data["credentials"].provider_name
        )

    if extng_id:
        extng_id.delete()
        update_identity = True

    if not social_data["user"]["id"]:
        request.session.flash(
            "No external user id found? Perhaps permissions for "
            "authentication are set incorrectly",
            "error",
        )
        return False

    if not extng_id or update_identity:
        if not update_identity:
            request.session.flash(
                "Your external identity is now " "connected with your account"
            )
        ex_identity = ExternalIdentity()
        ex_identity.external_id = social_data["user"]["id"]
        ex_identity.external_user_name = social_data["user"]["user_name"]
        ex_identity.provider_name = social_data["credentials"].provider_name
        ex_identity.access_token = social_data["credentials"].token
        ex_identity.token_secret = social_data["credentials"].token_secret
        ex_identity.alt_token = social_data["credentials"].refresh_token
        user.external_identities.append(ex_identity)
        request.session.pop("zigg.social_auth", None)
コード例 #12
0
 def test_get(self, db_session):
     user = add_user(db_session)
     identity = ExternalIdentity(external_user_name='foo',
                                 external_id='foo',
                                 provider_name='facebook')
     user.external_identities.append(identity)
     db_session.flush()
     found = ExternalIdentityService.get(
         provider_name='facebook',
         external_id='foo',
         local_user_id=user.id,
         db_session=db_session)
     assert identity == found
コード例 #13
0
def handle_social_data(request, user, social_data):
    social_data = social_data
    update_identity = False

    extng_id = ExternalIdentityService.by_external_id_and_provider(
        social_data['user']['id'], social_data['credentials'].provider_name)

    # fix legacy accounts with wrong google ID
    if not extng_id and social_data['credentials'].provider_name == 'google':
        extng_id = ExternalIdentityService.by_external_id_and_provider(
            social_data['user']['email'],
            social_data['credentials'].provider_name)

    if extng_id:
        extng_id.delete()
        update_identity = True

    if not social_data['user']['id']:
        request.session.flash(
            'No external user id found? Perhaps permissions for '
            'authentication are set incorrectly', 'error')
        return False

    if not extng_id or update_identity:
        if not update_identity:
            request.session.flash('Your external identity is now '
                                  'connected with your account')
        ex_identity = ExternalIdentity()
        ex_identity.external_id = social_data['user']['id']
        ex_identity.external_user_name = social_data['user']['user_name']
        ex_identity.provider_name = social_data['credentials'].provider_name
        ex_identity.access_token = social_data['credentials'].token
        ex_identity.token_secret = social_data['credentials'].token_secret
        ex_identity.alt_token = social_data['credentials'].refresh_token
        user.external_identities.append(ex_identity)
        request.session.pop('zigg.social_auth', None)
コード例 #14
0
    def user_by_external_id_and_provider(cls, external_id, provider_name,
                                         db_session=None):
        """
        Backwards compatible alias to
        :class:`ziggurat_foundations.models.services.external_identity.ExternalIdentityService.user_by_external_id_and_provider`

        .. deprecated:: 0.8

        :param external_id:
        :param provider_name:
        :param db_session:
        :return: User
        """
        db_session = get_db_session(db_session)
        return ExternalIdentityService.user_by_external_id_and_provider(
            external_id=external_id, provider_name=provider_name,
            db_session=db_session)
コード例 #15
0
    def user_by_external_id_and_provider(cls,
                                         external_id,
                                         provider_name,
                                         db_session=None):
        """
        Backwards compatible alias to
        :class:`ziggurat_foundations.models.services.external_identity.ExternalIdentityService.user_by_external_id_and_provider`

        .. deprecated:: 0.8

        :param external_id:
        :param provider_name:
        :param db_session:
        :return: User
        """
        db_session = get_db_session(db_session)
        return ExternalIdentityService.user_by_external_id_and_provider(
            external_id=external_id,
            provider_name=provider_name,
            db_session=db_session)