コード例 #1
0
def get_strategy(backends, strategy, storage, request=None, backend=None, *args, **kwargs):
    if backend:
        Backend = get_backend(backends, backend)
        if not Backend:
            raise ValueError("Missing backend entry")
    else:
        Backend = None
    Strategy = module_member(strategy)
    Storage = module_member(storage)
    return Strategy(Backend, Storage, request, backends=backends, *args, **kwargs)
コード例 #2
0
def init_social(app, db):
    User = module_member(app.config[setting_name('USER_MODEL')])

    class UserSocialAuth(db.Document, MongoengineUserMixin):
        """Social Auth association model"""
        user = ReferenceField(User)

        @classmethod
        def user_model(cls):
            return User

    class Nonce(db.Document, MongoengineNonceMixin):
        """One use numbers"""
        pass

    class Association(db.Document, MongoengineAssociationMixin):
        """OpenId account association"""
        pass

    class Code(db.Document, MongoengineCodeMixin):
        pass

    # Set the references in the storage class
    FlaskStorage.user = UserSocialAuth
    FlaskStorage.nonce = Nonce
    FlaskStorage.association = Association
    FlaskStorage.code = Code
コード例 #3
0
ファイル: utils.py プロジェクト: zqy1/flask_reveal
def load_backends(backends, force_load=False):
    """
    Load backends defined on SOCIAL_AUTH_AUTHENTICATION_BACKENDS, backends will
    be imported and cached on BACKENDSCACHE. The key in that dict will be the
    backend name, and the value is the backend class.

    Only subclasses of BaseAuth (and sub-classes) are considered backends.

    Previously there was a BACKENDS attribute expected on backends modules,
    this is not needed anymore since it's enough with the
    AUTHENTICATION_BACKENDS setting. BACKENDS was used because backends used to
    be split on two classes the authentication backend and another class that
    dealt with the auth mechanism with the provider, those classes are joined
    now.

    A force_load boolean argument is also provided so that get_backend
    below can retry a requested backend that may not yet be discovered.
    """
    global BACKENDSCACHE
    if force_load:
        BACKENDSCACHE = {}
    if not BACKENDSCACHE:
        for auth_backend in backends:
            backend = module_member(auth_backend)
            if issubclass(backend, BaseAuth):
                BACKENDSCACHE[backend.name] = backend
    return BACKENDSCACHE
コード例 #4
0
ファイル: utils.py プロジェクト: Akanksha18/Amipool
 def wrapper(request, *args, **kwargs):
     is_logged_in = module_member(
         request.backend.setting('LOGGEDIN_FUNCTION')
     )
     if not is_logged_in(request):
         raise HTTPForbidden('Not authorized user')
     return func(request, *args, **kwargs)
コード例 #5
0
def init_social(app, db):
    User = module_member(app.config[setting_name('USER_MODEL')])

    database_proxy.initialize(db)

    class UserSocialAuth(PeeweeUserMixin):
        """Social Auth association model"""
        user = ForeignKeyField(User, related_name='social_auth')

        @classmethod
        def user_model(cls):
            return User

    class Nonce(PeeweeNonceMixin):
        """One use numbers"""
        pass

    class Association(PeeweeAssociationMixin):
        """OpenId account association"""
        pass

    class Code(PeeweeCodeMixin):
        pass

    # Set the references in the storage class
    FlaskStorage.user = UserSocialAuth
    FlaskStorage.nonce = Nonce
    FlaskStorage.association = Association
    FlaskStorage.code = Code
コード例 #6
0
def get_login_providers(request, short=False):
    """
    Returns a list of available login providers based on the
    AUTHENTICATION_BACKENDS setting. Each provider is represented as a
    dictionary containing the backend name, name of required parameter if
    required and its verbose name.
    """
    def extract_backend_data(klass):
        """
        Helper function which extracts information useful for use in
        templates from SocialAuth subclasses and returns it as a
        dictionary.
        """
        return {
            'name': klass.name,
            'required_field': klass.REQUIRED_FIELD_NAME,
            'required_field_verbose': klass.REQUIRED_FIELD_VERBOSE_NAME,
        }

    backends = (module_member(auth_backend)
                for auth_backend in setting('AUTHENTICATION_BACKENDS'))
    providers = [
        extract_backend_data(backend) for backend in backends
        if issubclass(backend, BaseAuth)
    ]
    if short:
        return providers[:setting('AUTHENTICATION_PROVIDERS_BRIEF',
                                  DEFAULT_AUTHENTICATION_PROVIDERS_BRIEF)]
    return providers
コード例 #7
0
 def wrapper(request, *args, **kwargs):
     is_logged_in = module_member(
         request.strategy.setting('LOGGEDIN_FUNCTION')
     )
     if not is_logged_in(request):
         raise HTTPForbidden('Not authorized user')
     return func(request, *args, **kwargs)
コード例 #8
0
def get_login_providers(request, short=False):
    """
    Returns a list of available login providers based on the
    AUTHENTICATION_BACKENDS setting. Each provider is represented as a
    dictionary containing the backend name, name of required parameter if
    required and its verbose name.
    """
    def extract_backend_data(klass):
        """
        Helper function which extracts information useful for use in
        templates from SocialAuth subclasses and returns it as a
        dictionary.
        """
        return {
            'name': klass.name,
            'required_field': klass.REQUIRED_FIELD_NAME,
            'required_field_verbose': klass.REQUIRED_FIELD_VERBOSE_NAME,
        }

    backends = (module_member(auth_backend) for auth_backend in setting('AUTHENTICATION_BACKENDS'))
    providers = [extract_backend_data(backend) for backend in backends if issubclass(backend, BaseAuth)]
    if short:
        return providers[:setting('AUTHENTICATION_PROVIDERS_BRIEF',
                                  DEFAULT_AUTHENTICATION_PROVIDERS_BRIEF)]
    return providers
コード例 #9
0
ファイル: utils.py プロジェクト: FashtimeDotCom/flask_reveal
def load_backends(backends, force_load=False):
    """
    Load backends defined on SOCIAL_AUTH_AUTHENTICATION_BACKENDS, backends will
    be imported and cached on BACKENDSCACHE. The key in that dict will be the
    backend name, and the value is the backend class.

    Only subclasses of BaseAuth (and sub-classes) are considered backends.

    Previously there was a BACKENDS attribute expected on backends modules,
    this is not needed anymore since it's enough with the
    AUTHENTICATION_BACKENDS setting. BACKENDS was used because backends used to
    be split on two classes the authentication backend and another class that
    dealt with the auth mechanism with the provider, those classes are joined
    now.

    A force_load boolean argument is also provided so that get_backend
    below can retry a requested backend that may not yet be discovered.
    """
    global BACKENDSCACHE
    if force_load:
        BACKENDSCACHE = {}
    if not BACKENDSCACHE:
        for auth_backend in backends:
            backend = module_member(auth_backend)
            if issubclass(backend, BaseAuth):
                BACKENDSCACHE[backend.name] = backend
    return BACKENDSCACHE
コード例 #10
0
ファイル: models.py プロジェクト: jontsai/python-social-auth
def init_social(config, Base, session):
    if hasattr(config, 'registry'):
        config = config.registry.settings
    UID_LENGTH = config.get(setting_name('UID_LENGTH'), 255)
    User = module_member(config[setting_name('USER_MODEL')])
    app_session = session

    class _AppSession(object):
        COMMIT_SESSION = False

        @classmethod
        def _session(cls):
            return app_session

    class UserSocialAuth(_AppSession, Base, SQLAlchemyUserMixin):
        """Social Auth association model"""
        __tablename__ = 'social_auth_usersocialauth'
        __table_args__ = (UniqueConstraint('provider', 'uid'),)
        id = Column(Integer, primary_key=True)
        provider = Column(String(32))
        uid = Column(String(UID_LENGTH))
        extra_data = Column(JSONType)
        user_id = Column(Integer, ForeignKey(User.id),
                         nullable=False, index=True)
        user = relationship(User, backref=backref('social_auth',
                                                  lazy='dynamic'))

        @classmethod
        def username_max_length(cls):
            return User.__table__.columns.get('username').type.length

        @classmethod
        def user_model(cls):
            return User

    class Nonce(_AppSession, Base, SQLAlchemyNonceMixin):
        """One use numbers"""
        __tablename__ = 'social_auth_nonce'
        __table_args__ = (UniqueConstraint('server_url', 'timestamp', 'salt'),)
        id = Column(Integer, primary_key=True)
        server_url = Column(String(255))
        timestamp = Column(Integer)
        salt = Column(String(40))

    class Association(_AppSession, Base, SQLAlchemyAssociationMixin):
        """OpenId account association"""
        __tablename__ = 'social_auth_association'
        __table_args__ = (UniqueConstraint('server_url', 'handle'),)
        id = Column(Integer, primary_key=True)
        server_url = Column(String(255))
        handle = Column(String(255))
        secret = Column(String(255))  # base64 encoded
        issued = Column(Integer)
        lifetime = Column(Integer)
        assoc_type = Column(String(64))

    # Set the references in the storage class
    PyramidStorage.user = UserSocialAuth
    PyramidStorage.nonce = Nonce
    PyramidStorage.association = Association
コード例 #11
0
ファイル: models.py プロジェクト: 2070616d/TP3
def _get_user_model():
    """
    Get the User Document class user for MongoEngine authentication.

    Use the model defined in SOCIAL_AUTH_USER_MODEL if defined, or
    defaults to MongoEngine's configured user document class.
    """
    custom_model = getattr(settings, setting_name('USER_MODEL'), None)
    if custom_model:
        return module_member(custom_model)

    try:
        # Custom user model support with MongoEngine 0.8
        from mongoengine.django.mongo_auth.models import get_user_document
        return get_user_document()
    except ImportError:
        return module_member('mongoengine.django.auth.User')
コード例 #12
0
ファイル: views.py プロジェクト: MaxOliveira/MakeupSecrets
def complete(request, *args, **kwargs):
    do_login = module_member(request.backend.setting('LOGIN_FUNCTION'))
    return do_complete(request.backend,
                       do_login,
                       request.user,
                       redirect_name='next',
                       *args,
                       **kwargs)
コード例 #13
0
ファイル: models.py プロジェクト: lugnitdgp/avskr2.0
def _get_user_model():
    """
    Get the User Document class user for MongoEngine authentication.

    Use the model defined in SOCIAL_AUTH_USER_MODEL if defined, or
    defaults to MongoEngine's configured user document class.
    """
    custom_model = getattr(settings, setting_name('USER_MODEL'), None)
    if custom_model:
        return module_member(custom_model)

    try:
        # Custom user model support with MongoEngine 0.8
        from mongoengine.django.mongo_auth.models import get_user_document
        return get_user_document()
    except ImportError:
        return module_member('mongoengine.django.auth.User')
コード例 #14
0
ファイル: oauth1.py プロジェクト: wwitzel3/python-social-auth
 def __init__(self, *args, **kwargs):
     self.backend = module_member(self.backend_path)
     self.complete_url = '/complete/{0}/?{1}&{2}'.format(
         self.backend.name,
         'oauth_verifier=bazqux',
         'oauth_token=foobar'
     )
     super(OAuth1Test, self).__init__(*args, **kwargs)
コード例 #15
0
def init_social(app, Base, session):
    UID_LENGTH = app.config.get(setting_name('UID_LENGTH'), 255)
    User = module_member(app.config[setting_name('USER_MODEL')])
    app_session = session

    class _AppSession(object):
        @classmethod
        def _session(cls):
            return app_session

    class UserSocialAuth(_AppSession, Base, SQLAlchemyUserMixin):
        """Social Auth association model"""
        __tablename__ = 'social_auth_usersocialauth'
        __table_args__ = (UniqueConstraint('provider', 'uid'), )
        id = Column(Integer, primary_key=True)
        provider = Column(String(32))
        uid = Column(String(UID_LENGTH))
        extra_data = Column(JSONType)
        user_id = Column(Integer,
                         ForeignKey(User.id),
                         nullable=False,
                         index=True)
        user = relationship(User, backref='social_auth')

        @classmethod
        def username_max_length(cls):
            return User.__table__.columns.get('username').type.length

        @classmethod
        def user_model(cls):
            return User

    class Nonce(_AppSession, Base, SQLAlchemyNonceMixin):
        """One use numbers"""
        __tablename__ = 'social_auth_nonce'
        __table_args__ = (UniqueConstraint('server_url', 'timestamp',
                                           'salt'), )
        id = Column(Integer, primary_key=True)
        server_url = Column(String(255))
        timestamp = Column(Integer)
        salt = Column(String(40))

    class Association(_AppSession, Base, SQLAlchemyAssociationMixin):
        """OpenId account association"""
        __tablename__ = 'social_auth_association'
        __table_args__ = (UniqueConstraint('server_url', 'handle'), )
        id = Column(Integer, primary_key=True)
        server_url = Column(String(255))
        handle = Column(String(255))
        secret = Column(String(255))  # base64 encoded
        issued = Column(Integer)
        lifetime = Column(Integer)
        assoc_type = Column(String(64))

    # Set the references in the storage class
    FlaskStorage.user = UserSocialAuth
    FlaskStorage.nonce = Nonce
    FlaskStorage.association = Association
コード例 #16
0
ファイル: utils.py プロジェクト: ybbaigo/Starcal-Server
def load_backends(backends, force_load=False):
    global BACKENDSCACHE
    if force_load:
        BACKENDSCACHE = {}
    if not BACKENDSCACHE:
        for data_backend in backends:
            backend = module_member(data_backend)
            BACKENDSCACHE[backend.name] = backend
    return BACKENDSCACHE
コード例 #17
0
ファイル: actions.py プロジェクト: 0077cc/python-social-auth
 def setUp(self):
     HTTPretty.enable()
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     self.backend = module_member('social.backends.github.GithubOAuth2')
     self.strategy = TestStrategy(self.backend, TestStorage)
     self.user = None
コード例 #18
0
ファイル: utils.py プロジェクト: lugnitdgp/avskr2.0
def backends(request, user):
    """Load Social Auth current user data to context under the key 'backends'.
    Will return the output of social.backends.utils.user_backends_data."""
    storage = module_member(get_helper('STORAGE'))
    return {
        'backends':
        user_backends_data(user, get_helper('AUTHENTICATION_BACKENDS'),
                           storage)
    }
コード例 #19
0
 def setUp(self):
     HTTPretty.enable()
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     self.backend = module_member('social.backends.github.GithubOAuth2')
     self.strategy = TestStrategy(self.backend, TestStorage)
     self.user = None
コード例 #20
0
ファイル: utils.py プロジェクト: Akanksha18/Amipool
def backends(request, user):
    """Load Social Auth current user data to context under the key 'backends'.
    Will return the output of social.backends.utils.user_backends_data."""
    storage = module_member(get_helper('STORAGE'))
    return {
        'backends': user_backends_data(
            user, get_helper('AUTHENTICATION_BACKENDS'), storage
        )
    }
コード例 #21
0
ファイル: models.py プロジェクト: 2070616d/TP3
def init_social(app, session):
    UID_LENGTH = app.config.get(setting_name('UID_LENGTH'), 255)
    User = module_member(app.config[setting_name('USER_MODEL')])
    _AppSession._set_session(session)
    UserSocialAuth.__table_args__ = (UniqueConstraint('provider', 'uid'),)
    UserSocialAuth.uid = Column(String(UID_LENGTH))
    UserSocialAuth.user_id = Column(Integer, ForeignKey(User.id),
                                    nullable=False, index=True)
    UserSocialAuth.user = relationship(User, backref=backref('social_auth',
                                                             lazy='dynamic'))
コード例 #22
0
ファイル: open_id.py プロジェクト: bobhsr/python-social-auth
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     self.complete_url = "/complete/{0}/".format(self.backend.name)
     self.strategy = TestStrategy(self.backend, TestStorage, redirect_uri=self.complete_url)
     self.strategy.set_settings(
         {"SOCIAL_AUTH_AUTHENTICATION_BACKENDS": (self.backend_path, "tests.backends.broken_test.BrokenBackendAuth")}
     )
     # Force backends loading to trash PSA cache
     load_backends(self.strategy.get_setting("SOCIAL_AUTH_AUTHENTICATION_BACKENDS"), force_load=True)
コード例 #23
0
ファイル: actions.py プロジェクト: georgefs/django-login
 def setUp(self):
     HTTPretty.enable()
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     Backend = module_member('social.backends.github.GithubOAuth2')
     self.strategy = self.strategy or TestStrategy(TestStorage)
     self.backend = Backend(self.strategy, redirect_uri='/complete/github')
     self.user = None
コード例 #24
0
ファイル: actions.py プロジェクト: humaneu/flask_app
 def setUp(self):
     HTTPretty.enable()
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     Backend = module_member("social.backends.github.GithubOAuth2")
     self.strategy = self.strategy or TestStrategy(TestStorage)
     self.backend = Backend(self.strategy, redirect_uri="/complete/github")
     self.user = None
コード例 #25
0
def get_strategy(backends,
                 strategy,
                 storage,
                 request=None,
                 backend=None,
                 *args,
                 **kwargs):
    if backend:
        Backend = get_backend(backends, backend)
        if not Backend:
            raise ValueError('Missing backend entry')
    else:
        Backend = None
    Strategy = module_member(strategy)
    Storage = module_member(storage)
    return Strategy(Backend,
                    Storage,
                    request,
                    backends=backends,
                    *args,
                    **kwargs)
コード例 #26
0
ファイル: models.py プロジェクト: fabioz/python-social-auth
def init_social(Base, session, settings):
    if TornadoStorage._AppSession is not None:
        # Initialize only once. New calls are expected to have the same Base
        # and will set the session to be the new session passed.
        assert Base == TornadoStorage._Base
        TornadoStorage._AppSession.__use_db_session__ = session
        return
    
    
    UID_LENGTH = settings.get(setting_name('UID_LENGTH'), 255)
    User = module_member(settings[setting_name('USER_MODEL')])

    class _AppSession(object):
        @classmethod
        def _session(cls):
            return _AppSession.__use_db_session__

    _AppSession.__use_db_session__ = session
    TornadoStorage._AppSession = _AppSession
    TornadoStorage._Base = Base

    class UserSocialAuth(_AppSession, Base, SQLAlchemyUserMixin):
        """Social Auth association model"""
        uid = Column(String(UID_LENGTH))
        user_id = Column(Integer, ForeignKey(User.id),
                         nullable=False, index=True)
        user = relationship(User, backref=backref('social_auth',
                                                  lazy='dynamic'))

        @classmethod
        def username_max_length(cls):
            return User.__table__.columns.get('username').type.length

        @classmethod
        def user_model(cls):
            return User

    class Nonce(_AppSession, Base, SQLAlchemyNonceMixin):
        """One use numbers"""
        pass

    class Association(_AppSession, Base, SQLAlchemyAssociationMixin):
        """OpenId account association"""
        pass

    class Code(_AppSession, Base, SQLAlchemyCodeMixin):
        pass

    # Set the references in the storage class
    TornadoStorage.user = UserSocialAuth
    TornadoStorage.nonce = Nonce
    TornadoStorage.association = Association
    TornadoStorage.code = Code
コード例 #27
0
def get_username(strategy, details, user=None, *args, **kwargs):
    if 'username' not in strategy.setting('USER_FIELDS', USER_FIELDS):
        return
    storage = strategy.storage

    if not user:
        email_as_username = strategy.setting('USERNAME_IS_FULL_EMAIL', False)
        uuid_length = strategy.setting('UUID_LENGTH', 16)
        max_length = storage.user.username_max_length()
        do_slugify = strategy.setting('SLUGIFY_USERNAMES', False)
        do_clean = strategy.setting('CLEAN_USERNAMES', True)

        subdomain = strategy.request.subdomain

        if do_clean:
            clean_func = storage.user.clean_username
        else:
            clean_func = lambda val: val

        if do_slugify:
            override_slug = strategy.setting('SLUGIFY_FUNCTION')
            if override_slug:
                slug_func = module_member(override_slug)
            else:
                slug_func = slugify
        else:
            slug_func = lambda val: val

        if email_as_username and details.get('email'):
            username = details['email']
        elif details.get('username'):
            username = details['username']
        else:
            username = uuid4().hex

        short_username = (username[:max_length - uuid_length]
                          if max_length is not None else username)
        final_username = slug_func(clean_func(username[:max_length]))

        # Generate a unique username for current user using username
        # as base but adding a unique hash at the end. Original
        # username is cut to avoid any field max_length.
        # The final_username may be empty and will skip the loop.
        while not final_username or \
              storage.user.user_exists(username=final_username, subdomain=subdomain):
            username = short_username + uuid4().hex[:uuid_length]
            final_username = slug_func(clean_func(username[:max_length]))
    else:
        final_username = storage.user.get_username(user)
        subdomain = user.subdomain
    return {'username': final_username, 'subdomain': subdomain}
コード例 #28
0
ファイル: base.py プロジェクト: systemizer/python-social-auth
    def run_pipeline(self, pipeline, pipeline_index=0, *args, **kwargs):
        out = kwargs.copy()
        out.setdefault('strategy', self.strategy)
        out.setdefault('backend', out.pop(self.name, None) or self)

        for idx, name in enumerate(pipeline):
            out['pipeline_index'] = pipeline_index + idx
            func = module_member(name)
            result = func(*args, **out) or {}
            if not isinstance(result, dict):
                return result
            out.update(result)
        self.strategy.clean_partial_pipeline()
        return out
コード例 #29
0
    def setUp(self):

        self.backend_module_path = "tethys_services.backends.hydroshare.HydroShareOAuth2"
        self.Backend_Class = module_member(self.backend_module_path)
        self.client_complete_url = "https://apps.hydroshare.org/complete/hydroshare/"

        self.access_token = str(uuid.uuid4())
        self.refresh_token = str(uuid.uuid4())
        self.expires_in = random.randint(1, 30 * 60 * 60)  # 1 sec to 30 days
        self.token_type = "bearer"
        self.scope = "read write"

        self.social_username = "******"
        self.social_email = "*****@*****.**"
コード例 #30
0
ファイル: test_hydroshare.py プロジェクト: SarvaPulla/tethys
    def setUp(self):

        self.backend_module_path = "tethys_services.backends.hydroshare.HydroShareOAuth2"
        self.Backend_Class = module_member(self.backend_module_path)
        self.client_complete_url = "https://apps.hydroshare.org/complete/hydroshare/"

        self.access_token = str(uuid.uuid4())
        self.refresh_token = str(uuid.uuid4())
        self.expires_in = random.randint(1, 30 * 60 * 60)  # 1 sec to 30 days
        self.token_type = "bearer"
        self.scope = "read write"

        self.social_username = "******"
        self.social_email = "*****@*****.**"
コード例 #31
0
ファイル: user.py プロジェクト: BeatrizFerreira/EP1DAS
def get_username(strategy, details, user=None, *args, **kwargs):
    if 'username' not in strategy.setting('USER_FIELDS', USER_FIELDS):
        return
    storage = strategy.storage

    if not user:
        email_as_username = strategy.setting('USERNAME_IS_FULL_EMAIL', False)
        uuid_length = strategy.setting('UUID_LENGTH', 16)
        max_length = storage.user.username_max_length()
        do_slugify = strategy.setting('SLUGIFY_USERNAMES', False)
        do_clean = strategy.setting('CLEAN_USERNAMES', True)

        if do_clean:
            clean_func = storage.user.clean_username
        else:
            clean_func = lambda val: val

        if do_slugify:
            override_slug = strategy.setting('SLUGIFY_FUNCTION')
            if override_slug:
                slug_func = module_member(override_slug)
            else:
                slug_func = slugify
        else:
            slug_func = lambda val: val

        if email_as_username and details.get('email'):
            username = details['email']
        elif details.get('username'):
            username = details['username']
        else:
            username = uuid4().hex

        short_username = (username[:max_length - uuid_length]
                          if max_length is not None
                          else username)
        final_username = slug_func(clean_func(username[:max_length]))

        # Generate a unique username for current user using username
        # as base but adding a unique hash at the end. Original
        # username is cut to avoid any field max_length.
        # The final_username may be empty and will skip the loop.
        while not final_username or \
              storage.user.user_exists(username=final_username):
            username = short_username + uuid4().hex[:uuid_length]
            final_username = slug_func(clean_func(username[:max_length]))
    else:
        final_username = storage.user.get_username(user)
    return {'username': final_username}
コード例 #32
0
ファイル: open_id.py プロジェクト: lugnitdgp/avskr2.0
 def setUp(self):
     HTTPretty.enable()
     Backend = module_member(self.backend_path)
     self.strategy = TestStrategy(TestStorage)
     self.complete_url = self.raw_complete_url.format(Backend.name)
     self.backend = Backend(self.strategy, redirect_uri=self.complete_url)
     self.strategy.set_settings({
         'SOCIAL_AUTH_AUTHENTICATION_BACKENDS':
         (self.backend_path,
          'social.tests.backends.test_broken.BrokenBackendAuth')
     })
     # Force backends loading to trash PSA cache
     load_backends(
         self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
         force_load=True)
コード例 #33
0
ファイル: models.py プロジェクト: lugnitdgp/avskr2.0
def init_social(config, Base, session):
    if hasattr(config, 'registry'):
        config = config.registry.settings
    UID_LENGTH = config.get(setting_name('UID_LENGTH'), 255)
    User = module_member(config[setting_name('USER_MODEL')])
    app_session = session

    class _AppSession(object):
        COMMIT_SESSION = False

        @classmethod
        def _session(cls):
            return app_session

    class UserSocialAuth(_AppSession, Base, SQLAlchemyUserMixin):
        """Social Auth association model"""
        uid = Column(String(UID_LENGTH))
        user_id = Column(User.id.type,
                         ForeignKey(User.id),
                         nullable=False,
                         index=True)
        user = relationship(User,
                            backref=backref('social_auth', lazy='dynamic'))

        @classmethod
        def username_max_length(cls):
            return User.__table__.columns.get('username').type.length

        @classmethod
        def user_model(cls):
            return User

    class Nonce(_AppSession, Base, SQLAlchemyNonceMixin):
        """One use numbers"""
        pass

    class Association(_AppSession, Base, SQLAlchemyAssociationMixin):
        """OpenId account association"""
        pass

    class Code(_AppSession, Base, SQLAlchemyCodeMixin):
        pass

    # Set the references in the storage class
    PyramidStorage.user = UserSocialAuth
    PyramidStorage.nonce = Nonce
    PyramidStorage.association = Association
    PyramidStorage.code = Code
コード例 #34
0
ファイル: base.py プロジェクト: relsi/w2p-social-auth
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     self.strategy = TestStrategy(self.backend, TestStorage)
     self.name = self.backend.name.upper().replace("-", "_")
     self.complete_url = self.strategy.build_absolute_uri(self.raw_complete_url.format(self.backend.name))
     backends = (self.backend_path, "social.tests.backends.test_broken.BrokenBackendAuth")
     self.strategy.set_settings({"SOCIAL_AUTH_AUTHENTICATION_BACKENDS": backends})
     self.strategy.set_settings(self.extra_settings())
     # Force backends loading to trash PSA cache
     load_backends(backends, force_load=True)
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     TestCode.reset_cache()
コード例 #35
0
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     self.complete_url = '/complete/{0}/'.format(self.backend.name)
     self.strategy = TestStrategy(self.backend, TestStorage,
                                  redirect_uri=self.complete_url)
     self.strategy.set_settings({
         'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
             self.backend_path,
             'tests.backends.broken_test.BrokenBackendAuth'
         )
     })
     # Force backends loading to trash PSA cache
     load_backends(
         self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
         force_load=True
     )
コード例 #36
0
 def setUp(self):
     HTTPretty.enable()
     Backend = module_member(self.backend_path)
     self.strategy = TestStrategy(TestStorage)
     self.complete_url = self.raw_complete_url.format(Backend.name)
     self.backend = Backend(self.strategy, redirect_uri=self.complete_url)
     self.strategy.set_settings({
         'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
             self.backend_path,
             'social.tests.backends.test_broken.BrokenBackendAuth'
         )
     })
     # Force backends loading to trash PSA cache
     load_backends(
         self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
         force_load=True
     )
コード例 #37
0
def init_social(config, Base, session):
    if hasattr(config, 'registry'):
        config = config.registry.settings
    UID_LENGTH = config.get(setting_name('UID_LENGTH'), 255)
    User = module_member(config[setting_name('USER_MODEL')])
    app_session = session

    class _AppSession(object):
        COMMIT_SESSION = False

        @classmethod
        def _session(cls):
            return app_session

    class UserSocialAuth(_AppSession, Base, SQLAlchemyUserMixin):
        """Social Auth association model"""
        uid = Column(String(UID_LENGTH))
        user_id = Column(Integer, ForeignKey(User.id),
                         nullable=False, index=True)
        user = relationship(User, backref=backref('social_auth',
                                                  lazy='dynamic'))

        @classmethod
        def username_max_length(cls):
            return User.__table__.columns.get('username').type.length

        @classmethod
        def user_model(cls):
            return User

    class Nonce(_AppSession, Base, SQLAlchemyNonceMixin):
        """One use numbers"""
        pass

    class Association(_AppSession, Base, SQLAlchemyAssociationMixin):
        """OpenId account association"""
        pass

    class Code(_AppSession, Base, SQLAlchemyCodeMixin):
        pass

    # Set the references in the storage class
    PyramidStorage.user = UserSocialAuth
    PyramidStorage.nonce = Nonce
    PyramidStorage.association = Association
    PyramidStorage.code = Code
コード例 #38
0
    def setUp(self):
        HTTPretty.enable()
        Backend = module_member(self.backend_path)
        self.strategy = views.load_strategy()
        self.backend = Backend(self.strategy, redirect_uri=self.complete_url)
        self.name = self.backend.name.upper().replace('-', '_')
        self.complete_url = self.strategy.build_absolute_uri(
            self.raw_complete_url.format(self.backend.name))
        backends = (self.backend_path, )
        load_backends(backends, force_load=True)

        user_data_body = json.loads(self.user_data_body)
        self.email = '*****@*****.**'
        user_data_body['email'] = self.email
        self.user_data_body = json.dumps(user_data_body)

        self.do_rest_login()
コード例 #39
0
ファイル: base.py プロジェクト: FashtimeDotCom/flask_reveal
    def pipeline(self, pipeline, pipeline_index=0, *args, **kwargs):
        kwargs['strategy'] = self.strategy

        out = kwargs.copy()
        out.pop(self.name, None)
        for idx, name in enumerate(pipeline):
            out['pipeline_index'] = pipeline_index + idx
            func = module_member(name)
            result = func(*args, **out) or {}
            if not isinstance(result, dict):
                return result
            out.update(result)
        user = out['user']
        if user:
            user.social_user = out['social']
            user.is_new = out['is_new']
        return user
コード例 #40
0
    def pipeline(self, pipeline, pipeline_index=0, *args, **kwargs):
        kwargs['strategy'] = self.strategy

        out = kwargs.copy()
        out.pop(self.name, None)
        for idx, name in enumerate(pipeline):
            out['pipeline_index'] = pipeline_index + idx
            func = module_member(name)
            result = func(*args, **out) or {}
            if not isinstance(result, dict):
                return result
            out.update(result)
        user = out['user']
        if user:
            user.social_user = out['social']
            user.is_new = out['is_new']
        return user
コード例 #41
0
    def setUp(self):
        HTTPretty.enable()
        Backend = module_member(self.backend_path)
        self.strategy = load_strategy()
        self.backend = Backend(self.strategy, redirect_uri=self.complete_url)
        self.name = self.backend.name.upper().replace('-', '_')
        self.complete_url = self.strategy.build_absolute_uri(
            self.raw_complete_url.format(self.backend.name)
        )
        backends = (self.backend_path, )
        load_backends(backends, force_load=True)

        user_data_body = json.loads(self.user_data_body)
        self.email = '*****@*****.**'
        user_data_body['email'] = self.email
        self.user_data_body = json.dumps(user_data_body)

        self.do_rest_login()
コード例 #42
0
ファイル: models.py プロジェクト: ewianda/lscds-new-site
def init_social(app, db):
    UID_LENGTH = app.config.get(setting_name('UID_LENGTH'), 255)
    User = module_member(app.config[setting_name('USER_MODEL')])
    app_session = db.session

    class _AppSession(object):
        @classmethod
        def _session(cls):
            return app_session

    class UserSocialAuth(_AppSession, db.Model, SQLAlchemyUserMixin):
        """Social Auth association model"""
        uid = Column(String(UID_LENGTH))
        user_id = Column(Integer,
                         ForeignKey(User.id),
                         nullable=False,
                         index=True)
        user = relationship(User,
                            backref=backref('social_auth', lazy='dynamic'))

        @classmethod
        def username_max_length(cls):
            return User.__table__.columns.get('username').type.length

        @classmethod
        def user_model(cls):
            return User

    class Nonce(_AppSession, db.Model, SQLAlchemyNonceMixin):
        """One use numbers"""
        pass

    class Association(_AppSession, db.Model, SQLAlchemyAssociationMixin):
        """OpenId account association"""
        pass

    class Code(_AppSession, db.Model, SQLAlchemyCodeMixin):
        pass

    # Set the references in the storage class
    FlaskStorage.user = UserSocialAuth
    FlaskStorage.nonce = Nonce
    FlaskStorage.association = Association
    FlaskStorage.code = Code
コード例 #43
0
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     self.strategy = TestStrategy(self.backend, TestStorage)
     self.name = self.backend.name.upper().replace('-', '_')
     self.complete_url = self.strategy.build_absolute_uri(
         self.raw_complete_url.format(self.backend.name))
     backends = (self.backend_path,
                 'social.tests.backends.test_broken.BrokenBackendAuth')
     self.strategy.set_settings(
         {'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': backends})
     self.strategy.set_settings(self.extra_settings())
     # Force backends loading to trash PSA cache
     load_backends(backends, force_load=True)
     User.reset_cache()
     TestUserSocialAuth.reset_cache()
     TestNonce.reset_cache()
     TestAssociation.reset_cache()
     TestCode.reset_cache()
コード例 #44
0
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     name = self.backend.name
     self.complete_url = self.raw_complete_url.format(name)
     self.strategy = TestStrategy(self.backend, TestStorage)
     name = name.upper().replace('-', '_')
     self.strategy.set_settings({
         'SOCIAL_AUTH_' + name + '_KEY':
         'a-key',
         'SOCIAL_AUTH_' + name + '_SECRET':
         'a-secret-key',
         'SOCIAL_AUTH_AUTHENTICATION_BACKENDS':
         (self.backend_path, 'tests.backends.broken_test.BrokenBackendAuth')
     })
     # Force backends loading to trash PSA cache
     load_backends(
         self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
         force_load=True)
コード例 #45
0
ファイル: legacy.py プロジェクト: devvine/python-social-auth
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     name = self.backend.name.upper().replace('-', '_')
     self.strategy = TestStrategy(self.backend, TestStorage)
     self.complete_url = self.strategy.build_absolute_uri(
         '/complete/{0}'.format(name)
     )
     self.strategy.set_settings({
         'SOCIAL_AUTH_{0}_FORM_URL'.format(name): '/login/{0}'.format(name),
         'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
             self.backend_path,
             'social.tests.backends.broken_test.BrokenBackendAuth'
         )
     })
     # Force backends loading to trash PSA cache
     load_backends(
         self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
         force_load=True
     )
コード例 #46
0
ファイル: oauth.py プロジェクト: devvine/python-social-auth
 def setUp(self):
     HTTPretty.enable()
     self.backend = module_member(self.backend_path)
     name = self.backend.name
     self.complete_url = self.raw_complete_url.format(name)
     self.strategy = TestStrategy(self.backend, TestStorage)
     name = name.upper().replace('-', '_')
     self.strategy.set_settings({
         'SOCIAL_AUTH_' + name + '_KEY': 'a-key',
         'SOCIAL_AUTH_' + name + '_SECRET': 'a-secret-key',
         'SOCIAL_AUTH_AUTHENTICATION_BACKENDS': (
             self.backend_path,
             'social.tests.backends.broken_test.BrokenBackendAuth'
         )
     })
     # Force backends loading to trash PSA cache
     load_backends(
         self.strategy.get_setting('SOCIAL_AUTH_AUTHENTICATION_BACKENDS'),
         force_load=True
     )
コード例 #47
0
def get_helper(name, do_import=False):
    config = web.config.get(setting_name(name),
                            DEFAULTS.get(name, None))
    return do_import and module_member(config) or config
コード例 #48
0
ファイル: models.py プロジェクト: singhularity/edx-platform
def _load_backend_classes(base_class=BaseAuth):
    """ Load the list of python-social-auth backend classes from Django settings """
    for class_path in settings.AUTHENTICATION_BACKENDS:
        auth_class = module_member(class_path)
        if issubclass(auth_class, base_class):
            yield auth_class
コード例 #49
0
ファイル: auth.py プロジェクト: nozuono/calibre-webserver
 def complete(self, backend, *args, **kwargs):
     login = cherrypy.config.get(setting_name('LOGIN_METHOD'))
     do_login = module_member(login) if login else self.do_login
     user = getattr(cherrypy.request, 'user', None)
     return do_complete(self.strategy, do_login, user=user, *args, **kwargs)
コード例 #50
0
ファイル: base.py プロジェクト: lugnitdgp/avskr2.0
 def send_email_validation(self, backend, email):
     email_validation = self.setting('EMAIL_VALIDATION_FUNCTION')
     send_email = module_member(email_validation)
     code = self.storage.code.make_code(email)
     send_email(self, backend, code)
     return code
コード例 #51
0
ファイル: base.py プロジェクト: BeatrizFerreira/EP1DAS
 def send_email_validation(self, backend, email):
     email_validation = self.setting('EMAIL_VALIDATION_FUNCTION')
     send_email = module_member(email_validation)
     code = self.storage.code.make_code(email)
     send_email(self, backend, code)
     return code
コード例 #52
0
ファイル: models.py プロジェクト: nikolicnikola/edx-platform
def _load_backend_classes(base_class=BaseAuth):
    """ Load the list of python-social-auth backend classes from Django settings """
    for class_path in settings.AUTHENTICATION_BACKENDS:
        auth_class = module_member(class_path)
        if issubclass(auth_class, base_class):
            yield auth_class
コード例 #53
0
ファイル: models.py プロジェクト: yegle/python-social-auth
from mongoengine.queryset import OperationError

from social.utils import setting_name, module_member
from social.storage.django_orm import DjangoUserMixin, \
                                      DjangoAssociationMixin, \
                                      DjangoNonceMixin, \
                                      DjangoCodeMixin, \
                                      BaseDjangoStorage


UNUSABLE_PASSWORD = '******'  # Borrowed from django 1.4


USER_MODEL = module_member(
    getattr(settings, setting_name('USER_MODEL'), None) or
    getattr(settings, 'AUTH_USER_MODEL', None) or
    'mongoengine.django.auth.User'
)


class UserSocialAuth(Document, DjangoUserMixin):
    """Social Auth association model"""
    user = ReferenceField(USER_MODEL)
    provider = StringField(max_length=32)
    uid = StringField(max_length=255, unique_with='provider')
    extra_data = DictField()

    def str_id(self):
        return str(self.id)

    @classmethod
コード例 #54
0
def get_strategy(strategy, storage, *args, **kwargs):
    Strategy = module_member(strategy)
    Storage = module_member(storage)
    return Strategy(Storage, *args, **kwargs)
コード例 #55
0
ファイル: models.py プロジェクト: lugnitdgp/avskr2.0
from sqlalchemy import Column, Integer, String, ForeignKey
from sqlalchemy.orm import relationship
from sqlalchemy.ext.declarative import declarative_base

from social.utils import setting_name, module_member
from social.storage.sqlalchemy_orm import SQLAlchemyUserMixin, \
                                          SQLAlchemyAssociationMixin, \
                                          SQLAlchemyNonceMixin, \
                                          BaseSQLAlchemyStorage

SocialBase = declarative_base()

DB_SESSION_ATTR = cherrypy.config.get(setting_name('DB_SESSION_ATTR'), 'db')
UID_LENGTH = cherrypy.config.get(setting_name('UID_LENGTH'), 255)
User = module_member(cherrypy.config[setting_name('USER_MODEL')])


class CherryPySocialBase(object):
    @classmethod
    def _session(cls):
        return getattr(cherrypy.request, DB_SESSION_ATTR)


class UserSocialAuth(CherryPySocialBase, SQLAlchemyUserMixin, SocialBase):
    """Social Auth association model"""
    uid = Column(String(UID_LENGTH))
    user_id = Column(Integer, ForeignKey(User.id), nullable=False, index=True)
    user = relationship(User, backref='social_auth')

    @classmethod
コード例 #56
0
from sqlalchemy.schema import UniqueConstraint
from sqlalchemy.ext.declarative import declarative_base

from social.utils import setting_name, module_member
from social.storage.sqlalchemy_orm import SQLAlchemyUserMixin, \
                                          SQLAlchemyAssociationMixin, \
                                          SQLAlchemyNonceMixin, \
                                          SQLAlchemyCodeMixin, \
                                          BaseSQLAlchemyStorage
from social.apps.webpy_app.fields import JSONType


SocialBase = declarative_base()

UID_LENGTH = web.config.get(setting_name('UID_LENGTH'), 255)
User = module_member(web.config[setting_name('USER_MODEL')])


class UserSocialAuth(SQLAlchemyUserMixin, SocialBase):
    """Social Auth association model"""
    __tablename__ = 'social_auth_usersocialauth'
    __table_args__ = (UniqueConstraint('provider', 'uid'),)
    id = Column(Integer, primary_key=True)
    provider = Column(String(32))
    uid = Column(String(UID_LENGTH))
    extra_data = Column(JSONType)
    user_id = Column(Integer, ForeignKey(User.id),
                     nullable=False, index=True)
    user = relationship(User, backref='social_auth')

    @classmethod
コード例 #57
0
ファイル: utils.py プロジェクト: lugnitdgp/avskr2.0
def get_helper(name, do_import=False):
    config = web.config.get(setting_name(name), DEFAULTS.get(name, None))
    return do_import and module_member(config) or config