Exemple #1
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"""
        __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
Exemple #2
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
Exemple #3
0
 def setting(self, name, default=None):
     names = (setting_name(self.backend_name,
                           name), setting_name(name), name)
     for name in names:
         try:
             return self.get_setting(name)
         except (AttributeError, KeyError):
             pass
     return default
Exemple #4
0
 def setting(self, name, default=None):
     setting = default
     names = (setting_name(self.backend.titled_name, name), setting_name(name), name)
     for name in names:
         try:
             return self.get_setting(name)
         except (AttributeError, KeyError):
             pass
     return setting
Exemple #5
0
 def setting(self, name, default=None, backend=None):
     names = [setting_name(name), name]
     if backend:
         names.insert(0, setting_name(backend.name, name))
     for name in names:
         try:
             return self.get_setting(name)
         except (AttributeError, KeyError):
             pass
     return default
Exemple #6
0
 def setting(self, name, default=None, backend=None):
     names = [setting_name(name), name]
     if backend:
         names.insert(0, setting_name(backend.name, name))
     for name in names:
         try:
             return self.get_setting(name)
         except (AttributeError, KeyError):
             pass
     return default
Exemple #7
0
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'))
Exemple #8
0
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
Exemple #9
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
Exemple #10
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
class UserSocialAuthOption(admin.ModelAdmin):
    """Social Auth user options"""
    list_display = ('id', 'user', 'provider', 'uid')
    list_filter = ('provider', )
    raw_id_fields = ('user', )
    list_select_related = True
    raw_search_fields = getattr(
        settings, setting_name('ADMIN_USER_SEARCH_FIELDS'),
        ('first_name', 'last_name', 'email', 'username'))
    search_fields = ['user__' + name for name in raw_search_fields]

    def get_search_fields(self, request=None):
        search_fields = getattr(settings,
                                setting_name('ADMIN_USER_SEARCH_FIELDS'), None)
        print "%s" % search_fields
        logger.error("%s" % search_fields)
        if search_fields is None:
            _User = UserSocialAuth.user_model()
            username = getattr(_User, 'USERNAME_FIELD', None) or \
                       hasattr(_User, 'username') and 'username' or \
                       None
            fieldnames = ('first_name', 'last_name', 'email', username)
            all_names = _User._meta.get_all_field_names()
            search_fields = [
                name for name in fieldnames if name and name in all_names
            ]
        logger.error("%s" % str(['user__' + name for name in search_fields]))
        return ['user__' + name for name in search_fields]
Exemple #12
0
 def setting(self, name, default=None):
     for name in (setting_name(name), name):
         try:
             return self.get_setting(name)
         except (AttributeError, KeyError):
             pass
     return default
 def setting(self, name, default=None):
     for name in (setting_name(name), name):
         try:
             return self.get_setting(name)
         except (AttributeError, KeyError):
             pass
     return default
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
Exemple #15
0
 def setting(self, name, default=None):
     """Return setting value from strategy"""
     _default = object()
     for name in (setting_name(self.name, name), name):
         value = self.strategy.setting(name, _default)
         if value != _default:
             return value
     return default
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
Exemple #17
0
 def setting(self, name, default=None):
     """Return setting value from strategy"""
     _default = object()
     for name in (setting_name(self.name, name), name):
         value = self.strategy.setting(name, _default)
         if value != _default:
             return value
     return default
Exemple #18
0
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
def setup_social_auth():
	web.config[setting_name('GOOGLE_OAUTH2_KEY')] = oauth2_key
	web.config[setting_name('GOOGLE_OAUTH2_SECRET')] = oauth2_secret
	web.config[setting_name('USER_MODEL')] = 'models.user.User'
	web.config[setting_name('AUTHENTICATION_BACKENDS')] = (
	    'social.backends.google.GoogleOAuth2',
	    )
	# TODO: change following two lines on deployment
	web.config[setting_name('NEW_USER_REDIRECT_URL')] = '/openid/#/edit'
	web.config[setting_name('LOGIN_REDIRECT_URL')] = '/openid/'
	web.config[setting_name('SANITIZE_REDIRECTS')] = False
Exemple #20
0
 def get_search_fields(self, request=None):
     search_fields = getattr(settings,
                             setting_name('ADMIN_USER_SEARCH_FIELDS'), None)
     if search_fields is None:
         _User = UserSocialAuth.user_model()
         username = getattr(_User, 'USERNAME_FIELD', None) or \
                    hasattr(_User, 'username') and 'username' or \
                    None
         fieldnames = ('first_name', 'last_name', 'email', username)
         all_names = _User._meta.get_all_field_names()
         search_fields = [
             name for name in fieldnames if name and name in all_names
         ]
     return ['user__' + name for name in search_fields]
Exemple #21
0
 def get_search_fields(self):
     search_fields = getattr(
         settings, setting_name('ADMIN_USER_SEARCH_FIELDS'), None
     )
     if search_fields is None:
         _User = UserSocialAuth.user_model()
         username = getattr(_User, 'USERNAME_FIELD', None) or \
                    hasattr(_User, 'username') and 'username' or \
                    None
         fieldnames = ('first_name', 'last_name', 'email', username)
         all_names = _User._meta.get_all_field_names()
         search_fields = [name for name in fieldnames
                             if name and name in all_names]
     return ['user_' + name for name in search_fields]
Exemple #22
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')
Exemple #23
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')
Exemple #24
0
"""
Extra views required for SSO
"""
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseServerError, Http404, HttpResponseNotAllowed
from django.shortcuts import redirect, render
from django.views.decorators.csrf import csrf_exempt
import social
from social.apps.django_app.views import complete
from social.apps.django_app.utils import load_strategy, load_backend
from social.utils import setting_name
from .models import SAMLConfiguration

URL_NAMESPACE = getattr(settings, setting_name('URL_NAMESPACE'), None) or 'social'


def inactive_user_view(request):
    """
    A newly or recently registered user has completed the social auth pipeline.
    Their account is not yet activated, but we let them login since the third party auth
    provider is trusted to vouch for them. See details in pipeline.py.

    The reason this view exists is that if we don't define this as the
    SOCIAL_AUTH_INACTIVE_USER_URL, inactive users will get sent to LOGIN_ERROR_URL, which we
    don't want.
    """
    # 'next' may be set to '/account/finish_auth/.../' if this user needs to be auto-enrolled
    # in a course. Otherwise, just redirect them to the dashboard, which displays a message
    # about activating their account.
    return redirect(request.GET.get('next', 'dashboard'))
Exemple #25
0
'''
Project: Farnsworth

Author: Karandeep Singh Nagra
'''

from django.conf import settings
from django.db import models
from django.contrib.auth.models import User, Group, Permission

from phonenumber_field.modelfields import PhoneNumberField

from social.utils import setting_name

UID_LENGTH = getattr(settings, setting_name('UID_LENGTH'), 255)

class UserProfile(models.Model):
    '''
    The UserProfile model.  Tied to a unique User.  Contains e-mail settings
    and phone number.
    '''
    user = models.OneToOneField(User)
    former_houses = models.CharField(
        blank=True,
        null=True,
        max_length=100,
        help_text="List of user's former BSC houses",
        )
    phone_number = PhoneNumberField(
        null=True,
        blank=True,
Exemple #26
0
"""Django ORM models for Social Auth"""
from django.db import models
from django.conf import settings
from django.db.utils import IntegrityError

from social.utils import setting_name
from social.storage.django_orm import DjangoUserMixin, \
                                      DjangoAssociationMixin, \
                                      DjangoNonceMixin, \
                                      DjangoCodeMixin, \
                                      BaseDjangoStorage
from social.apps.django_app.default.fields import JSONField


USER_MODEL = getattr(settings, setting_name('USER_MODEL'), None) or \
             getattr(settings, 'AUTH_USER_MODEL', None) or \
             'auth.User'
UID_LENGTH = getattr(settings, setting_name('UID_LENGTH'), 255)
NONCE_SERVER_URL_LENGTH = getattr(
    settings, setting_name('NONCE_SERVER_URL_LENGTH'), 255)
ASSOCIATION_SERVER_URL_LENGTH = getattr(
    settings, setting_name('ASSOCIATION_SERVER_URL_LENGTH'), 255)
ASSOCIATION_HANDLE_LENGTH = getattr(
    settings, setting_name('ASSOCIATION_HANDLE_LENGTH'), 255)


class UserSocialAuth(models.Model, DjangoUserMixin):
    """Social Auth association model"""
    user = models.ForeignKey(USER_MODEL, related_name='social_auth')
    provider = models.CharField(max_length=32)
    uid = models.CharField(max_length=UID_LENGTH)
def setting(name, default=None):
    try:
        return getattr(settings, setting_name(name))
    except AttributeError:
        return getattr(settings, name, default)
Exemple #28
0
def get_helper(name):
    return cherrypy.config.get(setting_name(name), DEFAULTS.get(name, None))
Exemple #29
0
sys.path.append('../..')

import web
from web.contrib.template import render_jinja

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

from social.utils import setting_name
from social.apps.webpy_app.utils import strategy, backends
from social.apps.webpy_app import app as social_app

import local_settings

web.config.debug = False
web.config[setting_name('USER_MODEL')] = 'models.User'
web.config[setting_name('AUTHENTICATION_BACKENDS')] = (
    'social.backends.open_id.OpenIdAuth',
    'social.backends.google.GoogleOpenId',
    'social.backends.google.GoogleOAuth2',
    'social.backends.google.GoogleOAuth',
    'social.backends.twitter.TwitterOAuth',
    'social.backends.yahoo.YahooOpenId',
    'social.backends.stripe.StripeOAuth2',
    'social.backends.persona.PersonaAuth',
    'social.backends.facebook.FacebookOAuth2',
    'social.backends.facebook.FacebookAppOAuth2',
    'social.backends.yahoo.YahooOAuth',
    'social.backends.angel.AngelOAuth2',
    'social.backends.behance.BehanceOAuth2',
    'social.backends.bitbucket.BitbucketOAuth',
Exemple #30
0
from sqlalchemy.orm import relationship
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')
Exemple #31
0
from django.db import models
from django.conf import settings
from social.utils import setting_name
from djangotoolbox.fields import ListField, DictField


USER_MODEL = getattr(settings, setting_name('USER_MODEL'), None) or \
    getattr(settings, 'AUTH_USER_MODEL', None) or \
    'auth.User'


class ResumizrUserData(models.Model):
    ''' misc data for resumizr '''
    user = models.OneToOneField(USER_MODEL, related_name='resumizr_data')
    detailed_social_data = DictField()
    resume_data = DictField()
    subscribers = ListField()
    following = ListField()

    class Meta:
        verbose_name_plural = "Resumizr User Data"
        verbose_name = "Resumizr User Data"
Exemple #32
0
sys.path.append('../..')

import web
from web.contrib.template import render_jinja

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

from social.utils import setting_name
from social.apps.webpy_app.utils import psa, backends
from social.apps.webpy_app import app as social_app

import local_settings

web.config.debug = False
web.config[setting_name('USER_MODEL')] = 'models.User'
web.config[setting_name('AUTHENTICATION_BACKENDS')] = (
    'social.backends.open_id.OpenIdAuth',
    'social.backends.google.GoogleOpenId',
    'social.backends.google.GoogleOAuth2',
    'social.backends.google.GoogleOAuth',
    'social.backends.twitter.TwitterOAuth',
    'social.backends.yahoo.YahooOpenId',
    'social.backends.stripe.StripeOAuth2',
    'social.backends.persona.PersonaAuth',
    'social.backends.facebook.FacebookOAuth2',
    'social.backends.facebook.FacebookAppOAuth2',
    'social.backends.yahoo.YahooOAuth',
    'social.backends.angel.AngelOAuth2',
    'social.backends.behance.BehanceOAuth2',
    'social.backends.bitbucket.BitbucketOAuth',
Exemple #33
0
 def get_setting(name):
     return (settings.get(
         setting_name(SETTING_PREFIX, backend_name, name), None)
             or settings.get(setting_name(backend_name, name), None))
Exemple #34
0
 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)
Exemple #35
0
def get_helper(request_handler, name):
    return request_handler.settings.get(setting_name(name),
                                        DEFAULTS.get(name, None))
Exemple #36
0
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)
Exemple #37
0
Including another URLconf
    1. Add an import:  from blog import urls as blog_urls
    2. Add a URL to urlpatterns:  url(r'^blog/', include(blog_urls))
"""
from django.conf.urls import include, url, patterns
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static

from ui.views import Index, logout
from api.views_ui import redirect_ui
from social.utils import setting_name
from social.apps.django_app.views import complete
from edx_proctor_webassistant.decorators import set_token_cookie

extra = getattr(settings, setting_name('TRAILING_SLASH'), True) and '/' or ''

urlpatterns = patterns(
    '',
    url(r'^$', Index.as_view(), name="index"),
    url(r'^grappelli/', include('grappelli.urls')),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^api/', include('api.urls')),

    # few angular views
    url(r'^session/', redirect_ui),
    url(r'^archive/', redirect_ui),

    url(r'^complete/(?P<backend>[^/]+){0}$'.format(extra), set_token_cookie(complete),
        name='complete'),
    url('', include('social.apps.django_app.urls', namespace='social')),
Exemple #38
0
from functools import wraps

from django.conf import settings
from django.core.urlresolvers import reverse

from social.utils import setting_name, module_member
from social.strategies.utils import get_strategy


BACKENDS = settings.AUTHENTICATION_BACKENDS
STRATEGY = getattr(settings, setting_name('STRATEGY'),
                   'social.strategies.django_strategy.DjangoStrategy')
STORAGE = getattr(settings, setting_name('STORAGE'),
                  'social.apps.django_app.default.models.DjangoStorage')
Strategy = module_member(STRATEGY)
Storage = module_member(STORAGE)


def load_strategy(*args, **kwargs):
    return get_strategy(BACKENDS, STRATEGY, STORAGE, *args, **kwargs)


def strategy(redirect_uri=None, load_strategy=load_strategy):
    def decorator(func):
        @wraps(func)
        def wrapper(request, backend, *args, **kwargs):
            uri = redirect_uri
            if uri and not uri.startswith('/'):
                uri = reverse(redirect_uri, args=(backend,))
            request.strategy = load_strategy(request=request, backend=backend,
                                             redirect_uri=uri, *args, **kwargs)
Exemple #39
0
from django.conf import settings
from django.http import Http404
from django.contrib.auth import REDIRECT_FIELD_NAME
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.contrib.auth.decorators import login_required
from django.views.decorators.http import require_POST
from django.core.urlresolvers import reverse

from social.utils import setting_name
from social.actions import do_auth, do_complete, do_disconnect
from social.strategies.utils import get_strategy
from social.apps.django_app.utils import psa, BACKENDS, STORAGE
from social.apps.django_app.views import _do_login

STRATEGY = getattr(settings, setting_name('STRATEGY'),
                   'social_auth.strategy.DSAStrategy')


def load_strategy(*args, **kwargs):
    return get_strategy(STRATEGY, STORAGE, *args, **kwargs)


def get_backend(backends, backend, strategy):
    for item in backends:
        path, name = item.rsplit('.', 1)
        module = __import__(path, globals(), locals(), [path])
        klass = getattr(module, name)
        if klass.name == backend:
            uri = reverse('socialauth_complete', kwargs={'backend': backend})
            return klass(strategy, redirect_uri=uri)
Exemple #40
0
def setting(name, default=None):
    try:
        return getattr(settings, setting_name(name))
    except AttributeError:
        return getattr(settings, name, default)
Exemple #41
0
 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)
Exemple #42
0
def get_helper(name):
    settings = get_current_registry().settings
    return settings.get(setting_name(name), DEFAULTS.get(name, None))
Exemple #43
0
"""
Extra views required for SSO
"""
from django.conf import settings
from django.core.urlresolvers import reverse
from django.http import HttpResponse, HttpResponseServerError, Http404, HttpResponseNotAllowed
from django.shortcuts import redirect
from django.views.decorators.csrf import csrf_exempt
import social
from social.apps.django_app.views import complete
from social.apps.django_app.utils import load_strategy, load_backend
from social.utils import setting_name
from .models import SAMLConfiguration

URL_NAMESPACE = getattr(settings, setting_name('URL_NAMESPACE'),
                        None) or 'social'


def inactive_user_view(request):
    """
    A newly registered user has completed the social auth pipeline.
    Their account is not yet activated, but we let them login this once.
    """
    # 'next' may be set to '/account/finish_auth/.../' if this user needs to be auto-enrolled
    # in a course. Otherwise, just redirect them to the dashboard, which displays a message
    # about activating their account.
    return redirect(request.GET.get('next', 'dashboard'))


def saml_metadata_view(request):
    """
Exemple #44
0
def get_helper(name):
    settings = get_current_registry().settings
    return settings.get(setting_name(name), DEFAULTS.get(name, None))
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
Exemple #46
0
"""Django ORM models for Social Auth"""
from django.db import models
from django.conf import settings
from django.db.utils import IntegrityError

from social.utils import setting_name
from social.storage.django_orm import DjangoUserMixin, \
                                      DjangoAssociationMixin, \
                                      DjangoNonceMixin, \
                                      BaseDjangoStorage
from social.apps.django_app.default.fields import JSONField


USER_MODEL = getattr(settings, setting_name('USER_MODEL'), None) or \
             getattr(settings, 'AUTH_USER_MODEL', None) or \
             'auth.User'
UID_LENGTH = getattr(settings, setting_name('UID_LENGTH'), 255)


class UserSocialAuth(models.Model, DjangoUserMixin):
    """Social Auth association model"""
    user = models.ForeignKey(USER_MODEL, related_name='social_auth')
    provider = models.CharField(max_length=32)
    uid = models.CharField(max_length=UID_LENGTH)
    extra_data = JSONField()

    class Meta:
        """Meta data"""
        unique_together = ('provider', 'uid')
        db_table = 'social_auth_usersocialauth'
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.db import models, migrations
import social.apps.django_app.default.fields
from django.conf import settings
import social.storage.django_orm
from social.utils import setting_name

USER_MODEL = getattr(settings, setting_name('USER_MODEL'), None) or \
             getattr(settings, 'AUTH_USER_MODEL', None) or \
             'auth.User'
UID_LENGTH = getattr(settings, setting_name('UID_LENGTH'), 255)
NONCE_SERVER_URL_LENGTH = getattr(settings,
                                  setting_name('NONCE_SERVER_URL_LENGTH'), 255)
ASSOCIATION_SERVER_URL_LENGTH = getattr(
    settings, setting_name('ASSOCIATION_SERVER_URL_LENGTH'), 255)
ASSOCIATION_HANDLE_LENGTH = getattr(settings,
                                    setting_name('ASSOCIATION_HANDLE_LENGTH'),
                                    255)


class Migration(migrations.Migration):
    replaces = [('default', '0001_initial')]

    dependencies = [
        migrations.swappable_dependency(USER_MODEL),
    ]

    operations = [
        migrations.CreateModel(
Exemple #48
0
sys.path.append("../..")

import web
from web.contrib.template import render_jinja

from sqlalchemy import create_engine
from sqlalchemy.orm import scoped_session, sessionmaker

from social.utils import setting_name
from social.apps.webpy_app.utils import psa, backends
from social.apps.webpy_app import app as social_app

import local_settings

web.config.debug = False
web.config[setting_name("USER_MODEL")] = "models.User"
web.config[setting_name("AUTHENTICATION_BACKENDS")] = (
    "social.backends.open_id.OpenIdAuth",
    "social.backends.google.GoogleOpenId",
    "social.backends.google.GoogleOAuth2",
    "social.backends.google.GoogleOAuth",
    "social.backends.twitter.TwitterOAuth",
    "social.backends.yahoo.YahooOpenId",
    "social.backends.stripe.StripeOAuth2",
    "social.backends.persona.PersonaAuth",
    "social.backends.facebook.FacebookOAuth2",
    "social.backends.facebook.FacebookAppOAuth2",
    "social.backends.yahoo.YahooOAuth",
    "social.backends.angel.AngelOAuth2",
    "social.backends.behance.BehanceOAuth2",
    "social.backends.bitbucket.BitbucketOAuth",
Exemple #49
0
                        StringField, EmailField, BooleanField
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, dbref=True)
    provider = StringField(max_length=32)
    uid = StringField(max_length=255, unique_with='provider')
    extra_data = DictField()

    def str_id(self):
        return str(self.id)
Exemple #50
0
"""Flask SQLAlchemy ORM models for Social Auth"""
import cherrypy

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')
Exemple #51
0
# -*- coding: utf-8 -*-
from __future__ import unicode_literals

from django.conf import settings
from django.db import models, migrations

from social.utils import setting_name

EMAIL_LENGTH = getattr(settings, setting_name('EMAIL_LENGTH'), 254)


class Migration(migrations.Migration):
    dependencies = [
        ('social_auth', '0002_add_related_name'),
    ]

    operations = [
        migrations.AlterField(
            model_name='code',
            name='email',
            field=models.EmailField(max_length=EMAIL_LENGTH),
        ),
    ]
Exemple #52
0
def get_helper(request, name):
    return request.registry.settings.get(setting_name(name),
                                         DEFAULTS.get(name, None))
Exemple #53
0
from django.conf import settings
from django.contrib.auth import login, REDIRECT_FIELD_NAME
from django.contrib.auth.decorators import login_required
from django.views.decorators.csrf import csrf_exempt, csrf_protect
from django.views.decorators.http import require_POST
from django.views.decorators.cache import never_cache

from social.utils import setting_name
from social.actions import do_auth, do_complete, do_disconnect
from social.apps.django_app.utils import psa


NAMESPACE = getattr(settings, setting_name('URL_NAMESPACE'), None) or 'social'


@never_cache
@psa('{0}:complete'.format(NAMESPACE))
def auth(request, backend):
    return do_auth(request.backend, redirect_name=REDIRECT_FIELD_NAME)


@never_cache
@csrf_exempt
@psa('{0}:complete'.format(NAMESPACE))
def complete(request, backend, *args, **kwargs):
    """Authentication complete view"""
    return do_complete(request.backend, _do_login, request.user,
                       redirect_name=REDIRECT_FIELD_NAME, *args, **kwargs)


@never_cache
Exemple #54
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