def handle_noargs(self, **options): verbosity = int(options.get('verbosity')) try: from social_auth import version from social_auth.backends import get_backends, BaseOAuth except ImportError: # pragma: no cover raise CommandError("django-social-auth is not installed.") request = RequestFactory().get('/') for name, backend in get_backends().items(): if issubclass(backend, BaseOAuth) and backend.enabled(): if version < (0, 7): # Prior to 0.7 get_key_and_secret was an instance method backend = backend(request, '/') # Create providers if they don't already exist key, secret = backend.get_key_and_secret() defaults = { 'request_token_url': getattr(backend, 'REQUEST_TOKEN_URL', '') or '', 'authorization_url': getattr(backend, 'AUTHORIZATION_URL', '') or '', 'access_token_url': getattr(backend, 'ACCESS_TOKEN_URL', '') or '', 'profile_url': '', 'consumer_key': key or None, 'consumer_secret': secret or None, } provider, created = Provider.objects.get_or_create(name=name, defaults=defaults) if created and verbosity > 0: self.stdout.write('New provider created from "%s" backend.\n' % name)
def backends_data(user): """Return backends data for given user. Will return a dict with values: associated: UserSocialAuth model instances for currently associated accounts not_associated: Not associated (yet) backend names. backends: All backend names. If user is not authenticated, then first list is empty, and there's no difference between the second and third lists. """ available = get_backends().keys() values = {'associated': [], 'not_associated': available, 'backends': available} # user comes from request.user usually, on /admin/ it will be an instance # of auth.User and this code will fail if a custom User model was defined if isinstance(user, User) and user.is_authenticated(): associated = user.social_auth.all() not_associated = list(set(available) - set(assoc.provider for assoc in associated)) values['associated'] = associated values['not_associated'] = not_associated return values
def backends_data(user): """Return backends data for given user. Will return a dict with values: associated: UserSocialAuth model instances for currently associated accounts not_associated: Not associated (yet) backend names. backends: All backend names. If user is not authenticated, then first list is empty, and there's no difference between the second and third lists. """ available = get_backends().keys() values = { 'associated': [], 'not_associated': available, 'backends': available } # user comes from request.user usually, on /admin/ it will be an instance # of auth.User and this code will fail if a custom User model was defined if isinstance(user, User) and user.is_authenticated(): associated = user.social_auth.all() not_associated = list( set(available) - set(assoc.provider for assoc in associated)) values['associated'] = associated values['not_associated'] = not_associated return values
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(name, klass): """ Helper function which extracts information useful for use in templates from SocialAuth subclasses and returns it as a dictionary. """ return { 'name': name, 'required_field': klass.AUTH_BACKEND.REQUIRED_FIELD_NAME, 'required_field_verbose': klass.AUTH_BACKEND.REQUIRED_FIELD_VERBOSE_NAME, } providers = [extract_backend_data(name, auth) for name, auth in get_backends().items()] if short: return providers[:setting('AUTHENTICATION_PROVIDERS_BRIEF', DEFAULT_AUTHENTICATION_PROVIDERS_BRIEF)] return providers
def refresh_user_data(user): items = user.social_auth.all() key=lambda x: x backends = get_backends() for item in items: try: backend = backends[key(item.provider)] if issubclass(backend, SocialBackend): if item.provider != "google": service = SocialServiceLocator.get_instane().build_service_by_name(item.provider) service.pull_user_info(user.id, item.extra_data) if issubclass(backend, PhysicalBackend): service = PhysicalServiceLocator.get_instane().get_service_by_name(item.provider) service.pull_user_info(user.id, item.extra_data) if issubclass(backend, GenomicsBackend): service = GenomicsServiceLocator.get_instane().build_service_by_name(item.provider) service.pull_user_info(user.id, item.extra_data) if issubclass(backend, NutritionBackend): service = NutritionServiceLocator.get_instane().build_service_by_name(item.provider) service.pull_user_info(user.id, item.extra_data) if issubclass(backend, HealthBackend): service = HealthServiceLocator.get_instane().get_service_by_name(item.provider) service.pull_user_info(user.id, item.extra_data) except Exception, e: print e
def handle_noargs(self, **options): verbosity = int(options.get('verbosity')) try: from social_auth import version from social_auth.backends import get_backends, BaseOAuth except ImportError: # pragma: no cover raise CommandError("django-social-auth is not installed.") request = RequestFactory().get('/') for name, backend in get_backends().items(): if issubclass(backend, BaseOAuth) and backend.enabled(): if version < (0, 7): # Prior to 0.7 get_key_and_secret was an instance method backend = backend(request, '/') # Create providers if they don't already exist key, secret = backend.get_key_and_secret() defaults = { 'request_token_url': getattr(backend, 'REQUEST_TOKEN_URL', '') or '', 'authorization_url': getattr(backend, 'AUTHORIZATION_URL', '') or '', 'access_token_url': getattr(backend, 'ACCESS_TOKEN_URL', '') or '', 'profile_url': '', 'consumer_key': key or None, 'consumer_secret': secret or None, } provider, created = Provider.objects.get_or_create( name=name, defaults=defaults) if created and verbosity > 0: self.stdout.write( 'New provider created from "%s" backend.\n' % name)
def context_value(): keys = [key for key in get_backends().keys()] accounts = dict(zip(keys, [None] * len(keys))) user = request.user if hasattr(user, 'is_authenticated') and user.is_authenticated(): accounts.update((assoc.provider, assoc) for assoc in UserSocialAuth.get_social_auth_for_user(user)) return accounts
def admin_home(request): potential_providers = backends.get_backends().keys() for social in request.user.social_auth.all(): if social.provider in potential_providers: potential_providers = [x for x in potential_providers if x != social.provider] return render(request, 'admin_home.html', { 'potential_providers': potential_providers })
def context_value(): keys = [key for key in list(get_backends().keys())] accounts = dict(list(zip(keys, [None] * len(keys)))) user = request.user if hasattr(user, 'is_authenticated') and user.is_authenticated(): accounts.update( (assoc.provider, assoc) for assoc in UserSocialAuth.get_social_auth_for_user(user)) return accounts
def tokens(self): """Return access_token stored in extra_data or None""" # Make import here to avoid recursive imports :-/ from social_auth.backends import get_backends backend = get_backends().get(self.provider) if backend: return backend.AUTH_BACKEND.tokens(self) else: return {}
def context_value(): keys = list(get_backends().keys()) accounts = dict(list(zip(keys, [None] * len(keys)))) user = request.user if hasattr(user, "is_authenticated") and user.is_authenticated(): accounts.update( (assoc.provider.replace("-", "_"), assoc) for assoc in UserSocialAuth.get_social_auth_for_user(user) ) return accounts
def admin_home(request): potential_providers = backends.get_backends().keys() for social in request.user.social_auth.all(): if social.provider in potential_providers: potential_providers = [ x for x in potential_providers if x != social.provider ] return render(request, 'admin_home.html', {'potential_providers': potential_providers})
def oauth_discovery(request): from social_auth.backends import get_backends fiware_auth_backend = get_backends()['fiware'] endpoints = { 'auth_endpoint': fiware_auth_backend.AUTHORIZATION_URL, 'token_endpoint': fiware_auth_backend.ACCESS_TOKEN_URL, 'default_redirect_uri': get_absolute_reverse_url('oauth.default_redirect_uri', request), 'version': '2.0', } return HttpResponse(json.dumps(endpoints), content_type='application/json; charset=UTF-8')
def group_backend_by_type(items): """Group items by backend type.""" result = defaultdict(list) backends_defined = get_backends() for item in items: name = getattr(item, 'provider', item) backend = backends_defined[name] if issubclass(backend, OpenIdAuth): result['openid'].append(item) elif issubclass(backend, BaseOAuth2): result['oauth2'].append(item) elif issubclass(backend, BaseOAuth1): result['oauth'].append(item) return dict(result)
def group_backend_by_type(items, key=lambda x: x): """Group items by backend type.""" # Beware of cyclical imports! from social_auth.backends import \ get_backends, OpenIdAuth, BaseOAuth, BaseOAuth2, SocialBackend result = defaultdict(list) backends = get_backends() for item in items: backend = backends[key(item)] if issubclass(backend, SocialBackend): result['social'].append(item) return dict(result)
def social_auth_by_name_backends(request): """Load Social Auth current user data to context. Will add a social_auth object whose attribute names are the names of each provider, e.g. social_auth.facebook would be the facebook association or None, depending on the logged in user's current associations. Providers with a hyphen have the hyphen replaced with an underscore, e.g. google-oauth2 becomes google_oauth2 when referenced in templates. """ keys = get_backends().keys() accounts = dict(zip(keys, [None] * len(keys))) if isinstance(request.user, User) and request.user.is_authenticated(): for associated in request.user.social_auth.all(): accounts[associated.provider.replace('-', '_')] = associated return {'social_auth': accounts}
def setUp(self): """ Get the urls we are going to use. """ self.login_url = reverse('auth_login') self.reset_password_url = reverse('auth_password_reset') self.create_account_url = reverse('registration_register') self.change_password_url = reverse('auth_password_change') self.login_redirect_url = settings.LOGIN_REDIRECT_URL self.social_auth_backends = get_backends() social_auth_names = self.social_auth_backends.keys() self.social_auth_login_urls = [reverse('socialauth_begin', kwargs={'backend':backend}) for backend in social_auth_names]
def group_backend_by_type(items, key=lambda x: x): """Group items by backend type.""" # Beware of cyclical imports! from social_auth.backends import get_backends, BaseOAuth, BaseOAuth2 result = defaultdict(list) backends = get_backends() for item in items: backend = backends[key(item)] if issubclass(backend, BaseOAuth2): result["oauth2"].append(item) elif issubclass(backend, BaseOAuth): result["oauth"].append(item) return dict(result)
def refresh_user_physical_data(user): items = user.social_auth.all() key=lambda x: x backends = get_backends() for item in items: try: backend = backends[key(item.provider)] if issubclass(backend, PhysicalBackend): service = PhysicalServiceLocator.get_instane().get_service_by_name(item.provider) service.pull_user_info(user.id, item.extra_data) except Exception, e: exc_info = sys.exc_info() traceback.print_exception(*exc_info) del exc_info
def group_backend_by_type(items, key=lambda x: x): """Group items by backend type.""" # Beware of cyclical imports! from social_auth.backends import \ get_backends, OpenIdAuth, BaseOAuth, BaseOAuth2 result = defaultdict(list) for item in items: backend = get_backends()[key(item)] if issubclass(backend, OpenIdAuth): result['openid'].append(item) elif issubclass(backend, BaseOAuth2): result['oauth2'].append(item) elif issubclass(backend, BaseOAuth): result['oauth'].append(item) return dict(result)
def account(request): member = request.user.get_profile() #auctions_waiting_payment = member.items_won.filter(Q(shippingorder=None) | # Q(shippingorder__status=ORDER_WAITING_PAYMENT) | # Q(shippingorder__status=ORDER_SHIPPING_FEE_REQUESTED)) auctions_waiting_payment = request.user.items_won.all()#.filter(order=None) #orders processing and shipped auctions_processing = request.user.items_won.filter(order__status=ORDER_PROCESSING) auctions_shipped = request.user.items_won.filter(order__status=ORDER_SHIPPED) available = set(get_backends().keys()) associated = list(request.user.social_auth.all()) not_associated = available.difference(i.provider for i in associated) print request.session.keys() return {'member':member, 'auctions_waiting_payment': auctions_waiting_payment, 'auctions_processing':auctions_processing, 'auctions_shipped': auctions_shipped, 'not_associated':not_associated, 'associated':[i.provider for i in associated], 'available_auth_backends':available, }
def get_backend(self): # Make import here to avoid recursive imports :-/ from social_auth.backends import get_backends return get_backends().get(self.provider)
from django.conf.urls import patterns, include, url from django.utils.translation import ugettext_lazy as _ from django.views.decorators.cache import cache_page from wirecloud.commons.utils.template import TemplateParser from wirecloud.platform.core.plugins import get_version_hash from wirecloud.platform.markets.utils import MarketManager from wirecloud.platform.plugins import WirecloudPlugin, build_url_template import wirecloud.fiware from wirecloud.fiware.marketAdaptor.views import get_market_adaptor, get_market_user_data from wirecloud.fiware.storeclient import UnexpectedResponse try: from social_auth.backends import get_backends IDM_SUPPORT_ENABLED = 'wirecloud.fiware' in settings.INSTALLED_APPS and 'social_auth' in settings.INSTALLED_APPS and 'fiware' in get_backends() FIWARE_SOCIAL_AUTH_BACKEND = get_backends()['fiware'] except: IDM_SUPPORT_ENABLED = False def auth_fiware_token(auth_type, token): from social_auth.models import UserSocialAuth user_data = FIWARE_SOCIAL_AUTH_BACKEND._user_data(token) return UserSocialAuth.objects.get(provider='fiware', uid=user_data['username']).user class FiWareMarketManager(MarketManager): _user = None
def backends_data(user): """Return backends data for given user. Will return a dict with values: associated: UserSocialAuth model instances for currently associated accounts not_associated: Not associated (yet) backend names. backends: All backend names. If user is not authenticated, then first list is empty, and there's no difference between the second and third lists. """ available = get_backends().keys() values = {"social": {'associated': [], 'not_associated':available}, "physical": {'associated': [], 'not_associated':available}, "nutrition": {'associated': [], 'not_associated':available}, "health": {'associated': [], 'not_associated':available}, "genomics": {'associated': [], 'not_associated':available}, 'associated': [], 'not_associated': available, 'backends': available} # Beware of cyclical imports! key=lambda x: x from social_auth.backends import SocialBackend, PhysicalBackend, GenomicsBackend, NutritionBackend, HealthBackend # user comes from request.user usually, on /admin/ it will be an instance # of auth.User and this code will fail if a custom User model was defined if hasattr(user, 'is_authenticated') and user.is_authenticated(): associated = UserSocialAuth.get_social_auth_for_user(user) not_associated = list(set(available) - set(assoc.provider for assoc in associated)) backends = get_backends() not_associated_s = [] not_associated_p = [] not_associated_g = [] not_associated_h = [] not_associated_n = [] for item in associated: backend = backends[key(item.provider)] if issubclass(backend, SocialBackend): values['social']["associated"].append(item.provider) if issubclass(backend, PhysicalBackend): values["physical"]["associated"].append(item.provider) if issubclass(backend, GenomicsBackend): values["genomics"]["associated"].append(item.provider) if issubclass(backend, NutritionBackend): values["nutrition"]["associated"].append(item.provider) if issubclass(backend, HealthBackend): values["health"]["associated"].append(item.provider) for item in not_associated: backend = backends[key(item)] if issubclass(backend, SocialBackend): not_associated_s.append(item) if issubclass(backend, PhysicalBackend): not_associated_p.append(item) if issubclass(backend, GenomicsBackend): not_associated_g.append(item) if issubclass(backend, NutritionBackend): not_associated_n.append(item) if issubclass(backend, HealthBackend): not_associated_h.append(item) values['social']["not_associated"] = not_associated_s values['physical']["not_associated"] = not_associated_p values['genomics']["not_associated"] = not_associated_g values['nutrition']["not_associated"] = not_associated_n values['health']["not_associated"] = not_associated_h values['associated'] = associated values['not_associated'] = not_associated return values