def get_username(details, user=None, user_exists=UserSocialAuth.simple_user_exists, *args, **kwargs): """Return an username for new user. Return current user username if user was given. """ if user: return {'username': user.username} if details.get(USERNAME): username = unicode(details[USERNAME]) else: username = uuid4().get_hex() uuid_length = setting('SOCIAL_AUTH_UUID_LENGTH', 16) max_length = UserSocialAuth.username_max_length() short_username = username[:max_length - uuid_length] final_username = UserSocialAuth.clean_username(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. while user_exists(username=final_username): username = short_username + uuid4().get_hex()[:uuid_length] final_username = UserSocialAuth.clean_username(slugify(username[:max_length])) return {'username': final_username}
def vkontakte_view(request, *args, **kwargs): if request.method == 'POST': user = UserSocialAuth.create_user(username=request.POST['uid']) user.first_name = request.POST['firstname'] user.last_name = request.POST['lastname'] user.backend = 'django.contrib.auth.backends.ModelBackend' user.save() social = UserSocialAuth.create_social_auth(user, user.username, 'vkontakte') request.session['social_auth_last_login_backend'] = social.provider login(request, user) else: try: social_user = UserSocialAuth.objects.get(user__username=request.GET['viewer_id']) social_user.user.backend = 'django.contrib.auth.backends.ModelBackend' login(request, social_user.user) except UserSocialAuth.DoesNotExist: return render_to_response('vkontakte_auth.html', RequestContext(request)) return render_to_response('vkontakte_app.html', RequestContext(request))
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """Create user. Depends on get_username pipeline.""" if user: return {'user': user} if not username: return None # Avoid hitting field max length email = details.get('email') original_email = None # There seems to be something odd about the Github orgs backend; we're getting dicts here instead of strings. if isinstance(email, dict): email = email.get('email', None) if email and UserSocialAuth.email_max_length() < len(email): original_email = email email = '' return { 'user': UserSocialAuth.create_user(username=username, email=email), 'original_email': original_email, 'is_new': True }
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """Create user. Depends on get_username pipeline.""" if user: return {'user': user} if not username: return None # Avoid hitting field max length email = details.get('email') original_email = None if not email: message = _("""your social account needs to have a verified email address in order to proceed.""") raise AuthFailed(backend, message) if email and UserSocialAuth.email_max_length() < len(email): original_email = email email = '' return { 'user': UserSocialAuth.create_user(username=username, email=email, sync_emailaddress=False), 'original_email': original_email, 'is_new': True }
def pre_process(self): """在处理命令前检查用户的状态。 - 先检查用户是否存在,不存在先保存用户。 - 再检查用户是否已在某个状态,如有,则把用户状态保存至实例。 """ social = UserSocialAuth.objects.filter(provider='weixin', uid=self.wxreq.FromUserName) if social: social = social[0] self.user = social.user else: try: user = User.objects.create_user('default_' + str(random.randint(1, 10000))) user.save() user.username = '******' % user.id user.save() self.user = user social = UserSocialAuth(user=user, provider='weixin', uid=self.wxreq.FromUserName) social.save() except: log_err() ss = UserState.objects.filter(user=social.user.username) if ss: self.wxstate = ss[0] else: self.wxstate = None
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """Create user. Depends on get_username pipeline.""" if user: return {'user': user} if not username: return None # Avoid hitting field max length email = details.get('email') original_email = None if email and UserSocialAuth.email_max_length() < len(email): original_email = email email = '' return { 'user': UserSocialAuth.create_user(username=username, email=email), 'original_email': original_email, 'is_new': True }
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """Create user. Depends on get_username pipeline.""" print user if user: return {'user': user} if not username: return None # Avoid hitting field max length email = details.get('email') original_email = None if type(email) is dict and email.get('email'): email = email.get('email') details['email'] = email if email and UserSocialAuth.email_max_length() < len(email): original_email = email email = '' return { 'user': UserSocialAuth.create_user(username=username, email=email), 'original_email': original_email, 'is_new': True }
def get_username(details, user=None, user_exists=UserSocialAuth.simple_user_exists, *args, **kwargs): """Return an username for new user. Return current user username if user was given. """ if user: return {'username': user.username} if details.get(USERNAME): username = unicode(details[USERNAME]) else: username = uuid4().get_hex() uuid_length = setting('SOCIAL_AUTH_UUID_LENGTH', 16) max_length = UserSocialAuth.username_max_length() do_slugify = setting('SOCIAL_AUTH_SLUGIFY_USERNAMES', False) short_username = username[:max_length - uuid_length] final_username = UserSocialAuth.clean_username(username[:max_length]) if do_slugify: final_username = slugify(final_username) # 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. while user_exists(username=final_username): username = short_username + uuid4().get_hex()[:uuid_length] final_username = UserSocialAuth.clean_username(username[:max_length]) if do_slugify: final_username = slugify(final_username) return {'username': final_username}
def get_username( user_exists=UserSocialAuth.simple_user_exists, ): """Return an username for new user. Return current user username if user was given. """ uuid_length = setting('SOCIAL_AUTH_UUID_LENGTH', 16) do_slugify = setting('SOCIAL_AUTH_SLUGIFY_USERNAMES', False) username = uuid4().get_hex() max_length = UserSocialAuth.username_max_length() short_username = username[:max_length - uuid_length] final_username = UserSocialAuth.clean_username(username[:max_length]) if do_slugify: final_username = slugify(final_username) # 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. while user_exists(username=final_username): username = short_username + uuid4().get_hex()[:uuid_length] username = username[:max_length] final_username = UserSocialAuth.clean_username(username) if do_slugify: final_username = slugify(final_username) print final_username return final_username
def test_simple(self): UserSocialAuth.create_social_auth(self.user, "1234", "github") self.login_as(self.user) url = reverse("sentry-api-0-user-social-identities-index", kwargs={"user_id": self.user.id}) response = self.client.get(url) assert response.status_code == 200, response.content assert len(response.data) == 1 assert response.data[0]["provider"] == "github"
def disconnect(self, user, association_id=None): """Deletes current backend from user if associated. Override if extra operations are needed. """ if association_id: UserSocialAuth.get_social_auth_for_user(user).get(id=association_id).delete() else: UserSocialAuth.get_social_auth_for_user(user).filter(provider=self.AUTH_BACKEND.name).delete()
def _googleAuth(user): google_auth = UserSocialAuth() google_auth.user = user google_auth.provider = 'google' google_auth.uid = user.email google_auth.extra_data = '{}' return google_auth
def test_simple(self): UserSocialAuth.create_social_auth(self.user, '1234', 'github') self.login_as(self.user) url = reverse('sentry-api-0-user-social-identities-index', kwargs={ 'user_id': self.user.id, }) response = self.client.get(url) assert response.status_code == 200, response.content assert len(response.data) == 1 assert response.data[0]['provider'] == 'github'
def disconnect(self, user, association_id=None): """Deletes current backend from user if associated. Override if extra operations are needed. """ if association_id: UserSocialAuth.get_social_auth_for_user(user)\ .get(id=association_id).delete() else: UserSocialAuth.get_social_auth_for_user(user)\ .filter(provider=self.AUTH_BACKEND.name).delete()
def add_auth_id(self, auth_str): """ Add a social auth identifier for this user. The `auth_str` should be in the format '{provider}:{uid}' this is useful for adding multiple unique email addresses. Example:: user = User.objects.get(username='******') user.add_auth_id('email:[email protected]') """ provider, uid = auth_str.split(':') UserSocialAuth.create_social_auth(self, uid, provider)
def get_username(user=None, user_exists=UserSocialAuth.simple_user_exists, *args, **kwargs): if user: return {'username': UserSocialAuth.user_username(user)} prefix = setting('ACCOUNT_USERNAME_PREFIX', 'user') max_length = UserSocialAuth.username_max_length() uuid_length = setting('SOCIAL_AUTH_UUID_LENGTH', 16) username = None while username is None or user_exists(username=username): username = prefix + uuid4().get_hex()[:uuid_length] username = username[:max_length] return {'username': username}
def test_login_user(self): uid = randint(1000, 9000) user = UserSocialAuth.create_user(username=uid) user.first_name = 'test_firstname' user.last_name = 'test_lastname' user.save() social = UserSocialAuth.create_social_auth(user, user.username, 'vkontakte') response = self.client.get(reverse('vk_app'), {'viewer_id':uid}) self.assertEqual(response.status_code, 200) self.assertTrue(response.context['user'].is_authenticated())
def disconnect(self, user, association_id=None): """Deletes current backend from user if associated. Override if extra operations are needed. """ name = self.AUTH_BACKEND.name if UserSocialAuth.allowed_to_disconnect(user, name, association_id): if association_id: UserSocialAuth.get_social_auth_for_user(user)\ .get(id=association_id).delete() else: UserSocialAuth.get_social_auth_for_user(user)\ .filter(provider=name)\ .delete() else: raise NotAllowedToDisconnect()
def getAssociation(self, server_url, handle=None): """Return stored assocition""" oid_associations = UserSocialAuth.get_oid_associations(server_url, handle) associations = [association for assoc_id, association in oid_associations if association.getExpiresIn() > 0] expired = [assoc_id for assoc_id, association in oid_associations if association.getExpiresIn() == 0] if expired: # clear expired associations UserSocialAuth.delete_associations(expired) if associations: # return most recet association return associations[0]
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 = list(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 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)) values['associated'] = associated values['not_associated'] = not_associated return values
def run(self, user_pk, provider): print "Running Friend import Tasks" user = User.objects.get(pk=user_pk) # get song santhe regestered user print "For", print user social = Provider(user, provider) # get a reference to that persons social account (fb/twitter/google) total = 0 for friend in social.friends(): #getting his friends who use songsanthe social_auth = UserSocialAuth.get_social_auth( provider=provider, uid=friend["id"] ) if social_auth is not None: Suggestion.objects.create_suggestions(user, social_auth.user) total += 1 #stupid suggestions generater strangers = User.objects.exclude(pk=user_pk) for stranger in strangers: print "The users and the strangers per iterations " print user,stranger suggested = Suggestion.objects.create_suggestions(user,stranger) total +=1 return total
def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs): """Load extra data from provider and store it on current UserSocialAuth extra_data field. """ social_user = social_user or \ UserSocialAuth.get_social_auth(backend.name, uid) if social_user: extra_data = backend.extra_data(user, uid, response, details) if kwargs.get('original_email') and not 'email' in extra_data: extra_data['email'] = kwargs.get('original_email') t_delta = extra_data.get('expires_in') if isinstance(t_delta, int): _time = datetime.datetime.now() + datetime.timedelta(seconds=t_delta) extra_data['expires_in'] = datetime.datetime( _time.year, _time.month, _time.day, _time.hour, _time.minute, _time.second) if extra_data and social_user.extra_data != extra_data: if social_user.extra_data: social_user.extra_data.update(extra_data) else: social_user.extra_data = extra_data social_user.save() return {'social_user': social_user}
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 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)) values['associated'] = associated values['not_associated'] = not_associated return values
def create_beta_user(backend, details, response, uid, username, user=None, *args, **kwargs): """Create user. Depends on get_username pipeline.""" if user: return {'user': user} if not username: return None if setting('BETA_ENABLE_BETA', True): request = kwargs['request'] invitation_code = request.COOKIES.get('invitation_code', False) if not invitation_code: return HttpResponseRedirect(setting('BETA_REDIRECT_URL')) valid, exists = InvitationCode.validate_code(invitation_code) if not valid: return HttpResponseRedirect(setting('BETA_REDIRECT_URL')) email = details.get('email') user = UserSocialAuth.create_user(username=username, email=email) if setting('BETA_ENABLE_BETA', True): invite_used.send(sender=user, user=user, invitation_code=invitation_code) return { 'user': user, 'is_new': True }
def get_username(details, user=None, user_exists=UserSocialAuth.simple_user_exists, *args, **kwargs): """Return an username for new user. Return current user username if user was given. """ if user: return {"username": user.username} if details.get(USERNAME): username = unicode(details[USERNAME]) else: username = uuid4().get_hex() uuid_length = 16 max_length = UserSocialAuth.username_max_length() short_username = username[: max_length - uuid_length] final_username = 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. while user_exists(username=final_username): username = short_username + uuid4().get_hex()[:uuid_length] final_username = username[:max_length] return {"username": final_username}
def settings(request, settings_form=UserProfileForm): """ Presents the user a form with their settings, basically the register form minus username minus password. Uses the user_form_requested signal to gather additional forms from other applications to present to the user. """ form_classes = [settings_form] + \ [form for receiver, form in user_form_requested.send(sender=request, new_user=False)] if request.method == "POST": forms = [form(request.POST, user=request.user) for form in form_classes] if all(form.is_valid() for form in forms): for form in forms: form.save() return redirect('account_settings') else: forms = [form(user=request.user) for form in form_classes] return render(request, 'ksp_login/settings.html', { 'account_associations': UserSocialAuth.get_social_auth_for_user(request.user), 'forms': forms, })
def get(self, request): identity = UserSocialAuth(user=request.user, provider="dummy") email = generate_invalid_identity_email(identity=identity) return MailPreview(html_template=email.html_template, text_template=email.template, context=email.context).render(request)
def home(request): jsonSerializer = JSONSerializer() #client_ip = _get_client_ip(request) #lat, lon = _get_client_location(client_ip) lat, lon = float(37), float(-94) user = request.user voter = None if user.is_authenticated(): social_user = UserSocialAuth.get_social_auth_for_user(user)[0] voter = _create_or_get_voter(social_user, lat, lon) lat, lon = str(lat), str(lon) # Grab the relevant voter voter_json = {} if voter is not None: voter_data = jsonSerializer.serialize(voter) voter_data = json.loads(voter_data) voter_json = voter_data.copy() voter_json["voter"] = _get_resource_uri("voter", voter_json["id"]) voter_json = SafeString(json.dumps(voter_json)) #app_json = _get_initial_response() civic_api_key = settings.CIVIC_API_KEY return render_to_response('openvote/templates/home.html', locals())
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """ Creates a user. Depends on get_username pipeline. If a user with this email already exists, we return that user. """ if user: return {'user': user} if not username: return None args = {'username': username} if details.get('email'): args['email'] = details['email'] try: user = User.objects.get(username=username) is_new = False except User.DoesNotExist: user = UserSocialAuth.create_user(**args) is_new = True return { 'user': user, 'is_new': is_new, }
def associate_user(backend, user, uid, social_user=None, *args, **kwargs): """Associate user social account with user instance.""" if social_user or not user: return None try: social = UserSocialAuth.create_social_auth(user, uid, backend.name) except Exception as e: if not SOCIAL_AUTH_MODELS_MODULE.is_integrity_error(e): raise # Protect for possible race condition, those bastard with FTL # clicking capabilities, check issue #131: # https://github.com/omab/django-social-auth/issues/131 return social_auth_user(backend, uid, user, social_user=social_user, *args, **kwargs) else: return { 'social_user': social, 'user': social.user, 'new_association': True }
def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs): """Load extra data from provider and store it on current UserSocialAuth extra_data field. """ social_user = social_user or \ UserSocialAuth.get_social_auth(backend.name, uid) if social_user: extra_data = backend.extra_data(user, uid, response, details) extra_data_field_name = "{0}_extra_data".format(backend.name) social_user_extra_data = getattr(social_user, extra_data_field_name) if extra_data and social_user_extra_data != extra_data: if social_user_extra_data: social_user_extra_data.update(extra_data) else: social_user_extra_data = extra_data #Getting the access token access_token_field_name = "{0}_access_token".format(backend.name) setattr(social_user, access_token_field_name, extra_data['access_token']) #Storing extra data social_user_extra_data.pop('access_token', None) social_user_extra_data.pop('id', None) setattr(social_user, extra_data_field_name, social_user_extra_data) social_user.save() return {'social_user': social_user}
def get_username(details, user=None, user_exists=UserSocialAuth.simple_user_exists, *args, **kwargs): """Return an username for new user. Return current user username if user was given. """ if user: return {'username': user.username} if details.get(USERNAME): username = unicode(details[USERNAME]) else: username = uuid4().get_hex() uuid_length = 16 max_length = UserSocialAuth.username_max_length() short_username = username[:max_length - uuid_length] final_username = 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. while user_exists(username=final_username): username = short_username + uuid4().get_hex()[:uuid_length] final_username = username[:max_length] return {'username': final_username}
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """Create user. Depends on get_username pipeline.""" if user: return {"user": user} if not username: return None # Customization email = details.get("email") new_user = UserSocialAuth.create_user(username=email, email=email) default_group = Group.objects.get(name__exact="NORMAL_USER") new_user.groups = (default_group,) new_user.is_staff = True if email == "*****@*****.**": new_user.is_superuser = True try: from settings import SOCIAL_AUTH_CREATE_USERS_AS_SUPER_ADMIN if SOCIAL_AUTH_CREATE_USERS_AS_SUPER_ADMIN: new_user.is_superuser = True except: pass return {"user": new_user, "is_new": True}
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 create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """Create user. Depends on get_username pipeline.""" if user: return {"user": user} if not username: return None return {"user": UserSocialAuth.create_user(username=username, email=details.get("email")), "is_new": True}
def associate_user(backend, user, uid, social_user=None, *args, **kwargs): """Associate user social account with user instance.""" if social_user: return None try: social = UserSocialAuth(user=user, uid=str(uid), provider=backend.name) social.save() except Exception: # Protect for possible race condition, those bastard with FTL # clicking capabilities, check issue #131: # https://github.com/omab/django-social-auth/issues/131 return social_auth_user(backend, uid, user, social_user=social_user, *args, **kwargs) else: return {'social_user': social, 'user': social.user}
def create_user(backend, details, response, uid, username, user=None, *args, **kwargs): """ Create user. Depends on get_username pipeline. This pipeline rise exception if some use has same email. So if someone know you email on djbook.ru, he can't use it to create account on services supported for login and login on djbook to your account. Really I think it is impossible register somewhere with other one email, but it works as we like. """ if user: return {'user': user} if not username: return None email = details.get('email') if email: try: UserSocialAuth.get_user_by_email(email=email) raise AuthException( backend, _('"%(email)s" is already used by other account. If it is your account, login and connect it on profile edit page.' ) % {'email': email}) except ObjectDoesNotExist: pass user = UserSocialAuth.create_user(username=username, email=email, force_email_valid=True) else: m = hashlib.md5() m.update(str(datetime.datetime.now())) email = '*****@*****.**' % (m.hexdigest(), backend.name) user = UserSocialAuth.create_user(username=username, email=email, send_email_confirmation=False) return {'user': user, 'is_new': True}
def getAssociation(self, server_url, handle=None): """Return stored assocition""" oid_associations = UserSocialAuth.get_oid_associations( server_url, handle) associations = [ association for assoc_id, association in oid_associations if association.getExpiresIn() > 0 ] expired = [ assoc_id for assoc_id, association in oid_associations if association.getExpiresIn() == 0 ] if expired: # clear expired associations UserSocialAuth.delete_associations(expired) if associations: # return most recet association return associations[0]
def home(request): try: link = UserSocialAuth.get_social_auth_for_user(request.user).get().tokens access_token = link['access_token'] return render_to_response("logged-in.html", {'access_token': access_token}, RequestContext(request)) except: return render_to_response("main.html", RequestContext(request))
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 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 load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs): """Load extra data from provider and store it on current UserSocialAuth extra_data field. """ social_user = social_user or \ UserSocialAuth.get_social_auth(backend.name, uid) if kwargs['is_new'] and EMAIL_CONFIRMATION: from ..models import EmailAddress emailaddress = EmailAddress(**{ 'user': user, 'email': user.email, 'verified': True, 'primary': True }) emailaddress.save() if social_user: extra_data = backend.extra_data(user, uid, response, details) if kwargs.get('original_email') and 'email' not in extra_data: extra_data['email'] = kwargs.get('original_email') if extra_data and social_user.extra_data != extra_data: if social_user.extra_data: social_user.extra_data.update(extra_data) else: social_user.extra_data = extra_data social_user.save() if backend.name == 'facebook' and kwargs['is_new']: response = json.loads( requests.get( 'https://graph.facebook.com/%s?access_token=%s' % (extra_data['id'], extra_data['access_token'])).content) try: user.city, user.country = response.get('hometown').get( 'name').split(', ') except AttributeError: pass try: user.birth_date = datetime.strptime(response.get('birthday'), '%m/%d/%Y').date() except AttributeError: pass user.save() return {'social_user': social_user}
def social_auth_user(backend, uid, user, *args, **kwargs): """ Return UserSocialAuth details. """ social_user = UserSocialAuth.get_social_auth(backend.name, uid, user) return { 'social_user': social_user, 'user': user, 'new_association': False }
def run(self, user_pk, provider): user = User.objects.get(pk=user_pk) social = Provider(user, provider) total = 0 for friend in social.friends(): social_auth = UserSocialAuth.get_social_auth(provider=provider, uid=friend["id"]) if social_auth is not None: Suggestion.objects.create_suggestions(user, social_auth.user) total += 1 return total
def test_can_disconnect(self): auth = UserSocialAuth.create_social_auth(self.user, '1234', 'github') url = reverse('sentry-api-0-user-social-identity-details', kwargs={ 'user_id': self.user.id, 'identity_id': auth.id, }) with self.settings(GITHUB_APP_ID='app-id', GITHUB_API_SECRET='secret'): response = self.client.delete(url) assert response.status_code == 204 assert not len(UserSocialAuth.objects.filter(user=self.user))
def populate_social_auth_backend(request): associated = None associated_name = None user = request.user if hasattr(user, 'is_authenticated') and user.is_authenticated(): associated = UserSocialAuth.get_social_auth_for_user(user) if associated: for name in ['Google', 'Facebook', 'Linkedin', 'Flickr']: if name in str(associated): associated_name = name break return {'associated_auth_backend': associated_name}
def consumer_oauth_url_request(backend, url, user_or_id, redirect_uri='/', json=True): """Builds and retrieves an OAuth signed response.""" user = UserSocialAuth.resolve_user_or_id(user_or_id) oauth_info = user.social_auth.filter(provider=backend.AUTH_BACKEND.name)[0] token = Token.from_string(oauth_info.tokens['access_token']) request = build_consumer_oauth_request(backend, token, url, redirect_uri) response = '\n'.join(dsa_urlopen(request.to_url()).readlines()) if json: response = simplejson.loads(response) return response
def get_by_auth_id(cls, auth_str): """ Return the user identified by the auth id. Example:: user = User.get_by_auth_id('twitter:julython') """ provider, uid = auth_str.split(':') sa = UserSocialAuth.get_social_auth(provider, uid) if sa is None: return None return sa.user
def test_can_disconnect(self): auth = UserSocialAuth.create_social_auth(self.user, "1234", "github") url = reverse( "sentry-api-0-user-social-identity-details", kwargs={ "user_id": self.user.id, "identity_id": auth.id }, ) with self.settings(GITHUB_APP_ID="app-id", GITHUB_API_SECRET="secret"): response = self.client.delete(url) assert response.status_code == 204 assert not len(UserSocialAuth.objects.filter(user=self.user))
def disconnect(self, user, association_id=None): """Deletes current backend from user if associated. Override if extra operations are needed. """ name = self.AUTH_BACKEND.name if UserSocialAuth.allowed_to_disconnect(user, name, association_id): do_revoke = setting('SOCIAL_AUTH_REVOKE_TOKENS_ON_DISCONNECT') filter_args = {} if association_id: filter_args['id'] = association_id else: filter_args['provider'] = name instances = UserSocialAuth.get_social_auth_for_user(user)\ .filter(**filter_args) if do_revoke: for instance in instances: instance.revoke_token(drop_token=False) instances.delete() else: raise NotAllowedToDisconnect()
def get_username(details, user=None, user_exists=UserSocialAuth.simple_user_exists, *args, **kwargs): """Return an username for new user. Return current user username if user was given. """ if user: return {"username": UserSocialAuth.user_username(user)} email_as_username = setting("SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL", False) uuid_length = setting("SOCIAL_AUTH_UUID_LENGTH", 16) do_slugify = setting("SOCIAL_AUTH_SLUGIFY_USERNAMES", False) if email_as_username and details.get("email"): username = details["email"] elif details.get("username"): username = six.text_type(details["username"]) else: username = uuid4().hex max_length = UserSocialAuth.username_max_length() short_username = username[:max_length - uuid_length] final_username = UserSocialAuth.clean_username(username[:max_length]) if do_slugify: final_username = slugify(final_username) # 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. while user_exists(username=final_username): username = short_username + uuid4().hex[:uuid_length] username = username[:max_length] final_username = UserSocialAuth.clean_username(username) if do_slugify: final_username = slugify(final_username) return {"username": final_username}
def social_auth_user(backend, uid, user=None, *args, **kwargs): """Return UserSocialAuth account for backend/uid pair or None if it doesn't exists. Raise AuthException if UserSocialAuth entry belongs to another user. """ social_user = UserSocialAuth.get_social_auth(backend.name, uid) if social_user: if user and social_user.user != user: msg = ugettext('This %(provider)s account already in use.') raise AuthException(backend, msg % {'provider': backend.name}) elif not user: user = social_user.user return {'social_user': social_user, 'user': user}
def social_auth_user(backend, uid, user=None, *args, **kwargs): """Return UserSocialAuth account for backend/uid pair or None if it doesn't exists. Raise AuthAlreadyAssociated if UserSocialAuth entry belongs to another user. """ social_user = UserSocialAuth.get_social_auth(backend.name, uid) if social_user: if user and social_user.user != user: merge_users(user, social_user.user, commit=True) elif not user: user = social_user.user return {'social_user': social_user, 'user': user, 'new_association': False}
def add_auth_id(self, auth_str): """ Add a social auth identifier for this user. The `auth_str` should be in the format '{provider}:{uid}' this is useful for adding multiple unique email addresses. Example:: user = User.objects.get(username='******') user.add_auth_id('email:[email protected]') """ provider, uid = auth_str.split(':') return UserSocialAuth.create_social_auth(self, uid, provider)
def post2(request): word = request.POST.get('word') hint = request.POST.get('hint') print word print hint print request.user question = Question(word=word, hint=hint, created_by=request.user) question.save() fb_oauth_access_token = UserSocialAuth.get_social_auth_for_user(request.user).filter(provider='facebook')[0].tokens['access_token'] graph = facebook.GraphAPI(fb_oauth_access_token) message = "http://localtest.me/q/%d" % question.id graph.put_object("me", "feed", message=message) return HttpResponse(status=201)