def populate_user(self, request, sociallogin, data): """ Hook that can be used to further populate the user instance. For convenience, we populate several common fields. Note that the user instance being populated represents a suggested User instance that represents the social user that is in the process of being logged in. The User instance need not be completely valid and conflict free. For example, verifying whether or not the username already exists, is not a responsibility. """ username = data.get('username') first_name = data.get('first_name') last_name = data.get('last_name') email = username time_zone = data.get('time_zone') locale = data.get('locale') gravatar = data.get('profile_image_url') user = sociallogin.user user_username(user, username or '') user_email(user, valid_email_or_none(email) or '') user_field(user, 'given_name', first_name or '') user.is_active = True user.is_researcher = True user_field(user, 'family_name', last_name or '') user_field(user, 'time_zone', time_zone) user_field(user, 'locale', locale) user_field(user, '_identicon', self.get_base64_gravatar(gravatar)) return user
def populate_user(self, request, sociallogin, data): """ Hook that can be used to further populate the user instance. For convenience, we populate several common fields. Note that the user instance being populated represents a suggested User instance that represents the social user that is in the process of being logged in. The User instance need not be completely valid and conflict free. For example, verifying whether or not the username already exists, is not a responsibility. """ username = data.get('username') first_name = data.get('first_name') last_name = data.get('last_name') email = data.get('email') name = data.get('name') time_zone = data.get('time_zone') locale = data.get('locale') gravatar = data.get('profile_image_url') user = sociallogin.user user_username(user, username or '') user_email(user, valid_email_or_none(email) or '') name_parts = (name or '').partition(' ') user_field(user, 'first_name', first_name or name_parts[0]) user_field(user, 'last_name', last_name or name_parts[2]) user_field(user, 'time_zone', time_zone) user_field(user, 'locale', locale) user_field(user, 'gravatar', gravatar) return user
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 save_user(self, request, user, form): data = form.cleaned_data email = data['email'] first_name = data["first_name"] last_name = data["last_name"] username = generate_unique_username([first_name,last_name,email,'user']) user_email(user, email) user_username(user, username) user_field(user, 'first_name', first_name or '') user_field(user, 'last_name', last_name or '') password = data.get("password1") if password: user.set_password(password) else: user.set_unusable_password() user.save() 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') cover_picture = Photo.objects.create(caption=first_name + " " + last_name + " Cover Picture", \ user_post=user,image=DEFAULT_IMAGE_PATH_MAPPING['default_cover_picture'], unique_id=generate_unique_id("photo"),photo_type='user_profile') get_location_from_client_ip(request,user) user.get_profile().avatar = avatar user.get_profile().cover_picture = cover_picture user.get_profile().save() return user
def save_user(self, request, user, form, commit=True): from allauth.account.utils import user_email, user_field, user_username data = form.cleaned_data first_name = data.get("first_name") last_name = data.get("last_name") email = data.get("email") username = data.get("username") nickname = form.data.get("nickname") user_email(user, email) user_username(user, username) user_field(user, 'nickname', nickname) if first_name: user_field(user, "first_name", first_name) if last_name: user_field(user, "last_name", last_name) if "password1" in data: user.set_password(data["password1"]) else: user.set_unusable_password() self.populate_username(request, user) if commit: # Ability not to commit makes it easier to derive from # this adapter by adding user.save() return user
def save_user(self, request, user, form, commit=True): data = form.cleaned_data unregistered_user = data.get('unregistered_user') first_name = data.get('first_name') last_name = data.get('last_name') email = data.get('email') username = email password = data['password'] is_staff = unregistered_user.is_staff user_field(user, 'first_name', first_name) user_field(user, 'last_name', last_name) user_email(user, email) user_username(user, username) user.set_password(password) user.is_staff = is_staff self.populate_username(request, user) if commit: user.save() Profile.objects.create(user=user) if is_staff: Teacher.objects.create(user=user) else: Student.objects.create(user=user, group=unregistered_user.group) unregistered_user.delete() return user
def populate_user(self, request, sociallogin, data): user = sociallogin.user username = data.get('username') first_name = data.get('first_name') last_name = data.get('last_name') if sociallogin.account.provider == 'twitter': email = '{}@twitter.com'.format(username) else: email = data.get('email') birthday = sociallogin.account.extra_data.get('birthday') if birthday: user_field( user, 'data_de_nascimento', '{}'.format( datetime.strptime(birthday, '%m/%d/%Y').strftime('%Y-%m-%d'))) name = data.get('name') user_username(user, username or '') user_email(user, valid_email_or_none(email) or '') name_parts = (name or '').partition(' ') first_name = first_name or name_parts[0] last_name = last_name or name_parts[2] user_field(user, 'nome', u'{} {}'.decode('utf-8').format(first_name, last_name)) if not user.data_ativacao_email: user.data_ativacao_email = timezone.now() return user
def populate_user(self, request, sociallogin, data): """ Hook that can be used to further populate the user instance. For convenience, we populate several common fields. Note that the user instance being populated represents a suggested User instance that represents the social user that is in the process of being logged in. The User instance need not be completely valid and conflict free. For example, verifying whether or not the username already exists, is not a responsibility. """ first_name = data.get('first_name') last_name = data.get('last_name') email = data.get('email') name = data.get('name') user = sociallogin.user name_parts = (name or '').partition(' ') user_field(user, 'first_name', first_name or name_parts[0]) user_field(user, 'last_name', last_name or name_parts[2]) username = utils.generateRandomUsername(first_name or name_parts[0] or '') user_email(user, valid_email_or_none(email) or (username + '@redzza.com')) user_username(user, username) return user
def clean(self): super(SignupForm, self).clean() # `password` cannot be of type `SetPasswordField`, as we don't # have a `User` yet. So, let's populate a dummy user to be used # for password validaton. dummy_user = get_user_model() user_username(dummy_user, self.cleaned_data.get("username")) user_email(dummy_user, self.cleaned_data.get("email")) password = self.cleaned_data.get('password1') if password: try: get_adapter().clean_password( password, user=dummy_user) except forms.ValidationError as e: self.add_error('password1', e) if app_settings.SIGNUP_PASSWORD_ENTER_TWICE \ and "password1" in self.cleaned_data \ and "password2" in self.cleaned_data: if self.cleaned_data["password1"] \ != self.cleaned_data["password2"]: self.add_error( 'password2', _("You must type the same password each time.")) return self.cleaned_data
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 save_user(self, request, user, form, commit=True): """ Saves a new `User` instance using information provided in the signup form. """ from allauth.account.utils import user_username, user_email, user_field data = form.cleaned_data first_name = data.get('first_name') last_name = data.get('last_name') email = data.get('email') username = data.get('username') user_email(user, email) user_username(user, username) if first_name: user_field(user, 'first_name', first_name) if last_name: user_field(user, 'last_name', last_name) if 'password1' in data: user.set_password(data["password1"]) else: user.set_unusable_password() self.populate_username(request, user) user.is_active = False if commit: # Ability not to commit makes it easier to derive from # this adapter by adding user.save() return user
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): 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, user, form, commit=True): data = form.cleaned_data first_name = data.get('first_name') last_name = data.get('last_name') email = data.get('email') username = data.get('username').lower() user_email(user, email) user_username(user, username) if first_name: user_field(user, 'first_name', first_name) if last_name: user_field(user, 'last_name', last_name) if 'password1' in data: user.set_password(data["password1"]) else: user.set_unusable_password() self.populate_username(request, user) user.id_group_id = data.get("id_group") user.document = data.get("document") user.type_document = data.get('type_document') user.phone_home = data.get('phone_home') user.phone_mobile = data.get('phone_mobile') user.city = data.get('city') user.phone_office = data.get('phone_office') if commit: user.save() return user
def populate_user(self, request, sociallogin, data): username = data.get('username') email = data.get('email') user = sociallogin.user user_username(user, username or '') user_email(user, valid_email_or_none(email) or '') date_of_birth = data.get('birthdate') if date_of_birth: try: parsed = datetime.strptime(date_of_birth, "%Y-%m-%d") user.date_of_birth = parsed except ValueError: pass name = data.get('name') first_name = data.get('first_name') last_name = data.get('last_name') # if a full name exists, use that, if not, # join first_name and last_name if name: user_field(user, 'full_name', name) else: merged = ' '.join(x for x in [first_name, last_name] if x) if merged != '': user_field(user, 'full_name', merged) return user
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 _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 populate_user(self, request, sociallogin, data): user = super(SocialAccountAdapter, self).populate_user(request, sociallogin, data) first_name = data.get('first_name') last_name = data.get('last_name') user_username(user, last_name+first_name) return user
def populate_user(self, request, sociallogin, data): """Populate new UWUM user with unique display name and fake email.""" user = super(UWUMSocialAccountAdapter, self).populate_user(request, sociallogin, data) username = data.get('username') user_username(user, generate_display_name(username)) user_email(user, generate_fake_email(username)) return user
def populate_username(self, request, user): """ overrides the base populate_username to not make use of first_name and last_name """ full_name = user_field(user, 'full_name') email = user_email(user) username = user_username(user) user_username( user, username or self.generate_unique_username( [full_name, email, username, 'user']))
class UnescoLocalAccountAdapter(LocalAccountAdapter): """Customizations for local accounts Check `django-allauth's documentation`_ for more details on this class. .. _django-allauth's documentation: http://django-allauth.readthedocs.io/en/latest/advanced.html#creating-and-populating-user-instances """ def populate_username(self, request, user): # validate the already generated username with django validation # if it passes use that, otherwise use django-allauth's way of # generating a unique username # safe_username = user_username(user) try: safe_username = populate_username(user_field(user, 'first_name'), user_field(user, 'last_name')) except Exception, e: traceback.print_exc() raise forms.ValidationError(e) # safe_username = self.generate_unique_username([ # user_field(user, 'first_name'), # user_field(user, 'last_name'), # user_email(user), # user_username(user) # ]) User = get_user_model() lookup_kwargs = get_user_lookup_kwargs( {"{username}__iexact": safe_username}) qs = User.objects.filter(**lookup_kwargs) _user_name_is_valid = False if not qs.exists(): user.username = safe_username user.full_clean() user_username(user, safe_username) _user_name_is_valid = True else: lookup_kwargs = get_user_lookup_kwargs( {"{username}__startswith": safe_username}) qs = User.objects.filter(**lookup_kwargs) safe_username += '_{}'.format((qs.count())) try: User.objects.get(username__iexact=safe_username) except User.DoesNotExist: user.username = safe_username user.full_clean() user_username(user, safe_username) _user_name_is_valid = True if not _user_name_is_valid: raise forms.ValidationError(_("This username already exists."))
def save_user(self, user, first_name, last_name, email, username): user_email(user, email) user_username(user, username) user_field(user, 'first_name', first_name or '') user_field(user, 'last_name', last_name or '') password = username while len(password) < 6: password = password + '1' user.set_password(username) user.save() return user
def populate_username(self, request, user): """ Fills in a valid username, if required and missing. If the username is already present it is assumed to be valid (unique). """ first_name = user_field(user, "first_name") last_name = user_field(user, "last_name") email = user_email(user) username = user_username(user) if USER_MODEL_USERNAME_FIELD: user_username(user, username or generate_unique_username([first_name, last_name, email, "user"]))
def populate_username(self, request, user): """ Takes a partial user, and sets the username if missing based on existing fields. """ first_name = utils.user_field(user, "first_name") last_name = utils.user_field(user, "last_name") email = utils.user_email(user) username = utils.user_username(user) if app_settings.USER_MODEL_USERNAME_FIELD: username = username or self.generate_unique_username( [email, first_name, last_name, "user"]) utils.user_username(user, username)
def setUp(self): adapt = get_adapter() #create a test user usr = adapt.new_user(None) usr.set_password('test') usr.is_active = 'True' user_email(usr, '*****@*****.**') user_username(usr, 'test') usr.save() # manually confirm address email = EmailAddress.objects.create(user=usr,email='*****@*****.**') adapt.confirm_email(None,email)
def populate_username(self, request, user): """ Fills in a valid username, if missing. If the username is already present it is assumed to be valid. In astrosat, we simply use the email address as the username. """ email = user_email(user) username = user_username(user) if allauth_app_settings.USER_MODEL_USERNAME_FIELD: # the original code does some fancy logic to generate a unique username # this code just uses either the value explicitly passed by the fronted # or defaults to the email address user_username(user, username or email)
def populate_user(self, request, sociallogin, data): """ When populating a :class:`~django.contrib.auth.models.User` object during login, we make sure the username is the user part of the user's email address, e.g. ``[email protected]`` will mean the username is ``jdoe``. """ user = super().populate_user(request, sociallogin, data) email = user_email(user) if email and '@' in email: username = email.split('@')[0] user_username(user, username) return user
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 populate_username(self, request, user): """ Fills in a valid username, if required and missing. If the username is already present it is assumed to be valid (unique). """ first_name = user_field(user, 'first_name') last_name = user_field(user, 'last_name') email = user_email(user) username = user_username(user) if USER_MODEL_USERNAME_FIELD: user_username( user, username or generate_unique_username( [first_name, last_name, email, 'user']))
def populate_username(self, request, user): # validate the already generated username with django validation # if it passes use that, otherwise use django-allauth's way of # generating a unique username try: user.full_clean() safe_username = user_username(user) except ValidationError: safe_username = self.generate_unique_username([ user_field(user, 'first_name'), user_field(user, 'last_name'), user_email(user), user_username(user) ]) user_username(user, safe_username)
def populate_username(self, request, user): """ Takes a partial user, and sets the username if missing based on existing fields. """ from allauth.account.utils import user_username, user_email, user_field first_name = user_field(user, 'first_name') last_name = user_field(user, 'last_name') email = user_email(user) username = user_username(user) if allauth_settings.USER_MODEL_USERNAME_FIELD: username = username or self.generate_unique_username([ email, first_name, last_name, 'user', ]) user_username(user, username)
def populate_username(self, request, user): """ Fills in a valid username, if required and missing. If the username is already present it is assumed to be valid (unique). """ from allauth.account.utils import user_username, user_email, user_field first_name = user_field(user, 'first_name') last_name = user_field(user, 'last_name') email = user_email(user) username = user_username(user) if app_settings.USER_MODEL_USERNAME_FIELD: user_username( user, username or self.generate_unique_username( [first_name, last_name, email, username, 'user']))
def revert_usernames(apps, schema_editor): User = apps.get_model('auth', 'User') for user in User.objects.exclude(username='******'): old_username = user.username user_username( user, generate_unique_username([ user_field(user, 'first_name'), user_field(user, 'last_name'), user_email(user), user_username(user), ])) if user_username(user) != old_username: user.save()
def save(self, request, **kwargs): if 'allauth' not in settings.INSTALLED_APPS: return super().save(request, **kwargs) # for allauth current_site = get_current_site(request) email = self.cleaned_data['email'] token_generator = kwargs.get('token_generator', default_token_generator) for user in self.users: temp_key = token_generator.make_token(user) # save it to the password reset model # password_reset = PasswordReset(user=user, temp_key=temp_key) # password_reset.save() # send the password reset email path = reverse( 'password_reset_confirm', args=[user_pk_to_url_str(user), temp_key], ) url = build_absolute_uri(request, path) context = { 'current_site': current_site, 'user': user, 'password_reset_url': url, 'request': request, } if app_settings.AUTHENTICATION_METHOD != app_settings.AuthenticationMethod.EMAIL: context['username'] = user_username(user) get_adapter(request).send_mail('account/email/password_reset_key', email, context) return self.cleaned_data['email']
def save(self, request, **kwargs): current_site = get_current_site(request) email = self.validated_data['email'] token_generator = kwargs.get("token_generator", default_token_generator) for user in self.users: temp_key = token_generator.make_token(user) path = reverse("account_reset_password_from_key", kwargs=dict(uidb36=user_pk_to_url_str(user), key=temp_key)) url = build_absolute_uri( request, path) context = {"current_site": current_site, "user": user, "password_reset_url": url, "request": request} if app_settings.AUTHENTICATION_METHOD \ != AuthenticationMethod.EMAIL: context['username'] = user_username(user) get_adapter(request).send_mail( 'account/email/password_reset_key', email, context)
def revert_usernames(apps, schema_editor): User = apps.get_model('auth', 'User') for user in User.objects.exclude(username='******'): old_username = user.username user_username( user, generate_unique_username([ user_field(user, 'first_name'), user_field(user, 'last_name'), user_email(user), user_username(user), ]) ) if user_username(user) != old_username: user.save()
def save(self, request, **kwargs): email = self.cleaned_data["email"] last_name = self.data.get('last_name') token_generator = kwargs.get("token_generator", default_token_generator) for user in self.users: temp_key = token_generator.make_token(user) # save it to the password reset model # password_reset = PasswordReset(user=user, temp_key=temp_key) # password_reset.save() # send the password reset email path = reverse("account_reset_password_from_key", kwargs=dict(uidb36=user_pk_to_url_str(user), key=temp_key)) url = build_absolute_uri(request, path) context = { "last_name": last_name, "password_reset_url": url, } if app_settings.AUTHENTICATION_METHOD \ != 'email': context['username'] = user_username(user) get_adapter(request).send_mail('account/email/password_reset_key', email, context) return self.cleaned_data["email"]
def save(self, request, **kwargs): email = self.cleaned_data["email"] token_generator = kwargs.get("token_generator", default_token_generator) for user in self.users: temp_key = token_generator.make_token(user) # save it to the password reset model # password_reset = PasswordReset(user=user, temp_key=temp_key) # password_reset.save() current_site = get_current_site(request) # send the password reset email path = reverse("account_reset_password_from_key", kwargs=dict(uidb36=user_pk_to_url_str(user), key=temp_key)) url = build_absolute_uri( request, path, protocol=app_settings.DEFAULT_HTTP_PROTOCOL) context = {"site": current_site, "user": user, "password_reset_url": url, "request": request} if app_settings.AUTHENTICATION_METHOD \ != AuthenticationMethod.EMAIL: context['username'] = user_username(user) get_adapter().send_mail('account/email/password_reset_key', email, context) return self.cleaned_data["email"]
def fix_usernames(apps, schema_editor): User = apps.get_model('auth', 'User') for user in User.objects.exclude(username='******'): if user.email and '@' in user.email: email_username = user.email.split('@')[0] old_username = user.username user_username( user, generate_unique_username([ email_username, user_field(user, 'first_name'), user_field(user, 'last_name'), user_email(user), user_username(user), ]) ) if user_username(user) != old_username: user.save()
def __init__(self, *args, **kwargs): self.sociallogin = kwargs.pop('sociallogin') user = self.sociallogin.account.user initial = { 'email': user_email(user) or '', 'username': user_username(user) or '', 'first_name': user.first_name or '', 'last_name': user.last_name or '' } kwargs['initial'] = initial super(SignupForm, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): self.sociallogin = kwargs.pop('sociallogin') user = self.sociallogin.account.user initial = { 'email': user_email(user) or '', 'username': user_username(user) or '', 'first_name': user.first_name or '', 'last_name': user.last_name or '' } kwargs['initial'] = initial kwargs['email_required'] = app_settings.EMAIL_REQUIRED super(SignupForm, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): self.sociallogin = kwargs.pop("sociallogin") user = self.sociallogin.account.user initial = { "email": user_email(user) or "", "username": user_username(user) or "", "first_name": user.first_name or "", "last_name": user.last_name or "", } kwargs["initial"] = initial super(SignupForm, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): self.sociallogin = kwargs.pop('sociallogin') user = self.sociallogin.account.user # TODO: Should become more generic, not listing # a few fixed properties. initial = {'email': user_email(user) or '', 'username': user_username(user) or '', 'first_name': user_field(user, 'first_name') or '', 'last_name': user_field(user, 'last_name') or ''} kwargs['initial'] = initial kwargs['email_required'] = app_settings.EMAIL_REQUIRED super(SignupForm, self).__init__(*args, **kwargs)
def __init__(self, *args, **kwargs): self.sociallogin = kwargs.pop("sociallogin") user = self.sociallogin.account.user initial = { "email": user_email(user) or "", "username": user_username(user) or "", "first_name": user_field(user, "first_name") or "", "last_name": user_field(user, "last_name") or "", } kwargs["initial"] = initial kwargs["email_required"] = app_settings.EMAIL_REQUIRED super(SignupForm, self).__init__(*args, **kwargs)
def populate_user(self,request,sociallogin,data): socialaccount = sociallogin.account username = data.get('username') first_name = data.get('first_name') last_name = data.get('last_name') email = data.get('email') name = data.get('name') user = sociallogin.account.user user_model = get_user_model() try: query = {"username" + '__iexact': username} user_model.objects.get(**query) user_username(user,generate_unique_username([first_name,last_name,email,'user'])) except Exception as e: if username == None: user_username(user,generate_unique_username([first_name,last_name,email,'user'])) else: user_username(user,username.replace(".","")) user_email(user, valid_email_or_none(email) or '') name_parts = (name or '').partition(' ') user_field(user, 'first_name', first_name or name_parts[0]) user_field(user, 'last_name', last_name or name_parts[2]) return user
def client_force_login(self, user): if django.VERSION >= (1, 9): self.client.force_login( user, 'django.contrib.auth.backends.ModelBackend') else: old_password = user.password user.set_password('doe') user.save() self.client.login( username=user_username(user), password='******') user.password = old_password user.save()
def save_user(self, request, user, form, commit=False): """ Saves a new `User` instance using information provided in the signup form. """ # user_field(user, 'date_of_birth', date_of_birth) # when field date_of_birth (datetime.date(1975, 11, 11),) # is evaluated by user_field, utils.py:80 # v = v[0:User._meta.get_field(field).max_length] # (or even just v[0] is evaluated on it's own) # {TypeError}'datetime.date' object has no attribute '__getitem__' # is thrown from allauth.account.utils import user_username, user_email, user_field data = form.cleaned_data first_name = data.get('first_name') last_name = data.get('last_name') email = data.get('email') username = data.get('username') date_of_birth = data.get('date_of_birth') gender = data.get('gender') user_email(user, email) user_username(user, username) user_field(user, 'first_name', first_name or '') user_field(user, 'last_name', last_name or '') user_field(user, 'gender', gender or '') user_field(user, 'date_of_birth', date_of_birth) if 'password1' in data: user.set_password(user, data["password1"]) else: user.set_unusable_password() self.populate_username(request, user) if commit: # Ability not to commit makes it easier to derive from # this adapter by adding user.save() print user return user
def populate_user(self, request, sociallogin, data): first_name = data.get('first_name') last_name = data.get('last_name') email = data.get('email') name = data.get('name') username = data.get('username') user = sociallogin.account.user print(sociallogin.account.provider) # TODO: Consider using the super class for the stuff that is not unique to facebook! if sociallogin.account.provider == 'facebook': user_email(user, valid_email_or_none(email) or '') name_parts = (name or '').partition(' ') user_field(user, 'first_name', first_name or name_parts[0]) user_field(user, 'last_name', last_name or name_parts[2]) # Save a good username if username: username_suggestions = [username, first_name, last_name, email, 'user'] else: username_suggestions = [first_name, last_name, email, 'user'] user_username(user, generate_unique_username(username_suggestions)) return user elif sociallogin.account.provider == 'twitter': if "screen_name" in sociallogin.account.extra_data.keys(): username = sociallogin.account.extra_data['screen_name'] user_email(user, valid_email_or_none(email) or '') name_parts = (name or '').partition(' ') user_field(user, 'first_name', first_name or name_parts[0]) user_field(user, 'last_name', last_name or name_parts[2]) # Save a good username if username: username_suggestions = [username, first_name, last_name, email, 'user'] else: username_suggestions = [first_name, last_name, email, 'user'] user_username(user, generate_unique_username(username_suggestions)) return user elif sociallogin.account.provider == 'google': #if "screen_name" in sociallogin.account.extra_data.keys(): # username = sociallogin.account.extra_data['screen_name'] user_email(user, valid_email_or_none(email) or '') name_parts = (name or '').partition(' ') user_field(user, 'first_name', first_name or name_parts[0]) user_field(user, 'last_name', last_name or name_parts[2]) print("sociallogin.account.extra_data:", str(sociallogin.account.extra_data).encode('utf-8')) if username: username_suggestions = [username, first_name, last_name, email, 'user'] else: username_suggestions = [first_name, last_name, email, 'user'] user_username(user, generate_unique_username(username_suggestions)) return user else: return super(SocialAccountAdapter, self).populate_user(request, sociallogin, data)
def populate_user(self, request, sociallogin, data): first_name = data.get("first_name") last_name = data.get("last_name") email = data.get("email") name = data.get("name") username = data.get("username") user = sociallogin.account.user # TODO: Consider using the super class for the stuff that is not unique to facebook! if sociallogin.account.provider == "facebook": user_email(user, valid_email_or_none(email) or "") name_parts = (name or "").partition(" ") user_field(user, "first_name", first_name or name_parts[0]) user_field(user, "last_name", last_name or name_parts[2]) # Save a good username if username: username_suggestions = [username, first_name, last_name, email, "user"] else: username_suggestions = [first_name, last_name, email, "user"] user_username(user, generate_unique_username(username_suggestions)) return user elif sociallogin.account.provider == "twitter": if "screen_name" in sociallogin.account.extra_data.keys(): username = sociallogin.account.extra_data["screen_name"] user_email(user, valid_email_or_none(email) or "") name_parts = (name or "").partition(" ") user_field(user, "first_name", first_name or name_parts[0]) user_field(user, "last_name", last_name or name_parts[2]) # Save a good username if username: username_suggestions = [username, first_name, last_name, email, "user"] else: username_suggestions = [first_name, last_name, email, "user"] user_username(user, generate_unique_username(username_suggestions)) return user elif sociallogin.account.provider == "google": # if "screen_name" in sociallogin.account.extra_data.keys(): # username = sociallogin.account.extra_data['screen_name'] user_email(user, valid_email_or_none(email) or "") name_parts = (name or "").partition(" ") user_field(user, "first_name", first_name or name_parts[0]) user_field(user, "last_name", last_name or name_parts[2]) if username: username_suggestions = [username, first_name, last_name, email, "user"] else: username_suggestions = [first_name, last_name, email, "user"] user_username(user, generate_unique_username(username_suggestions)) return user else: return super(SocialAccountAdapter, self).populate_user(request, sociallogin, data)
def user_info(request): headers = extract_headers(request) user = request.user if not user: out = {'success': False, 'status': 'error', 'errors': {'user': ['User is not authenticated']} } return json_response(out, status=401) if 'Authorization' not in headers and 'Bearer' not in headers["Authorization"]: out = {'success': False, 'status': 'error', 'errors': {'auth': ['No token provided.']} } return json_response(out, status=403) groups = [group.name for group in user.groups.all()] if user.is_superuser: groups.append("admin") user_info = json.dumps({ "sub": str(user.id), "name": " ".join([user_field(user, 'first_name'), user_field(user, 'last_name')]), "given_name": user_field(user, 'first_name'), "family_name": user_field(user, 'last_name'), "email": user_email(user), "preferred_username": user_username(user), "groups": groups }) response = HttpResponse( user_info, content_type="application/json" ) response['Cache-Control'] = 'no-store' response['Pragma'] = 'no-cache' return response
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