def _process_signup(request, sociallogin): auto_signup = get_adapter().is_auto_signup_allowed(request, sociallogin) if not auto_signup: request.session['socialaccount_sociallogin'] = sociallogin.serialize() url = reverse('socialaccount_signup') ret = HttpResponseRedirect(url) else: # Ok, auto signup it is, at least the e-mail address is ok. # We still need to check the username though... if account_settings.USER_MODEL_USERNAME_FIELD: username = user_username(sociallogin.user) try: get_account_adapter().clean_username(username) except ValidationError: # This username is no good ... user_username(sociallogin.user, '') # FIXME: This part contains a lot of duplication of logic # ("closed" rendering, create user, send email, in active # etc..) try: if not get_adapter().is_open_for_signup(request, sociallogin): return render(request, "account/signup_closed.html") except ImmediateHttpResponse as e: return e.response get_adapter().save_user(request, sociallogin, form=None) ret = complete_social_signup(request, sociallogin) return ret
def save_user(self, request, new_social_login, form, commit=False): """if a user who has an account already created logs in, merge the two accounts (rather than complaining about duplicate email addresses) """ # cf: # https://github.com/pennersr/django-allauth/blob/0367b51514e592db011511e420570789c7d1df75/allauth/socialaccount/models.py#L158 # https://github.com/pennersr/django-allauth/blob/0367b51514e592db011511e420570789c7d1df75/allauth/socialaccount/adapter.py#L70 serialized = new_social_login.serialize() new_user_email = serialized['email_addresses'][0]['email'] # if there's another user with this same email address # (that's unpaired with the Google Account)... # delete the new one and merge it's social account with the old one. already_existing_user = User.objects.all().filter( email=new_user_email).first() if already_existing_user and not already_existing_user.socialaccount_set.count( ): new_social_login.connect(user=already_existing_user, request=request) already_existing_user.first_name = new_social_login.account.extra_data[ 'given_name'] already_existing_user.last_name = new_social_login.account.extra_data[ 'family_name'] already_existing_user.save() else: new_user = new_social_login.user new_user.set_unusable_password() if form: get_account_adapter().save_user(request, new_user, form) else: get_account_adapter().populate_username(request, new_user) new_social_login.save(request) return new_social_login.user
def _add_social_account(request, sociallogin): if request.user.is_anonymous(): # This should not happen. Simply redirect to the connections # view (which has a login required) return HttpResponseRedirect(reverse('socialaccount_connections')) level = messages.INFO message = 'socialaccount/messages/account_connected.txt' if sociallogin.is_existing: if sociallogin.user != request.user: # Social account of other user. For now, this scenario # is not supported. Issue is that one cannot simply # remove the social account from the other user, as # that may render the account unusable. level = messages.ERROR message = 'socialaccount/messages/account_connected_other.txt' else: # This account is already connected -- let's play along # and render the standard "account connected" message # without actually doing anything. pass else: # New account, let's connect sociallogin.connect(request, request.user) try: signals.social_account_added.send(sender=SocialLogin, request=request, sociallogin=sociallogin) except ImmediateHttpResponse as e: return e.response default_next = get_adapter() \ .get_connect_redirect_url(request, sociallogin.account) next_url = sociallogin.get_redirect_url(request) or default_next get_account_adapter().add_message(request, level, message) return HttpResponseRedirect(next_url)
def _complete_social_login(request, sociallogin, response): if request.user.is_authenticated(): get_account_adapter().logout(request) if sociallogin.is_existing: # Login existing user ret = _login_social_account(request, sociallogin) else: # New social user ret = _process_signup(request, sociallogin) try: url = response['profile_image_url'] except Exception: url = response.get('picture') if type(url) is dict: # Incase of facebook response dict is different. url = response.get('picture').get('data').get('url') if url: url = urllib.request.urlopen(url) file = BytesIO(url.read()) img = ImageFile(file) filename = '%s_original.jpg' % (uuid.uuid4()) img.name = filename # ser = ImageSerializer(img) Image.objects.create( image=img, title=img.name, content_object=sociallogin.user, object_id=sociallogin.user.id, image_type='P') return ret
def _add_social_account(request, sociallogin): if request.user.is_anonymous(): # This should not happen. Simply redirect to the connections # view (which has a login required) return HttpResponseRedirect(reverse('socialaccount_connections')) level = messages.INFO message = 'socialaccount/messages/account_connected.txt' if sociallogin.is_existing: if sociallogin.account.user != request.user: # Social account of other user. For now, this scenario # is not supported. Issue is that one cannot simply # remove the social account from the other user, as # that may render the account unusable. level = messages.ERROR message = 'socialaccount/messages/account_connected_other.txt' else: # This account is already connected -- let's play along # and render the standard "account connected" message # without actually doing anything. pass else: # New account, let's connect sociallogin.connect(request, request.user) try: signals.social_account_added.send(sender=SocialLogin, request=request, sociallogin=sociallogin) except ImmediateHttpResponse as e: return e.response default_next = get_adapter() \ .get_connect_redirect_url(request, sociallogin.account) next_url = sociallogin.get_redirect_url(request) or default_next get_account_adapter().add_message(request, level, message) return HttpResponseRedirect(next_url)
def form_valid(self, form): get_account_adapter().add_message(self.request, messages.INFO, 'socialaccount/messages/' 'account_disconnected.txt') form.save() return super(IntegrationsView, self).form_valid(form)
def _process_signup(request, sociallogin): auto_signup = get_adapter(request).is_auto_signup_allowed( request, sociallogin) if not auto_signup: request.session['socialaccount_sociallogin'] = sociallogin.serialize() url = reverse('socialaccount_signup') if hasattr(settings, 'SOCIALACCOUNT_SIGNUP_URL'): name = sociallogin.serialize()['account']['extra_data']['username'] phone = sociallogin.serialize()['account']['extra_data']['phone'] url = settings.SOCIALACCOUNT_SIGNUP_URL url += '?type=bind&nickname={}&phone={}'.format(name, phone) ret = HttpResponseRedirect(url) else: # Ok, auto signup it is, at least the e-mail address is ok. # We still need to check the username though... if account_settings.USER_MODEL_USERNAME_FIELD: username = user_username(sociallogin.user) try: get_account_adapter(request).clean_username(username) except ValidationError: # This username is no good ... user_username(sociallogin.user, '') # FIXME: This part contains a lot of duplication of logic # ("closed" rendering, create user, send email, in active # etc..) if not get_adapter(request).is_open_for_signup(request, sociallogin): return render( request, "account/signup_closed." + account_settings.TEMPLATE_EXTENSION) get_adapter(request).save_user(request, sociallogin, form=None) ret = complete_social_signup(request, sociallogin) return ret
def post(self, request, *args, **kwargs): current_url = self.request.get_full_path() social_application = current_url.split('/')[6] for account in request.user.socialaccount_set.all(): if account.provider == social_application: social_account = account branding = account.get_provider().name # we do not need to use validate_disconnect, because accounts are not # associated with being able to log in try: social_account.delete() social_account_removed.send(sender=SocialAccount, request=request, socialaccount=social_account) message = "%s has been successfully disconnected." % branding messages.add_message(self.request, messages.SUCCESS, message) # if multiple posts went in, there won't be any 'social_account' or 'branding' # basically, that means it's already gone and it already works except UnboundLocalError: get_account_adapter().add_message(self.request, messages.SUCCESS, 'socialaccount/messages/' 'account_disconnected.txt') return HttpResponseRedirect(self.get_success_url())
def _process_signup(request, sociallogin): email = sociallogin.account.extra_data.get('email') if email: if account_settings.USER_MODEL_USERNAME_FIELD: username = user_username(sociallogin.user) try: get_account_adapter(request).clean_username(username) except ValidationError: # This username is no good ... user_username(sociallogin.user, '') try: if not get_adapter(request).is_open_for_signup( request, sociallogin): return render( request, "account/signup_closed." + account_settings.TEMPLATE_EXTENSION) except ImmediateHttpResponse as e: return e.response # Since user is getting registered via social account # explicitly mark it as active. sociallogin.user.is_active = True get_adapter(request).save_user(request, sociallogin, form=None) ret = complete_social_signup(request, sociallogin) # New signup send email. from users.emails import Email Email().user_welcome(user=sociallogin.user, request=request) return ret else: raise ValidationError( "Your social account doesn't have email associated.")
def _process_signup(request, sociallogin): auto_signup = get_adapter(request).is_auto_signup_allowed( request, sociallogin) if not auto_signup: request.session['socialaccount_sociallogin'] = sociallogin.serialize() url = reverse('socialaccount_signup') ret = HttpResponseRedirect(url) else: # Ok, auto signup it is, at least the email address is ok. # We still need to check the username though... if account_settings.USER_MODEL_USERNAME_FIELD: username = user_username(sociallogin.user) try: get_account_adapter(request).clean_username(username) except ValidationError: # This username is no good ... user_username(sociallogin.user, '') # FIXME: This part contains a lot of duplication of logic # ("closed" rendering, create user, send email, in active # etc..) if not get_adapter(request).is_open_for_signup( request, sociallogin): return render( request, "account/signup_closed." + account_settings.TEMPLATE_EXTENSION) get_adapter(request).save_user(request, sociallogin, form=None) ret = complete_social_signup(request, sociallogin) return ret
def _process_signup(request, sociallogin): # If email is specified, check for duplicate and if so, no auto signup. auto_signup = app_settings.AUTO_SIGNUP email = sociallogin.account.user.email if auto_signup: # Let's check if auto_signup is really possible... if email: if account_settings.UNIQUE_EMAIL: try: user = User.objects.get(email__iexact=email) # Oops, another user already has this address. We # cannot simply connect this social account to the # existing user. Reason is that the email adress may # not be verified, meaning, the user may be a hacker # that has added your email address to his account in # the hope that you fall in his trap. To solve this, # we reset the password of the email account and connect # the user. user.set_password(md5.new('%s:%s ' % (email, time.time())).hexdigest()) user.save() context = create_password_reset_context(user) get_account_adapter().send_mail('account/email/link_facebook', email, context) sociallogin.account.user = user sociallogin.save() return perform_login(request, user, redirect_url=sociallogin.get_redirect_url(request)) except User.DoesNotExist: # No user exists with this email. Let's auto sign up the user. auto_signup = True elif account_settings.EMAIL_REQUIRED: # Nope, email is required and we don't have it yet... auto_signup = False if not auto_signup: request.session['socialaccount_sociallogin'] = sociallogin url = reverse('socialaccount_signup') ret = HttpResponseRedirect(url) else: # FIXME: This part contains a lot of duplication of logic # ("closed" rendering, create user, send email, in active # etc..) try: if not get_account_adapter().is_open_for_signup(request): return render(request, "account/signup_closed.html") except ImmediateHttpResponse, e: return e.response u = sociallogin.account.user u.username = generate_unique_username(u.username or email or 'user') u.last_name = (u.last_name or '') \ [0:User._meta.get_field('last_name').max_length] u.first_name = (u.first_name or '') \ [0:User._meta.get_field('first_name').max_length] u.email = email or '' u.set_unusable_password() sociallogin.save() send_email_confirmation(request, u) ret = complete_social_signup(request, sociallogin)
def pre_social_login(self, request, sociallogin): social_email = sociallogin.email_addresses[0].email if sociallogin.email_addresses else '' try: email_user = User.objects.get(email=social_email) except User.DoesNotExist: email_user = None # If user signed up using email but not yet verified, and used Social Network account for signup, # we deliberately verify it (with assumption that email from social network is already verified). try: unverified_email = EmailAddress.objects.get(user=email_user, verified=False) get_account_adapter(request).confirm_email(request, unverified_email) except EmailAddress.DoesNotExist: pass # If user already have account registered by email, it will connect them together. if email_user and not sociallogin.is_existing: sociallogin.connect(request, email_user) if not email_user.profile_image: save_profile_image_from_url(email_user, sociallogin.account.get_avatar_url()) # Load user profile image from social network to temp, unless user already have one. if not email_user: save_temp_profile_image_from_url(sociallogin)
def save_user(self, request, sociallogin, form=None): """ Saves a newly signed up social login. In case of auto-signup, the signup form is not available. """ u = sociallogin.user u.set_unusable_password() if form: get_account_adapter().save_user(request, u, form) else: get_account_adapter().populate_username(request, u) u.username = u.email sociallogin.save(request) try: if sociallogin.account.provider == 'facebook': sociallogin.user.profile.picture = "https://graph.facebook.com/" + sociallogin.account.extra_data[ 'id'] + "/picture?type=large" if sociallogin.account.provider == 'google': sociallogin.user.profile.picture = sociallogin.account.extra_data[ 'picture'] sociallogin.user.profile.save() except: pass return u
def form_valid(self, form): form.save() get_account_adapter().add_message(self.request, messages.SUCCESS, 'account/messages/password_set.txt') signals.password_set.send(sender=self.request.user.__class__, request=self.request, user=self.request.user) return super(PasswordSetView, self).form_valid(form)
def save_user(self, request, sociallogin, form=None, commit=True): u = sociallogin.user u.set_unusable_password() if form: get_account_adapter().save_user(request, u, form, commit) else: get_account_adapter().populate_username(request, u, commit) sociallogin.save(request) return u
def save(self, request): self.cleaned_data = self.validated_data # Needed by new_user() user = get_account_adapter().new_user(request) original_request = request._request get_account_adapter().save_user(request, user, self) setup_user_email(request, user, []) complete_signup(original_request, user, allauth_settings.EMAIL_VERIFICATION, None) return user
def _complete_social_login(request, sociallogin): if request.user.is_authenticated(): get_account_adapter().logout(request) if sociallogin.is_existing: # Login existing user ret = _login_social_account(request, sociallogin) else: # New social user ret = _process_signup(request, sociallogin) return ret
def _complete_social_login(request, sociallogin): if is_authenticated(request.user): get_account_adapter(request).logout(request) if sociallogin.is_existing: # Login existing user ret = _login_social_account(request, sociallogin) else: # New social user ret = _process_signup(request, sociallogin) return ret
def save_user(self, request, sociallogin, form=None): """ Saves a newly signed up social login. In case of auto-signup, the signup form is not available. """ u = sociallogin.user u.set_unusable_password() u.id = request.user.id get_account_adapter().populate_username(request, u) LazyUser.objects.filter(user=u).delete() sociallogin.save(request) return u
def _complete_social_login(request, sociallogin): if request.user.is_authenticated: get_account_adapter(request).logout(request) if sociallogin.is_existing: # Login existing user ret = _login_social_account(request, sociallogin) signals.social_account_updated.send(sender=SocialLogin, request=request, sociallogin=sociallogin) else: # New social user ret = _process_signup(request, sociallogin) return ret
def _process_signup(request, sociallogin): # If email is specified, check for duplicate and if so, no auto signup. auto_signup = app_settings.AUTO_SIGNUP email = user_email(sociallogin.account.user) if auto_signup: # Let's check if auto_signup is really possible... if email: if account_settings.UNIQUE_EMAIL: if email_address_exists(email): # Oops, another user already has this address. We # cannot simply connect this social account to the # existing user. Reason is that the email adress may # not be verified, meaning, the user may be a hacker # that has added your email address to his account in # the hope that you fall in his trap. We cannot check # on 'email_address.verified' either, because # 'email_address' is not guaranteed to be verified. auto_signup = False # FIXME: We redirect to signup form -- user will # see email address conflict only after posting # whereas we detected it here already. elif app_settings.EMAIL_REQUIRED: # Nope, email is required and we don't have it yet... auto_signup = False if not auto_signup: request.session['socialaccount_sociallogin'] = sociallogin.serialize() url = reverse('socialaccount_signup') ret = HttpResponseRedirect(url) else: # Ok, auto signup it is, at least the e-mail address is ok. # We still need to check the username though... if account_settings.USER_MODEL_USERNAME_FIELD: username = user_username(sociallogin.account.user) try: get_account_adapter().clean_username(username) except ValidationError: # This username is no good ... user_username(sociallogin.account.user, '') # FIXME: This part contains a lot of duplication of logic # ("closed" rendering, create user, send email, in active # etc..) try: if not get_adapter().is_open_for_signup(request, sociallogin): return render(request, "account/signup_closed.html") except ImmediateHttpResponse as e: return e.response get_adapter().save_user(request, sociallogin, form=None) ret = complete_social_signup(request, sociallogin) return ret
def _complete_social_login(request, sociallogin): if request.user.is_authenticated: get_account_adapter(request).logout(request) if sociallogin.is_existing: # Login existing user ret = _login_social_account(request, sociallogin) signals.social_account_updated.send( sender=SocialLogin, request=request, sociallogin=sociallogin) else: # New social user ret = _process_signup(request, sociallogin) return ret
def save_user(self, request, sociallogin, form=None): """ Saves a newly signed up social login. In case of auto-signup, the signup form is not available. """ u = sociallogin.user u.set_unusable_password() u.is_active = True if form: get_account_adapter().save_user(request, u, form) else: get_account_adapter().populate_username(request, u) sociallogin.save(request) return u
def _complete_social_login(request, sociallogin): if django.VERSION < (1, 10): authenticated = request.user.is_authenticated() else: authenticated = request.user.is_authenticated if authenticated: get_account_adapter().logout(request) if sociallogin.is_existing: # Login existing user ret = _login_social_account(request, sociallogin) else: # New social user ret = _process_signup(request, sociallogin) return ret
def callback(request): if request.user.is_authenticated: get_account_adapter(request).logout(request) # logging in while being authenticated breaks the login procedure current_app = SocialApp.objects.get_current(provider='edu_id') #extract state of redirect state = json.loads(request.GET.get('state')) referer, badgr_app_pk, lti_context_id,lti_user_id,lti_roles = state lti_data = request.session.get('lti_data', None); code = request.GET.get('code', None) # access codes to access user info endpoint if code is None: #check if code is given error = 'Server error: No userToken found in callback' logger.debug(error) return render_authentication_error(request, EduIDProvider.id, error=error) # 1. Exchange callback Token for access token payload = { "grant_type": "authorization_code", "redirect_uri": '%s/account/eduid/login/callback/' % settings.HTTP_ORIGIN, "code": code, "client_id": current_app.client_id, "client_secret": current_app.secret, } headers = {'Content-Type': "application/x-www-form-urlencoded", 'Cache-Control': "no-cache" } response = requests.post("{}/token".format(settings.EDUID_PROVIDER_URL), data=urllib.parse.urlencode(payload), headers=headers) token_json = response.json() # 2. now with access token we can request userinfo headers = {"Authorization": "Bearer " + token_json['access_token'] } response = requests.get("{}/userinfo".format(settings.EDUID_PROVIDER_URL), headers=headers) if response.status_code != 200: error = 'Server error: User info endpoint error (http %s). Try alternative login methods' % response.status_code logger.debug(error) return render_authentication_error(request, EduIDProvider.id, error=error) userinfo_json = response.json() keyword_arguments = {'access_token':token_json['access_token'], 'state': json.dumps([str(badgr_app_pk), 'edu_id', lti_context_id,lti_user_id,lti_roles]+ [json.loads(referer)]), 'after_terms_agreement_url_name': 'eduid_terms_accepted_callback'} if not get_social_account(userinfo_json['sub']): return HttpResponseRedirect(reverse('accept_terms', kwargs=keyword_arguments)) social_account = get_social_account(userinfo_json['sub']) badgr_app = BadgrApp.objects.get(pk=badgr_app_pk) if not check_agreed_term_and_conditions(social_account.user, badgr_app): return HttpResponseRedirect(reverse('accept_terms_resign', kwargs=keyword_arguments)) return after_terms_agreement(request, **keyword_arguments)
def _add_social_account(request, sociallogin): if is_anonymous(request.user): # This should not happen. Simply redirect to the connections # view (which has a login required) return HttpResponseRedirect(reverse('socialaccount_connections')) level = messages.INFO message = 'socialaccount/messages/account_connected.txt' action = None if sociallogin.is_existing: if sociallogin.user != request.user: # Social account of other user. For now, this scenario # is not supported. Issue is that one cannot simply # remove the social account from the other user, as # that may render the account unusable. level = messages.ERROR message = 'socialaccount/messages/account_connected_other.txt' else: # This account is already connected -- we give the opportunity # for customized behaviour through use of a signal. If not # implemented, we render the standard "account connected" # message without actually doing anything. action = 'updated' try: signals.social_account_updated.send(sender=SocialLogin, request=request, sociallogin=sociallogin) except ImmediateHttpResponse as e: return e.response else: # New account, let's connect action = 'added' sociallogin.connect(request, request.user) try: signals.social_account_added.send(sender=SocialLogin, request=request, sociallogin=sociallogin) except ImmediateHttpResponse as e: return e.response default_next = get_adapter(request).get_connect_redirect_url( request, sociallogin.account) next_url = sociallogin.get_redirect_url(request) or default_next get_account_adapter(request).add_message(request, level, message, message_context={ 'sociallogin': sociallogin, 'action': action }) return HttpResponseRedirect(next_url)
def _add_social_account(request, sociallogin): sociallogin.connect(request, request.user) try: signals.social_account_added.send(sender=SocialLogin, request=request, sociallogin=sociallogin) except ImmediateHttpResponse as e: return e.response default_next = get_adapter() \ .get_connect_redirect_url(request, sociallogin.account) next_url = sociallogin.get_redirect_url(request) or default_next get_account_adapter().add_message( request, messages.INFO, 'socialaccount/messages/account_connected.txt') return HttpResponseRedirect(next_url)
def _add_social_account(request, sociallogin): sociallogin.connect(request, request.user) try: signals.social_account_added.send(sender=SocialLogin, request=request, sociallogin=sociallogin) except ImmediateHttpResponse as e: return e.response default_next = get_adapter() \ .get_connect_redirect_url(request, sociallogin.account) next_url = sociallogin.get_redirect_url(request) or default_next get_account_adapter().add_message(request, messages.INFO, 'socialaccount/messages/account_connected.txt') return HttpResponseRedirect(next_url)
def validate_email(self, email): email = get_account_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.")) return email
def _process_signup(request, sociallogin): # If email is specified, check for duplicate and if so, no auto signup. auto_signup = app_settings.AUTO_SIGNUP email = user_email(sociallogin.account.user) if auto_signup: # Let's check if auto_signup is really possible... if email: if account_settings.UNIQUE_EMAIL: if email_address_exists(email): # Oops, another user already has this address. We # cannot simply connect this social account to the # existing user. Reason is that the email adress may # not be verified, meaning, the user may be a hacker # that has added your email address to his account in # the hope that you fall in his trap. We cannot check # on 'email_address.verified' either, because # 'email_address' is not guaranteed to be verified. auto_signup = False # FIXME: We redirect to signup form -- user will # see email address conflict only after posting # whereas we detected it here already. elif app_settings.EMAIL_REQUIRED: # Nope, email is required and we don't have it yet... auto_signup = False if not auto_signup: request.session['socialaccount_sociallogin'] = sociallogin url = reverse('socialaccount_signup') ret = HttpResponseRedirect(url) else: # FIXME: This part contains a lot of duplication of logic # ("closed" rendering, create user, send email, in active # etc..) try: if not get_account_adapter().is_open_for_signup(request): return render(request, "account/signup_closed.html") except ImmediateHttpResponse as e: return e.response u = sociallogin.account.user if account_settings.USER_MODEL_USERNAME_FIELD: user_username( u, generate_unique_username(user_username(u) or email or 'user')) for field in ['last_name', 'first_name']: if hasattr(u, field): truncated_value = (user_field(u, field) or '') \ [0:User._meta.get_field(field).max_length] user_field(u, field, truncated_value) user_email(u, email or '') u.set_unusable_password() sociallogin.save(request) from allauth.account.models import EmailAddress email_address = EmailAddress.objects.get(user=u, email__iexact=email) if app_settings.AUTO_EMAIL_VERIFY == True: email_address.verified = True email_address.save() #send_email_confirmation(request, u) ret = complete_social_signup(request, sociallogin) return ret
def save_user(self, request, sociallogin, form=None): u = sociallogin.user u.set_unusable_password() if form: get_account_adapter().save_user(request, u, form) else: if u.twitter_screen_name: # claim account if not u.username: u.username = u.twitter_screen_name u.twitter_screen_name = None u.twitter_profile_image_url = None # u.save() else: get_account_adapter().populate_username(request, u) sociallogin.save(request) return u
def save_user(self, request, sociallogin, form=None): user = sociallogin.user data = form.cleaned_data username = data.get('username') # ソーシャルアカウントのユーザ名を自動で入れてくれる email = data.get('email') """ django-allauth/allauth/account/utils.pyのuser_fieldを使用 setattr(user, field, fieldの値)でuserのプロパティに値を入れている。 """ user_field(user, 'username', username) user_email(user, email) """ 画像が選択されていればそれをそれを登録する 選択されていなければSNSのプロフィール画像を登録する """ if request.FILES.get('profile_pic'): profile_pic_file = request.FILES.get('profile_pic') profile_pic_name = username + '_' + profile_pic_file.name user.profile_pic.save(profile_pic_name, profile_pic_file) else: # Twitter if sociallogin.account.extra_data.get('profile_image_url_https'): profile_pic_url = sociallogin.account.extra_data.get( 'profile_image_url_https', None) # Github if sociallogin.account.extra_data.get('avatar_url'): profile_pic_url = sociallogin.account.extra_data.get( 'avatar_url', None) # Twitter・Githubどちらかの画像が取得できる場合は登録する if profile_pic_url is not None: response = requests.get(profile_pic_url) profile_pic_name = username + '.jpg' user.profile_pic.save(profile_pic_name, ContentFile(response.content), save=True) user.set_unusable_password() get_account_adapter().populate_username(request, user) sociallogin.save(request) return user
def is_open_for_signup(self, request, sociallogin): """ Checks whether or not the site is open for signups. Next to simply returning True/False you can also intervene the regular flow by raising an ImmediateHttpResponse """ return get_account_adapter(request).is_open_for_signup(request)
def validate_email(self, email): email = get_account_adapter().clean_email(email) if allauth_settings.UNIQUE_EMAIL: if email and email_address_exists(email): raise serializers.ValidationError( _("A user is already registered with this e-mail address.") ) return email
def _process_signup(request, sociallogin): # If email is specified, check for duplicate and if so, no auto signup. auto_signup = app_settings.AUTO_SIGNUP email = user_email(sociallogin.account.user) if auto_signup: # Let's check if auto_signup is really possible... if email: if account_settings.UNIQUE_EMAIL: if email_address_exists(email): # Oops, another user already has this address. We # cannot simply connect this social account to the # existing user. Reason is that the email adress may # not be verified, meaning, the user may be a hacker # that has added your email address to his account in # the hope that you fall in his trap. We cannot check # on 'email_address.verified' either, because # 'email_address' is not guaranteed to be verified. auto_signup = False # FIXME: We redirect to signup form -- user will # see email address conflict only after posting # whereas we detected it here already. elif app_settings.EMAIL_REQUIRED: # Nope, email is required and we don't have it yet... auto_signup = False if not auto_signup: request.session['socialaccount_sociallogin'] = sociallogin url = reverse('socialaccount_signup') ret = HttpResponseRedirect(url) else: # FIXME: This part contains a lot of duplication of logic # ("closed" rendering, create user, send email, in active # etc..) try: if not get_account_adapter().is_open_for_signup(request): return render(request, "account/signup_closed.html") except ImmediateHttpResponse as e: return e.response u = sociallogin.account.user if account_settings.USER_MODEL_USERNAME_FIELD: user_username(u, generate_unique_username(user_username(u) or email or 'user')) for field in ['last_name', 'first_name']: if hasattr(u, field): truncated_value = (user_field(u, field) or '') \ [0:User._meta.get_field(field).max_length] user_field(u, field, truncated_value) user_email(u, email or '') if u.password: pass else: u.set_unusable_password() sociallogin.save(request) ret = complete_social_signup(request, sociallogin) return ret
def _add_social_account(request, sociallogin): if request.user.is_anonymous: # This should not happen. Simply redirect to the connections # view (which has a login required) return HttpResponseRedirect(reverse('socialaccount_connections')) level = messages.INFO message = 'socialaccount/messages/account_connected.txt' action = None if sociallogin.is_existing: if sociallogin.user != request.user: # Social account of other user. For now, this scenario # is not supported. Issue is that one cannot simply # remove the social account from the other user, as # that may render the account unusable. level = messages.ERROR message = 'socialaccount/messages/account_connected_other.txt' else: # This account is already connected -- we give the opportunity # for customized behaviour through use of a signal. If not # implemented, we render the standard "account connected" # message without actually doing anything. action = 'updated' signals.social_account_updated.send( sender=SocialLogin, request=request, sociallogin=sociallogin) else: # New account, let's connect action = 'added' sociallogin.connect(request, request.user) signals.social_account_added.send(sender=SocialLogin, request=request, sociallogin=sociallogin) default_next = get_adapter(request).get_connect_redirect_url( request, sociallogin.account) next_url = sociallogin.get_redirect_url(request) or default_next get_account_adapter(request).add_message( request, level, message, message_context={ 'sociallogin': sociallogin, 'action': action } ) return HttpResponseRedirect(next_url)
def save_user(self, request, sociallogin, form=None): """ Saves a newly signed up social login. In case of auto-signup, the signup form is not available. """ user = sociallogin.user user.set_unusable_password() if form: get_account_adapter().save_user(request, user, form) else: get_account_adapter().populate_username(request, user) sociallogin.save(request) try: picture = user.socialaccount_set.first().get_avatar_url() except ObjectDoesNotExist: picture = None ProfileOperator.create_profile(user, {'picture': picture}) return user
def get(self, request, *args, **kwargs): user_login = get_user_login_object(request) email = user_login.email request.session['is_show_request_message'] = True try: email_address = EmailAddress.objects.get( user=request.user, email=email, ) get_account_adapter().add_message(request, messages.INFO, 'account/messages/' 'email_confirmation_sent.txt', {'email': email}) email_address.send_confirmation(request) return HttpResponseRedirect("/?action=resend_confirm_email&result=success") except EmailAddress.DoesNotExist: return HttpResponseRedirect("/?action=resend_confirm_email&result=error")
def post(self, request): if request.is_ajax: account = SocialAccount.objects.get( id=request.POST.get('social_account_id')) if account.provider == 'custom_telegram': request.user.send_news_to_telegram = False account.delete() get_account_adapter().add_message( request, messages.INFO, "socialaccount/messages/" "account_disconnected.txt", ) signals.social_account_removed.send(sender=SocialAccount, request=request, socialaccount=account) return HttpResponse(status=200) return HttpResponse(status=400)
def save(self, request): with transaction.atomic(): # skip SocialAccountAdapter. This is a huge refactor of allauth: much, # much more direct. user = self.sociallogin.user user.set_unusable_password() get_account_adapter().populate_username(request, user) user.save( ) # skip default behavior of reading name, email from form self.sociallogin.save(request) # User profile user_profile = UserProfile.objects.create( user=user, locale_id=request.locale_id, get_newsletter=self.cleaned_data["get_newsletter"], ) return user
def _add_social_account(request, sociallogin): if request.user.is_anonymous: # This should not happen. Simply redirect to the connections # view (which has a login required) return HttpResponseRedirect(reverse("socialaccount_connections")) level = messages.INFO message = "socialaccount/messages/account_connected.txt" action = None if sociallogin.is_existing: if sociallogin.user != request.user: # Social account of other user. For now, this scenario # is not supported. Issue is that one cannot simply # remove the social account from the other user, as # that may render the account unusable. level = messages.ERROR message = "socialaccount/messages/account_connected_other.txt" else: # This account is already connected -- we give the opportunity # for customized behaviour through use of a signal. action = "updated" message = "socialaccount/messages/account_connected_updated.txt" signals.social_account_updated.send(sender=SocialLogin, request=request, sociallogin=sociallogin) else: # New account, let's connect action = "added" sociallogin.connect(request, request.user) signals.social_account_added.send(sender=SocialLogin, request=request, sociallogin=sociallogin) default_next = get_adapter(request).get_connect_redirect_url( request, sociallogin.account) next_url = sociallogin.get_redirect_url(request) or default_next get_account_adapter(request).add_message( request, level, message, message_context={ "sociallogin": sociallogin, "action": action }, ) return HttpResponseRedirect(next_url)
def complete_social_login(request, sociallogin): assert not sociallogin.is_existing sociallogin.lookup() try: get_adapter().pre_social_login(request, sociallogin) signals.pre_social_login.send(sender=SocialLogin, request=request, sociallogin=sociallogin) except ImmediateHttpResponse as e: return e.response if request.user.is_authenticated(): if sociallogin.is_existing: # Existing social account, existing user if sociallogin.account.user != request.user: # Social account of other user. Simply logging in may # not be correct in the case that the user was # attempting to hook up another social account to his # existing user account. For now, this scenario is not # supported. Issue is that one cannot simply remove # the social account from the other user, as that may # render the account unusable. pass ret = _login_social_account(request, sociallogin) else: # New social account sociallogin.connect(request, request.user) default_next = get_adapter() \ .get_connect_redirect_url(request, sociallogin.account) next = sociallogin.get_redirect_url(request) or default_next get_account_adapter().add_message(request, messages.INFO, 'socialaccount/messages/account_connected.txt') return HttpResponseRedirect(next) else: if sociallogin.is_existing: # Login existing user ret = _login_social_account(request, sociallogin) else: # New social user ret = _process_signup(request, sociallogin) return ret
def complete_social_login(request, sociallogin): assert not sociallogin.is_existing sociallogin.lookup() try: get_adapter().pre_social_login(request, sociallogin) signals.pre_social_login.send(sender=SocialLogin, request=request, sociallogin=sociallogin) except ImmediateHttpResponse as e: return e.response if request.user.is_authenticated(): if sociallogin.is_existing: # Existing social account, existing user if sociallogin.account.user != request.user: # Social account of other user. Simply logging in may # not be correct in the case that the user was # attempting to hook up another social account to his # existing user account. For now, this scenario is not # supported. Issue is that one cannot simply remove # the social account from the other user, as that may # render the account unusable. pass ret = _login_social_account(request, sociallogin) else: # New social account sociallogin.connect(request, request.user) default_next = get_adapter() \ .get_connect_redirect_url(request, sociallogin.account) next = sociallogin.get_redirect_url(request) or default_next get_account_adapter().add_message( request, messages.INFO, 'socialaccount/messages/account_connected.txt') return HttpResponseRedirect(next) else: if sociallogin.is_existing: # Login existing user ret = _login_social_account(request, sociallogin) else: # New social user ret = _process_signup(request, sociallogin) return ret
def save_user(self, request, sociallogin, form=None): u = sociallogin.user u.set_unusable_password() if form: get_account_adapter().save_user(request, u, form) else: get_account_adapter().populate_username(request, u) if str.isdigit(u.username[1]): if u.username[0] == "f": u.category = "FD" elif request.user.username[0] == "h": u.category = "HD" else: u.category = "PD" else: messages.error(request, "Please login using a valid Student Bitsmail") raise ImmediateHttpResponse(redirect("account-login")) u.enrollment_year = int(u.username[1:5]) sociallogin.save(request) return u
def save_user(self, request, sociallogin, form=None): user = sociallogin.user user.set_unusable_password() if form: get_account_adapter().save_user(request, user, form) else: get_account_adapter().populate_username(request, user) sociallogin.save(request) # check Facebook friends logic user_id = get_user_id(user) access_token = get_access_token(user) try: friends_data = get_connections_data(user_id, access_token, 'friends') friends_count = friends_data.get('summary').get('total_count') if friends_count >= 30: permission = Permission.objects.get(name='Can review') user.user_permissions.add(permission) except: pass return user
def post(self, *args, **kwargs): self.object = confirmation = self.get_object() confirmation.confirm(self.request) get_account_adapter().add_message(self.request, messages.SUCCESS, 'account/messages/email_confirmed.txt', {'email': confirmation.email_address.email}) resp = self.login_on_confirm(confirmation) if resp: return resp # Don't -- allauth doesn't touch is_active so that sys admin can # use it to block users et al # # user = confirmation.email_address.user # user.is_active = True # user.save() redirect_url = self.get_redirect_url() self.request.session['is_show_request_message'] = True if not redirect_url: ctx = self.get_context_data() return self.render_to_response(ctx) return redirect(redirect_url)
def validate_password(self, password): return get_account_adapter().clean_password(password)
def _process_signup(request, sociallogin): # If email is specified, check for duplicate and if so, no auto signup. auto_signup = app_settings.AUTO_SIGNUP email = user_email(sociallogin.account.user) if auto_signup: # Let's check if auto_signup is really possible... if email: if account_settings.UNIQUE_EMAIL: if email_address_exists(email): # Oops, another user already has this address. We # cannot simply connect this social account to the # existing user. Reason is that the email adress may # not be verified, meaning, the user may be a hacker # that has added your email address to his account in # the hope that you fall in his trap. We cannot check # on 'email_address.verified' either, because # 'email_address' is not guaranteed to be verified. auto_signup = False # FIXME: We redirect to signup form -- user will # see email address conflict only after posting # whereas we detected it here already. else: # Extra stuff hacked in here to integrate with # the account whitelist app. # Will be ignored if the whitelist app can't be # imported, thus making this slightly less hacky. whitelist_model_setting = getattr( settings, 'SOCIALACCOUNT_WHITELIST_MODEL', None ) if whitelist_model_setting: whitelist_model_path = whitelist_model_setting.split(r'.') whitelist_model_str = whitelist_model_path[-1] whitelist_path_str = r'.'.join(whitelist_model_path[:-1]) try: whitelist_app = __import__(whitelist_path_str, fromlist=[whitelist_path_str]) whitelist_model = getattr(whitelist_app, whitelist_model_str, None) if whitelist_model: try: guest = whitelist_model.objects.get(email=email) if not guest.active: auto_signup = False except whitelist_model.DoesNotExist: auto_signup = False except ImportError: pass elif app_settings.EMAIL_REQUIRED: # Nope, email is required and we don't have it yet... auto_signup = False if not auto_signup: url = reverse('socialaccount_login_error') ret = HttpResponseRedirect(url) else: # FIXME: This part contains a lot of duplication of logic # ("closed" rendering, create user, send email, in active # etc..) try: if not get_account_adapter().is_open_for_signup(request): return render(request, "account/signup_closed.html") except ImmediateHttpResponse as e: return e.response u = sociallogin.account.user if account_settings.USER_MODEL_USERNAME_FIELD: user_username(u, generate_unique_username(user_username(u) or email or 'user')) u.last_name = (u.last_name or '') \ [0:User._meta.get_field('last_name').max_length] u.first_name = (u.first_name or '') \ [0:User._meta.get_field('first_name').max_length] user_email(u, email or '') u.set_unusable_password() sociallogin.save(request) ret = complete_social_signup(request, sociallogin) return ret
def validate_username(self, username): return get_account_adapter().clean_username(username)
def save_user(self, request, sociallogin, form=None): socialaccount = sociallogin.account user = sociallogin.account.user user.set_unusable_password() user.save() try: birthday = socialaccount.extra_data['birthday'] month = int(birthday[0:2]) day = int(birthday[3:5]) year = int(birthday[6:]) user.get_profile().birthday = datetime.date(year,month,day) except Exception as e: logger.exception(e) gender = socialaccount.extra_data['gender'] user.get_profile().gender = GENDER_MAP_BY_NAME[gender] user.get_profile().facebook_id = socialaccount.uid # Download Facebook Profile Picture and store it try: file_name = "facebook_user_" + str(socialaccount.extra_data['id']) + "_avatar.jpg" image_request = requests.get("http://graph.facebook.com/" + socialaccount.uid + "/picture?width=1000&height=1000", stream=True) image_file = tempfile.NamedTemporaryFile() for block in image_request.iter_content(1024 * 8): if not block: break image_file.write(block) image_file.name = file_name avatar = Photo.objects.create(caption=str(user.username) + " Avatar", user_post=user,image=files.File(image_file), unique_id=generate_unique_id("photo"),photo_type='user_profile') user.get_profile().avatar = avatar except Exception as e: logger.exception(e) avatar = None if gender == "m": avatar = Photo.objects.create(caption=first_name + " " + last_name + " Avatar", \ user_post=user,image=DEFAULT_IMAGE_PATH_MAPPING['default_male_icon'], unique_id=generate_unique_id("photo"),photo_type='user_profile') else: avatar = Photo.objects.create(caption=first_name + " " + last_name + " Avatar", \ user_post=user,image=DEFAULT_IMAGE_PATH_MAPPING['default_female_icon'], unique_id=generate_unique_id("photo"),photo_type='user_profile') user.get_profile().avatar = avatar cover_picture = Photo.objects.create(caption=user.get_profile().get_user_fullname() + " Cover Picture", \ user_post=user,image=DEFAULT_IMAGE_PATH_MAPPING['default_cover_picture'], unique_id=generate_unique_id("photo"),photo_type='user_profile') user.get_profile().cover_picture = cover_picture get_location_from_client_ip(request,user) user.get_profile().save() if form: email = form.cleaned_data['email'] user.email = email user.save() else: get_account_adapter().populate_username(request, user) sociallogin.save(request) SocialFriendList.objects.get_or_create_with_social_auth(socialaccount) return user
def get_redirect_url(self): return get_account_adapter().get_email_confirmation_redirect_url(self.request)
def get_redirect_url(self): return (get_next_redirect_url(self.request, self.redirect_field_name) or get_account_adapter().get_logout_redirect_url(self.request))
def logout(self): get_account_adapter().add_message(self.request, messages.SUCCESS, 'account/messages/logged_out.txt') auth_logout(self.request)