def _setup_idp(self, oidc_backend_config): self.config[setting_name('AUTH_EXTRA_ARGUMENTS')] = {'access_type': 'offline'} self.config['KEY'] = oidc_backend_config.get('client_id') self.config['SECRET'] = oidc_backend_config.get('client_secret') self.config['redirect_uri'] = oidc_backend_config.get('redirect_uri') if oidc_backend_config.get('prompt') is not None: self.config[setting_name('AUTH_EXTRA_ARGUMENTS')]['prompt'] = oidc_backend_config.get('prompt')
def _setup_google_backend(self, oidc_backend_config): self.config[setting_name('AUTH_EXTRA_ARGUMENTS')] = {'access_type': 'offline'} self.config['SOCIAL_AUTH_GOOGLE_OPENIDCONNECT_KEY'] = oidc_backend_config.get('client_id') self.config['SOCIAL_AUTH_GOOGLE_OPENIDCONNECT_SECRET'] = oidc_backend_config.get('client_secret') self.config['redirect_uri'] = oidc_backend_config.get('redirect_uri') if oidc_backend_config.get('prompt') is not None: self.config[setting_name('AUTH_EXTRA_ARGUMENTS')]['prompt'] = oidc_backend_config.get('prompt')
def __init__(self, provider, oidc_config, oidc_backend_config): self.config = {'provider': provider.lower()} for key, value in oidc_config.items(): self.config[setting_name(key)] = value self.config[setting_name('USER_MODEL')] = 'models.User' self.config['SOCIAL_AUTH_PIPELINE'] = AUTH_PIPELINE self.config['DISCONNECT_PIPELINE'] = DISCONNECT_PIPELINE self.config[setting_name('AUTHENTICATION_BACKENDS')] = ( BACKENDS[provider], ) self.config["VERIFY_SSL"] = oidc_config.get("VERIFY_SSL") self.config["REQUESTS_TIMEOUT"] = oidc_config.get("REQUESTS_TIMEOUT") self.config["ID_TOKEN_MAX_AGE"] = oidc_config.get("ID_TOKEN_MAX_AGE") # The following config sets PSA to call the `_login_user` function for # logging in a user. If this setting is set to false, the `_login_user` # would not be called, and as a result Galaxy would not know who is # the just logged-in user. self.config[setting_name('INACTIVE_USER_LOGIN')] = True if provider in BACKENDS_NAME: self._setup_idp(oidc_backend_config) # Secondary AuthZ with Google identities is currently supported if provider != "google": if 'SOCIAL_AUTH_SECONDARY_AUTH_PROVIDER' in self.config: del self.config["SOCIAL_AUTH_SECONDARY_AUTH_PROVIDER"] if 'SOCIAL_AUTH_SECONDARY_AUTH_ENDPOINT' in self.config: del self.config["SOCIAL_AUTH_SECONDARY_AUTH_ENDPOINT"]
def render_home(self, **extra): context = common_context( web.config[setting_name('AUTHENTICATION_BACKENDS')], load_strategy(), user=self.get_current_user(), plus_id=web.config.get(setting_name('SOCIAL_AUTH_GOOGLE_PLUS_KEY')), **extra ) return render.home(**context)
def render_home(self): context = common_context( cherrypy.config[setting_name('AUTHENTICATION_BACKENDS')], load_strategy(), user=getattr(cherrypy.request, 'user', None), plus_id=cherrypy.config.get( setting_name('SOCIAL_AUTH_GOOGLE_PLUS_KEY'))) return cherrypy.tools.jinja2env \ .get_template("home.html") \ .render(**context)
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): """Mail validation single one time use code""" pass class Partial(_AppSession, Base, SQLAlchemyPartialMixin): """Partial pipeline storage""" pass # Set the references in the storage class PyramidStorage.user = UserSocialAuth PyramidStorage.nonce = Nonce PyramidStorage.association = Association PyramidStorage.code = Code PyramidStorage.partial = Partial
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, backend) except (AttributeError, KeyError): pass return default
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(User.id.type, ForeignKey(User.id), nullable=False, index=True) UserSocialAuth.user = relationship(User, backref=backref('social_auth', lazy='dynamic'))
def _setup_google_backend(self, oidc_backend_config): self.config[setting_name('AUTH_EXTRA_ARGUMENTS')] = { 'access_type': 'offline' } self.config[ 'SOCIAL_AUTH_GOOGLE_OPENIDCONNECT_KEY'] = oidc_backend_config.get( 'client_id') self.config[ 'SOCIAL_AUTH_GOOGLE_OPENIDCONNECT_SECRET'] = oidc_backend_config.get( 'client_secret') self.config['redirect_uri'] = oidc_backend_config.get('redirect_uri') if oidc_backend_config.get('prompt') is not None: self.config[setting_name('AUTH_EXTRA_ARGUMENTS')][ 'prompt'] = oidc_backend_config.get('prompt')
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 = self._get_all_field_names(_User._meta) search_fields = [ name for name in fieldnames if name and name in all_names ] return ['user__' + name for name in search_fields] + \ getattr(settings, setting_name('ADMIN_SEARCH_FIELDS'), [])
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 = self._get_all_field_names(_User._meta) search_fields = [name for name in fieldnames if name and name in all_names] return ['user__' + name for name in search_fields] + \ getattr(settings, setting_name('ADMIN_SEARCH_FIELDS'), [])
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): """Mail validation single one time use code""" pass class Partial(db.Document, MongoenginePartialMixin): """Partial pipeline storage""" pass # Set the references in the storage class FlaskStorage.user = UserSocialAuth FlaskStorage.nonce = Nonce FlaskStorage.association = Association FlaskStorage.code = Code FlaskStorage.partial = Partial
def tenant(self, val): """ Normalize and validate the tenant name provided by user and set _tenant (e.g.: "GitHub" -> "github"). Validation includes verifying that the tenant is included in the MULTI_TENANT settings. Args: val (str): the raw tenant name (e.g.: GitHub). Raises: ImproperlyConfigured: if the backend-namespaced MULTI_TENANT setting cannot be found for validation. ValueError: if the normalized tenant string con't be found in the backend-namespaced MULTI_TENANT setting. """ # noqa: E501 # Normalize before saving normalized_tenant = val.lower() # Validate tenant before saving multi_tenant_setting_name = setting_name(self.name, 'MULTI_TENANT') multi_tenant_settings = self.setting('MULTI_TENANT') if not multi_tenant_settings: raise ImproperlyConfigured( f'Backend "{self.name}" not configured for multi-tenant: ' f'{multi_tenant_setting_name} setting not found.') if normalized_tenant not in multi_tenant_settings: raise ValueError( f'Tenant "{normalized_tenant}" not found in {multi_tenant_setting_name}.' ) self._tenant = normalized_tenant
def setting(self, name, default=None): """Return setting from tenant_settings if found there, otherwise default behavior.""" # If the setting is in the MULTI_TENANT settings, return that value expanded_setting_name = setting_name(self.name, name) if name != 'MULTI_TENANT' and self.tenant_settings and expanded_setting_name in self.tenant_settings: return self.tenant_settings.get(expanded_setting_name) return super().setting(name, default)
def __init__(self, provider, oidc_config, oidc_backend_config): self.config = {'provider': provider.lower()} for key, value in oidc_config.iteritems(): self.config[setting_name(key)] = value self.config[setting_name('USER_MODEL')] = 'models.User' self.config['SOCIAL_AUTH_PIPELINE'] = AUTH_PIPELINE self.config['DISCONNECT_PIPELINE'] = DISCONNECT_PIPELINE self.config[setting_name('AUTHENTICATION_BACKENDS')] = (BACKENDS[provider],) # The following config sets PSA to call the `_login_user` function for # logging in a user. If this setting is set to false, the `_login_user` # would not be called, and as a result Galaxy would not know who is # the just logged-in user. self.config[setting_name('INACTIVE_USER_LOGIN')] = True if provider == 'google': self._setup_google_backend(oidc_backend_config)
def wrapper(self, backend=None, *args, **kwargs): uri = redirect_uri if uri and backend and '%(backend)s' in uri: uri = uri % {'backend': backend} if uri[-1] != '/' and \ cherrypy.config.get(setting_name('TRAILING_SLASH'), False): uri = uri + '/' self.strategy = load_strategy() self.backend = load_backend(self.strategy, backend, uri) return func(self, backend, *args, **kwargs)
def disconnect(self, provider, trans, disconnect_redirect_url=None, association_id=None): on_the_fly_config(trans.sa_session) self.config[setting_name('DISCONNECT_REDIRECT_URL')] =\ disconnect_redirect_url if disconnect_redirect_url is not None else () strategy = Strategy(trans.request, trans.session, Storage, self.config) backend = self._load_backend(strategy, self.config['redirect_uri']) response = do_disconnect(backend, trans.user, association_id) if isinstance(response, six.string_types): return True, "", response return response.get('success', False), response.get('message', ""), ""
def __init__(self, provider, oidc_config, oidc_backend_config): self.config = {'provider': provider.lower()} for key, value in oidc_config.iteritems(): self.config[setting_name(key)] = value self.config[setting_name('USER_MODEL')] = 'models.User' self.config['SOCIAL_AUTH_PIPELINE'] = AUTH_PIPELINE self.config['DISCONNECT_PIPELINE'] = DISCONNECT_PIPELINE self.config[setting_name('AUTHENTICATION_BACKENDS')] = ( BACKENDS[provider], ) # The following config sets PSA to call the `_login_user` function for # logging in a user. If this setting is set to false, the `_login_user` # would not be called, and as a result Galaxy would not know who is # the just logged-in user. self.config[setting_name('INACTIVE_USER_LOGIN')] = True if provider == 'google': self._setup_google_backend(oidc_backend_config)
def disconnect(self, provider, trans, disconnect_redirect_url=None, association_id=None): self._on_the_fly_config(trans) self.config[setting_name('DISCONNECT_REDIRECT_URL')] =\ disconnect_redirect_url if disconnect_redirect_url is not None else () strategy = Strategy(trans, Storage, self.config) backend = self._load_backend(strategy, self.config['redirect_uri']) response = do_disconnect(backend, self._get_current_user(trans), association_id) if isinstance(response, six.string_types): return True, "", response return response.get('success', False), response.get('message', ""), ""
def callback(self, state_token, authz_code, trans, login_redirect_url): on_the_fly_config(trans.sa_session) self.config[setting_name('LOGIN_REDIRECT_URL')] = login_redirect_url strategy = Strategy(trans.request, trans.session, Storage, self.config) strategy.session_set(BACKENDS_NAME[self.config['provider']] + '_state', state_token) backend = self._load_backend(strategy, self.config['redirect_uri']) redirect_url = do_complete( backend, login=lambda backend, user, social_user: self._login_user(backend, user, social_user), user=trans.user, state=state_token) return redirect_url, self.config.get('user', None)
def callback(self, state_token, authz_code, trans, login_redirect_url): self._on_the_fly_config(trans) self.config[setting_name('LOGIN_REDIRECT_URL')] = login_redirect_url strategy = Strategy(trans, Storage, self.config) strategy.session_set(BACKENDS_NAME[self.config['provider']] + '_state', state_token) backend = self._load_backend(strategy, self.config['redirect_uri']) redirect_url = do_complete( backend, login=lambda backend, user, social_user: self._login_user(backend, user, social_user), user=self._get_current_user(trans), state=state_token) return redirect_url, self.config.get('user', None)
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: from django_mongoengine.mongo_auth.models import get_user_document return get_user_document() except ImportError: return module_member('mongoengine.django.auth.User')
def _get_helper(self, name, do_import=False): this_config = self.config.get(setting_name(name), DEFAULTS.get(name, None)) return do_import and module_member(this_config) or this_config
def get_setting(name): return (settings.get( setting_name(SETTING_PREFIX, backend_name, name), None) or settings.get(setting_name(backend_name, name), None))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations from social_core.utils import setting_name EMAIL_LENGTH = getattr(settings, setting_name('EMAIL_LENGTH'), 254) class Migration(migrations.Migration): replaces = [ ('social_auth', '0003_alter_email_max_length') ] dependencies = [ ('social_django', '0002_add_related_name'), ] operations = [ migrations.AlterField( model_name='code', name='email', field=models.EmailField(max_length=EMAIL_LENGTH), ), ]
from django.urls import reverse from django.views.decorators.csrf import csrf_exempt from django.views.generic.base import View from social_core.utils import setting_name from social_django.utils import load_backend, load_strategy, psa from social_django.views import complete import third_party_auth from student.helpers import get_next_url_for_login_page from student.models import UserProfile from student.views import compose_and_send_activation_email from third_party_auth import pipeline, provider from .models import SAMLConfiguration, SAMLProviderConfig 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. If the third_party_provider.skip_email_verification is set then the user is activated and verification email is not sent
# -*- encoding: utf-8 -*- 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_core.utils import setting_name from social_core.actions import do_auth, do_complete, do_disconnect from .utils import psa NAMESPACE = getattr(settings, setting_name('URL_NAMESPACE'), None) or 'social' # Calling `session.set_expiry(None)` results in a session lifetime equal to # platform default session lifetime. DEFAULT_SESSION_TIMEOUT = None @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,
import six from django.db import models from django.conf import settings from django.db.utils import IntegrityError from social_core.utils import setting_name from .storage import DjangoUserMixin, DjangoAssociationMixin, \ DjangoNonceMixin, DjangoCodeMixin, \ DjangoPartialMixin, BaseDjangoStorage from .fields import JSONField from .managers import UserSocialAuthManager 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) EMAIL_LENGTH = getattr(settings, setting_name('EMAIL_LENGTH'), 254) 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 AbstractUserSocialAuth(models.Model, DjangoUserMixin): """Abstract Social Auth association model""" user = models.ForeignKey(USER_MODEL, related_name='social_auth',
OAuth2InputSerializer, TokenSerializer, UserJWTSlidingSerializer, UserKnoxSerializer, UserJWTPairSerializer, UserSerializer, UserTokenSerializer, ) logger = logging.getLogger(__name__) REDIRECT_URI = getattr(settings, 'REST_SOCIAL_OAUTH_REDIRECT_URI', '/') DOMAIN_FROM_ORIGIN = getattr(settings, 'REST_SOCIAL_DOMAIN_FROM_ORIGIN', True) LOG_AUTH_EXCEPTIONS = getattr(settings, 'REST_SOCIAL_LOG_AUTH_EXCEPTIONS', True) STRATEGY = getattr(settings, setting_name('STRATEGY'), 'rest_social_auth.strategy.DRFStrategy') def load_strategy(request=None): return get_strategy(STRATEGY, STORAGE, request) @psa(REDIRECT_URI, load_strategy=load_strategy) def decorate_request(request, backend): pass class BaseSocialAuthView(GenericAPIView): """ View will login or signin (create) the user from social oauth2.0 provider.
import warnings from functools import wraps from django.conf import settings from django.core.urlresolvers import reverse from django.http import Http404 from social_core.utils import setting_name, module_member, get_strategy from social_core.exceptions import MissingBackend from social_core.backends.utils import get_backend BACKENDS = settings.AUTHENTICATION_BACKENDS STRATEGY = getattr(settings, setting_name('STRATEGY'), 'social_django.strategy.DjangoStrategy') STORAGE = getattr(settings, setting_name('STORAGE'), 'social_django.models.DjangoStorage') Strategy = module_member(STRATEGY) Storage = module_member(STORAGE) def load_strategy(request=None): return get_strategy(STRATEGY, STORAGE, request) def load_backend(strategy, name, redirect_uri): Backend = get_backend(BACKENDS, name) return Backend(strategy, redirect_uri)
def setting(name, default=None): try: return getattr(settings, setting_name(name)) except AttributeError: return getattr(settings, name, default)
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models, migrations from django.conf import settings from social_core.utils import setting_name USER_MODEL = getattr(settings, setting_name('USER_MODEL'), None) or \ getattr(settings, 'AUTH_USER_MODEL', None) or \ 'auth.User' class Migration(migrations.Migration): replaces = [('default', '0002_add_related_name'), ('social_auth', '0002_add_related_name')] dependencies = [ ('social_django', '0001_initial'), ] operations = [ migrations.AlterField(model_name='usersocialauth', name='user', field=models.ForeignKey( related_name='social_auth', to=USER_MODEL, on_delete=models.CASCADE, )), ]
"""URLs module""" from django.conf import settings from django.conf.urls import url from social_core.utils import setting_name from . import views extra = getattr(settings, setting_name('TRAILING_SLASH'), True) and '/' or '' app_name = 'social' urlpatterns = [ # authentication / association url(r'^login/(?P<backend>[^/]+){0}$'.format(extra), views.auth, name='begin'), url(r'^complete/(?P<backend>[^/]+){0}$'.format(extra), views.complete, name='complete'), # disconnection url(r'^disconnect/(?P<backend>[^/]+){0}$'.format(extra), views.disconnect, name='disconnect'), url(r'^disconnect/(?P<backend>[^/]+)/(?P<association_id>[^/]+){0}$' .format(extra), views.disconnect, name='disconnect_individual'), ]
def get_setting(name): return ( settings.get(setting_name(SETTING_PREFIX, backend_name, name), None) or settings.get(setting_name(backend_name, name), None))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations from social_core.utils import setting_name EMAIL_LENGTH = getattr(settings, setting_name('EMAIL_LENGTH'), 254) class Migration(migrations.Migration): replaces = [ ('default', '0003_alter_email_max_length'), ('social_auth', '0003_alter_email_max_length') ] dependencies = [ ('social_django', '0002_add_related_name'), ] operations = [ migrations.AlterField( model_name='code', name='email', field=models.EmailField(max_length=EMAIL_LENGTH), ), ]
def get_helper(name): settings = get_current_registry().settings return settings.get(setting_name(name), DEFAULTS.get(name, None))
# -*- coding: utf-8 -*- from __future__ import unicode_literals from django.conf import settings from django.db import models, migrations from social_core.utils import setting_name UID_LENGTH = getattr(settings, setting_name('UID_LENGTH'), 255) class Migration(migrations.Migration): dependencies = [ ('social_django', '0009_auto_20191118_0520'), ] operations = [ migrations.AlterField( model_name='usersocialauth', name='uid', field=models.CharField(max_length=UID_LENGTH, db_index=True), ), ]
from django.contrib.auth.decorators import login_required, permission_required from django.urls import include, path, re_path, reverse_lazy from django.views.decorators.cache import never_cache from django.views.generic import TemplateView from django.views.generic.base import RedirectView from django.views.i18n import JavaScriptCatalog from django.views.static import serve from social_core.utils import setting_name from contentbox.views import DisplayContentBoxView, EditContentBoxView from dataporten.views import Logout, login_wrapper from news import urls as news_urls from util.url_utils import debug_toolbar_urls from . import views extra = "/" if getattr(settings, setting_name('TRAILING_SLASH'), True) else "" urlpatterns = [ path( "robots.txt", TemplateView.as_view(template_name='web/robots.txt', content_type='text/plain')), path( ".well-known/security.txt", TemplateView.as_view(template_name='web/security.txt', content_type='text/plain')), *debug_toolbar_urls(), path("i18n/", include('django.conf.urls.i18n')), ] admin_urlpatterns = [
""" URL routing patterns for the Drycc REST API. """ from django.conf import settings from django.conf.urls import include, url from rest_framework.routers import DefaultRouter from social_core.utils import setting_name from api import views router = DefaultRouter(trailing_slash=False) extra = getattr(settings, setting_name('TRAILING_SLASH'), True) and '/' or '' # Add the generated REST URLs and login/logout endpoint app_urlpatterns = [ url(r'^', include(router.urls)), url(r'auth/login/?$', views.AuthLoginView.as_view({"post": "login"})), url(r'auth/token/(?P<key>[-_\w]+)/?$', views.AuthTokenView.as_view({"get": "token"})), # application release components url(r"^apps/(?P<id>{})/config/?$".format(settings.APP_URL_REGEX), views.ConfigViewSet.as_view({ 'get': 'retrieve', 'post': 'create' })), url( r"^apps/(?P<id>{})/builds/(?P<uuid>[-_\w]+)/?$".format( settings.APP_URL_REGEX), views.BuildViewSet.as_view({'get': 'retrieve'})), url(r"^apps/(?P<id>{})/builds/?$".format(settings.APP_URL_REGEX), views.BuildViewSet.as_view({ 'get': 'list',
""" from django.conf import settings from django.urls import reverse from django.http import Http404, HttpResponse, HttpResponseNotAllowed, HttpResponseServerError from django.shortcuts import redirect, render from django.views.decorators.csrf import csrf_exempt from social_django.utils import load_strategy, load_backend, psa from social_django.views import complete from social_core.utils import setting_name from student.models import UserProfile from student.views import compose_and_send_activation_email from .models import SAMLConfiguration, SAMLProviderConfig 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.
from django.db import models from django.conf import settings from django.db.utils import IntegrityError from social_core.utils import setting_name from .compat import get_rel_model from .storage import DjangoUserMixin, DjangoAssociationMixin, \ DjangoNonceMixin, DjangoCodeMixin, \ DjangoPartialMixin, BaseDjangoStorage from .fields import JSONField from .managers import UserSocialAuthManager 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) EMAIL_LENGTH = getattr(settings, setting_name('EMAIL_LENGTH'), 254) 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 AbstractUserSocialAuth(models.Model, DjangoUserMixin): """Abstract Social Auth association model"""
from django.utils.encoding import smart_unicode as smart_text smart_text # placate pyflakes except ImportError: from django.utils.encoding import smart_text # SubfieldBase causes RemovedInDjango110Warning in 1.8 and 1.9, and # will not work in 1.10 or later if django.VERSION[:2] >= (1, 8): field_metaclass = type else: from django.db.models import SubfieldBase field_metaclass = SubfieldBase field_class = functools.partial(six.with_metaclass, field_metaclass) if getattr(settings, setting_name('POSTGRES_JSONFIELD'), False): from django.contrib.postgres.fields import JSONField as JSONFieldBase else: JSONFieldBase = field_class(models.TextField) class JSONField(JSONFieldBase): """Simple JSON field that stores python structures as JSON strings on database. """ def __init__(self, *args, **kwargs): kwargs.setdefault('default', dict) super(JSONField, self).__init__(*args, **kwargs) def from_db_value(self, value, expression, connection):