Example #1
0
	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
Example #2
0
    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
Example #3
0
 def signup(self, request, user):
     assert EmailAddress.objects.filter(user=user).count() == 0
     priority_addresses = []
     adapter = get_adapter()
     stashed_email = adapter.unstash_verified_email(request)
     if stashed_email:
         priority_addresses.append(EmailAddress(user=user,
                                                email=stashed_email,
                                                primary=True,
                                                verified=True))
     email = user_email(user)
     if email:
         priority_addresses.append(EmailAddress(user=user,
                                                email=email,
                                                primary=True,
                                                verified=False))
     addresses, primary = cleanup_email_addresses(request,
                                                  priority_addresses
                                                  + addresses)
     for a in addresses:
         a.user = user
         a.save()
     EmailAddress.objects.fill_cache_for_user(user, addresses)
     if (primary
             and email
             and email.lower() != primary.email.lower()):
         user_email(user, primary.email)
         user.save()
     return primary
Example #4
0
	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
Example #5
0
    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 設定欄位內容(self, 資料內容={}):
		"讓allauth的接口使用"
		email = valid_email_or_none(資料內容.get('email')) or ''
		if email:
			user_email(self, email)
		
		try:
			self.來源
		except:
			name = 資料內容.get('name')
			username = 資料內容.get('username')
			last_name = 資料內容.get('last_name')
			first_name = 資料內容.get('first_name')
			if name:
				來源名 = name
			elif username:
				來源名 = username
			elif last_name and first_name:
				來源名 = last_name + first_name
			else:
				來源名 = email
			self.來源 = 來源表. 加來源({ '名':來源名})

		if 'password1' in 資料內容:
			self.set_password(資料內容["password1"])
		else:
			self.set_unusable_password()
		return
Example #7
0
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
Example #8
0
    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)
Example #9
0
def send_email_confirmation_for_celery(request, user, signup=False, **kwargs):
    """
    Customized send confirmation function that doesn't set (notification) messages and other
    things that depend on the request object since we're passing a mock request object to it.
    """
    from .models import SmallsEmailAddress, SmallsEmailConfirmation

    COOLDOWN_PERIOD = timedelta(minutes=3)
    email = user_email(user)
    if email:
        try:
            email_address = SmallsEmailAddress.objects.get(user=user, email__iexact=email)
            if not email_address.verified:
                send_email = not SmallsEmailConfirmation.objects \
                    .filter(sent__gt=now() - COOLDOWN_PERIOD,
                            email_address=email_address) \
                    .exists()
                if send_email:
                    email_address.send_confirmation(request,
                                                    signup=signup, activate_view=kwargs.get('activate_view'))
            else:
                send_email = False
        except SmallsEmailAddress.DoesNotExist:
            send_email = True
            email_address = SmallsEmailAddress.objects.add_email(request,
                                                           user,
                                                           email,
                                                           signup=signup,
                                                           confirm=True)
            assert email_address
Example #10
0
 def complete_login(self, request, app, token, **kwargs):
     resp = requests.get(self.profile_url,
                         params={ 'access_token': token.token,
                                  'alt': 'json' })
     extra_data = resp.json()
     # extra_data is something of the form:
     #
     # {u'family_name': u'Penners', u'name': u'Raymond Penners',
     #  u'picture': u'https://lh5.googleusercontent.com/-GOFYGBVOdBQ/AAAAAAAAAAI/AAAAAAAAAGM/WzRfPkv4xbo/photo.jpg',
     #  u'locale': u'nl', u'gender': u'male',
     #  u'email': u'*****@*****.**',
     #  u'link': u'https://plus.google.com/108204268033311374519',
     #  u'given_name': u'Raymond', u'id': u'108204268033311374519',
     #  u'verified_email': True}
     #
     # TODO: We could use verified_email to bypass allauth email verification
     uid = str(extra_data['id'])
     account = SocialAccount(extra_data=extra_data,
                             uid=uid,
                             provider=self.provider_id)
     user = get_adapter() \
         .populate_new_user(request,
                            account,
                            email=extra_data.get('email'),
                            last_name=extra_data.get('family_name'),
                            first_name=extra_data.get('given_name'))
     account.user = user
     email_addresses = []
     email = user_email(user)
     if email and extra_data.get('verified_email'):
         email_addresses.append(EmailAddress(email=email,
                                             verified=True,
                                             primary=True))
     return SocialLogin(account,
                        email_addresses=email_addresses)
Example #11
0
 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)
Example #12
0
 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 pre_social_login(self, request, sociallogin):
     # This isn't tested, but should work
     try:
             email = user_email(sociallogin.account.user)
             user = CustomUser.objects.get(email=email)
             if user and not sociallogin.is_existing:
                 sociallogin.connect(request, user)
                 return user
     except CustomUser.DoesNotExist:
         pass
Example #14
0
File: forms.py Project: brob/trucks
 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)
Example #15
0
 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)
Example #16
0
 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)
Example #17
0
 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
     """
     email = user_email(sociallogin.user)
     try:
         queryset = UserEmail.objects.select_related().get(email=email)
         return True
     except:
         return False
Example #18
0
 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_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
Example #20
0
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 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
Example #22
0
 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)
Example #23
0
    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_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 "password1" in self.cleaned_data \
                and "password2" in self.cleaned_data:
            if self.cleaned_data["password1"] \
                    != self.cleaned_data["password2"]:
                self.add_error(
                    'password2',
                    _("The password and confirm password fields do not match.")
                )
        return self.cleaned_data
Example #24
0
def resend_verification(request):
    '''Resend the verification email, if no verified email exists.
    '''
    # success = send_email_confirmation(request, request.user)
    email = user_email(request.user)
    if email:
        email_address = EmailAddress.objects.get_for_user(request.user, email)
        if not email_address.verified:
            confirmation = email_address.send_confirmation(request,
                                                           signup=False)
            success = confirmation != None
        else:
            success = False
    else:
        success = False
    return JsonResponse({'success': success})
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()
Example #26
0
def send_email_confirmation(request, user, signup=False, **kwargs):
    """
    E-mail verification mails are sent:
    a) Explicitly: when a user signs up
    b) Implicitly: when a user attempts to log in using an unverified
    e-mail while EMAIL_VERIFICATION is mandatory.

    Especially in case of b), we want to limit the number of mails
    sent (consider a user retrying a few times), which is why there is
    a cooldown period before sending a new mail.
    """
    from .models import SmallsEmailAddress, SmallsEmailConfirmation

    COOLDOWN_PERIOD = timedelta(minutes=3)
    email = user_email(user)
    if email:
        try:
            email_address = SmallsEmailAddress.objects.get(user=user,
                                                           email__iexact=email)
            if not email_address.verified:
                send_email = not SmallsEmailConfirmation.objects \
                    .filter(sent__gt=now() - COOLDOWN_PERIOD,
                            email_address=email_address) \
                    .exists()
                if send_email:
                    email_address.send_confirmation(
                        request,
                        signup=signup,
                        activate_view=kwargs.get('activate_view'))
            else:
                send_email = False
        except SmallsEmailAddress.DoesNotExist:
            send_email = True
            email_address = SmallsEmailAddress.objects.add_email(request,
                                                                 user,
                                                                 email,
                                                                 signup=signup,
                                                                 confirm=True)
            assert email_address
        # At this point, if we were supposed to send an email we have sent it.
        if send_email:
            get_adapter().add_message(
                request, messages.INFO, 'account/messages/'
                'email_confirmation_sent.txt', {'email': email})
    if signup:
        request.session['account_user'] = user.pk
Example #27
0
    def unprimary_extra_primary_emails(self, user):
        primary_email_addresses = EmailAddress.objects.filter(user=user,
                                                              primary=True)

        for primary_email_address in primary_email_addresses:
            if primary_email_address.email == user_email(user):
                break
        else:
            # Didn't find the main email addresses and break the for loop
            print("WARNING: Multiple primary without a user.email match for"
                  "user pk %s; (tried: %s, using: %s)") % (user.pk, ", ".join([
                      email_address.email
                      for email_address in primary_email_addresses
                  ]), primary_email_address)

        primary_email_addresses.exclude(pk=primary_email_address.pk).update(
            primary=False)
Example #28
0
    def get_signup_form_initial_data(self, sociallogin):
        user = sociallogin.user

        initial = {
            'email':
            user_email(user) or '',
            'uni_id':
            sociallogin.account.extra_data.get('user').get('username') or '',
            'nickname':
            sociallogin.account.extra_data.get('nickname') or '',
            'first_name':
            user_field(user, 'first_name') or '',
            'last_name':
            user_field(user, 'last_name') or ''
        }

        return initial
Example #29
0
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()
Example #30
0
def resend_verification(request):
    '''Resend the verification email, if no verified email exists.
    '''
    # success = send_email_confirmation(request, request.user)
    email = user_email(request.user)
    if email:
        email_address = EmailAddress.objects.get_for_user(request.user, email)
        if not email_address.verified:
            confirmation = email_address.send_confirmation(request, signup=False)
            success = confirmation != None
        else:
            success = False
    else:
        success = False
    return JsonResponse({
        'success': success
    })
Example #31
0
 def is_auto_signup_allowed(self, request, sociallogin):
     # If email is specified, check for duplicate and if so, no auto signup.
     auto_signup = app_settings.AUTO_SIGNUP
     if auto_signup:
         email = user_email(sociallogin.user)
         # Let's check if auto_signup is really possible...
         if email:
             if settings.ACCOUNT_UNIQUE_EMAIL:
                 # Change: in Badge always check for email
                 if email_address_exists(email):
                     # Oops, another user already has this address.
                     # Otherwise False, because we cannot trust which provider properly verified the emails.
                     auto_signup = False
         elif app_settings.EMAIL_REQUIRED:
             # Nope, email is required and we don't have it yet...
             auto_signup = False
     return auto_signup
Example #32
0
def send_email_confirmation(request, user, signup=False, **kwargs):
    """
    E-mail verification mails are sent:
    a) Explicitly: when a user signs up
    b) Implicitly: when a user attempts to log in using an unverified
    e-mail while EMAIL_VERIFICATION is mandatory.

    Especially in case of b), we want to limit the number of mails
    sent (consider a user retrying a few times), which is why there is
    a cooldown period before sending a new mail.
    """
    from .models import SmallsEmailAddress, SmallsEmailConfirmation

    COOLDOWN_PERIOD = timedelta(minutes=3)
    email = user_email(user)
    if email:
        try:
            email_address = SmallsEmailAddress.objects.get(user=user, email__iexact=email)
            if not email_address.verified:
                send_email = not SmallsEmailConfirmation.objects \
                    .filter(sent__gt=now() - COOLDOWN_PERIOD,
                            email_address=email_address) \
                    .exists()
                if send_email:
                    email_address.send_confirmation(request,
                                                    signup=signup, activate_view=kwargs.get('activate_view'))
            else:
                send_email = False
        except SmallsEmailAddress.DoesNotExist:
            send_email = True
            email_address = SmallsEmailAddress.objects.add_email(request,
                                                           user,
                                                           email,
                                                           signup=signup,
                                                           confirm=True)
            assert email_address
        # At this point, if we were supposed to send an email we have sent it.
        if send_email:
            get_adapter().add_message(request,
                                      messages.INFO,
                                      'account/messages/'
                                      'email_confirmation_sent.txt',
                                      {'email': email})
    if signup:
        request.session['account_user'] = user.pk
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()
Example #34
0
 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.update({
         'initial':
         initial,
         'email_required':
         kwargs.get('email_required', app_settings.EMAIL_REQUIRED)
     })
     super(SignupForm, self).__init__(*args, **kwargs)
    def is_auto_signup_allowed(self, request, sociallogin):
        # If email is specified, check for duplicate and if so, no auto signup.
        auto_signup = app_settings.AUTO_SIGNUP
        if auto_signup:
            email = user_email(sociallogin.user)
            # Let's check if auto_signup is really possible...
            if email:
                if account_settings.UNIQUE_EMAIL:
                    if email_address_exists(email):
                        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

        return auto_signup
Example #36
0
	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 unprimary_extra_primary_emails(self, user):
        primary_email_addresses = EmailAddress.objects.filter(
                user=user, primary=True)

        for primary_email_address in primary_email_addresses:
            if primary_email_address.email == user_email(user):
                break
        else:
            # Didn't find the main email addresses and break the for loop
            print ("WARNING: Multiple primary without a user.email match for"
                   "user pk %s; (tried: %s, using: %s)") % (
                                    user.pk,
                                    ", ".join([email_address.email
                                               for email_address
                                               in primary_email_addresses]),
                                    primary_email_address)

        primary_email_addresses.exclude(pk=primary_email_address.pk
                ).update(primary=False)
Example #38
0
	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)
Example #39
0
    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')

        # pass it the full name as the first item in 'txts' instead
        user_name = first_name + 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([
                    user_name, first_name, last_name, email, username, 'user'
                ]))
Example #40
0
 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)
Example #41
0
    def post(self, request, student):
        student = get_object_or_404(
            Student,
            teacher=request.user,
            user__username=student,
        )
        user = student.user

        email = user_email(request.user)

        if not email:
            messages.error(
                request,
                "Can not send a password reset link since your account ({}) doesn't have an email address associated with it.".format(request.user.username)
            )
            return redirect('teachers:teacher')

        temp_key = default_token_generator.make_token(user)
        path = reverse(
            'account_reset_password_from_key',
            kwargs={'uidb36': user_pk_to_url_str(user), 'key': temp_key},
        )
        context = {
            'current_site': get_current_site(request),
            'user': user,
            'password_reset_url': build_absolute_uri(request, path),
            'request': request,
            'username': user_username(user),
            'timeout_days': settings.PASSWORD_RESET_TIMEOUT_DAYS,
        }
        get_adapter(request).send_mail(
            'teachers/email/password_reset_key',
            email,
            context,
        )
        messages.success(
            request,
            "Password reset link for user {user} has been sent to your email address ({email})".format(
                user=user, email=email)
        )
        return redirect('teachers:teacher')
Example #42
0
 def is_open_for_signup(self, request, sociallogin):
     email = user_email(sociallogin.user)
     # If we have a user with that email already, we don't allow
     # a signup through a new provider. Revisit this in the future.
     if email_address_exists(email):
         User = get_user_model()
         try:
             user = User.objects.get(email__iexact=email)
             social_set = user.socialaccount_set.all()
             # If the account doesn't have any social logins yet,
             # allow the signup.
             if not social_set:
                 return True
             providers = [a.provider for a in social_set]
             request.other_logins = LoginMethod.objects.filter(
                 provider_id__in=providers)
         except User.DoesNotExist:
             request.other_logins = []
         return False
     else:
         return True
Example #43
0
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 save_user(self, request, sociallogin, form=None):
        email = user_email(sociallogin.account.user)
        try:
            u = User.objects.get(email=email)
            sociallogin.account.user = u
            u = super(CFSocialAccountAdapter,
                      self).save_user(request, sociallogin, form)
        except:
            try:
                u = super(CFSocialAccountAdapter,
                          self).save_user(request, sociallogin, form)
            except:
                u = User.objects.get(email=email)
            u.username = email.replace('@neuro.fchampalimaud.org', '').replace(
                '@research.fchampalimaud.org', '')
            u.set_password(User.objects.make_random_password(length=50))
            u.is_staff = True

        g = Group.objects.get(name=settings.PROFILE_GUEST)
        u.groups.add(g)
        u.save()
        return u
Example #45
0
    def pre_social_login(self, _, sociallogin):
        """Invoked after a user successfully auths with a provider, but before
        the login is actually processed on our side and before the
        pre_social_login signal is emitted.

        We use this hook to abort the login if the user is not coming from a
        whitelisted domain.  Otherwise this hook has no effect and the login
        proceeds as normal.

        Args:
          request: (unused)
          sociallogin: an allauth sociallogin instance with user data attached

        Raises:
          ImmediateHttpResponse if user's email domain is not in the whitelist
        """
        social_login_email = user_email(sociallogin.user)
        domain = social_login_email.split('@')[1]
        if domain not in settings.STAFF_EMAIL_DOMAIN_WHITELIST:
            # TODO(matt): log this
            login_url = urlresolvers.reverse('endagaweb.views.user.loginview')
            raise ImmediateHttpResponse(redirect(login_url))
Example #46
0
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 test_email_address_created(self):
        factory = RequestFactory()
        request = factory.get('/accounts/login/callback/')
        request.user = AnonymousUser()
        SessionMiddleware().process_request(request)
        MessageMiddleware().process_request(request)

        User = get_user_model()
        user = User()
        setattr(user, account_settings.USER_MODEL_USERNAME_FIELD, 'test')
        setattr(user, account_settings.USER_MODEL_EMAIL_FIELD, '*****@*****.**')

        account = SocialAccount(user=user, provider='openid', uid='123')
        sociallogin = SocialLogin(account)
        complete_social_login(request, sociallogin)

        user = User.objects.get(
            **{account_settings.USER_MODEL_USERNAME_FIELD: 'test'})
        self.assertTrue(
            SocialAccount.objects.filter(user=user, uid=account.uid).exists())
        self.assertTrue(
            EmailAddress.objects.filter(user=user,
                                        email=user_email(user)).exists())
Example #48
0
    def send_giftorder_mail(self, total_price, user):
        # TODO: move bank, beneficiary, account, reply e-mail into preferences.
        # TODO: make nicer HTML mail....
        messagetext = _(
            "Thank you so much for ordering a voucher and helping the couple to make their dream come true!"
        ) + "\n\n"
        messagetext += _(
            "The voucher will be issued after payment receipt.") + "\n\n"
        messagetext += _("Please send your payment as follows: ") + "\n\n"
        messagetext += _("Bank") + ": Zürcher Kantonalbank" + "\n"
        messagetext += _("Account") + ": IBAN CH68 0070 0110 0056 1840 3\n"
        messagetext += _(
            "In favour of") + ": Sibylle Widmer + Marco Zurbriggen\n"
        messagetext += _("Amount") + ": " + total_price.__str__() + "\n\n"

        try:
            send_mail(
                subject="The Travelling 2 - Voucher Order",
                message=messagetext,
                from_email="*****@*****.**",
                recipient_list=[user_email(user)],
            )
        except:
            pass
Example #49
0
def user_info(request):
    is_authenticated = OAuthAuthentication().is_authenticated(request)

    if is_authenticated:
        user = request.user
        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
    else:
        return HttpResponse(status=404)
    def save_user(self, request, user, serializer, commit=True):
        """
		Saves a new `User` instance using information provided in the
		signup form.
		"""
        secure = request.is_secure()
        protocol = 'https' if secure == True else 'http'
        serializer = registroSerializer(data=request.data)

        url = '%s://%s' % (protocol, request.get_host())
        if serializer.is_valid():
            affiliate = serializer.validated_data.pop('affiliate', None)
            data = serializer.validated_data
            instance = data.get('instance')
            client_type = data.pop('client_type', None)
            first_name = data.get('first_name')
            last_name = data.get('last_name')
            email = data.get('email')
            username = data.get('email').replace('@', '')
            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)
            if commit:
                user.save()
                # Ability not to commit makes it easier to derive from
                # this adapter by adding
                if client_type:
                    if client_type == 'condominio':
                        condominio_data = {
                            'rif': data.get('rif'),
                            'pais': data.get('pais'),
                            'terminos': data.get('terminos'),
                            'comprobante_rif': data.get('comprobante_rif'),
                            'user': user
                        }
                        instance = Condominio.objects.create(**condominio_data)
                        if affiliate:
                            instance.affiliate = affiliate
                            comission = get_comission(affiliate)
                            affiliate.comission = comission
                            affiliate.save()
                            #send email to affiliate
                            protocol = 'https' if request.is_secure(
                            ) else 'http'
                            site_name = get_current_site(request).name
                            site_url = protocol + '://' + site_name

                            message_context = {
                                'affiliate':
                                affiliate.user.get_full_name(),
                                'condominio_name':
                                str(data.get('first_name')) + ' ' +
                                str(data.get('last_name') or ''),
                                'site_url':
                                site_url,
                                'rif':
                                data.get('rif'),
                                'pais':
                                data.get('pais')
                            }
                            subject_context = {
                                'condominio_name':
                                str(data.get('first_name')) + ' ' +
                                str(data.get('last_name') or '')
                            }
                            subject = loader.render_to_string(
                                'account/email/affiliate_condo_subject.txt',
                                subject_context)
                            message = loader.render_to_string(
                                'account/email/affiliate_condo_message.txt',
                                message_context)
                            send_email.delay(subject, message,
                                             settings.DEFAULT_FROM_EMAIL,
                                             [affiliate.user.email])

                    elif client_type == 'afiliado':
                        afiliado_dada = {
                            'rif': data.get('rif'),
                            'terminos': data.get('terminos'),
                            'comprobante_rif': data.get('comprobante_rif'),
                            'comission': 0.10,
                            'user': user
                            #'url' : url + '/#/registro?affiliate='+ str(user.id)
                        }
                        instance = Affiliate.objects.create(**afiliado_dada)
                        instance.url = url + '/#/registro?affiliate=' + str(
                            user.pk)

            instance.save()
            return user
        else:
            return Response(serializer.errors)
Example #51
0
 def populate_username(self, request, user):
     # override the username population to always use the email
     user_field(user, app_settings.USER_MODEL_USERNAME_FIELD, user_email(user))
Example #52
0
 def _update_session(self, request, sociallogin):
     email = user_email(sociallogin.user)
     set_session_verification_email(request, email)
def create_default_provider(user) -> chain:
    email = user_email(user)  # type: str
    return guess_configuration.s(email) | _create_email_account_task.s(
        user.id) | verify_email_account_task.s(user.id)
    def pre_social_login(self, request, sociallogin):
        email = user_email(sociallogin.user)
        UserModel = get_user_model()
        login_provider_id = sociallogin.account.provider

        if (
                not email or
                not email_address_exists(email) or
                sociallogin.state.get('process') != AuthProcess.LOGIN
        ):
            # This is a new email address, or we're connecting social accounts
            # so we don't need to do anything
            return

        try:
            user = UserModel.objects.get(email=email)
        except UserModel.DoesNotExist:
            # This case shouldn't really happen, but even if it does, we
            # don't do anything and let the default behavior kick in.
            return

        social_accounts = list(SocialAccount.objects.filter(
            user=user
        ).values_list('provider', flat=True))

        if len(social_accounts) == 0:
            # This is a hack to associate existing accounts on pulse
            # that were added via Google Auth the old way to the new allauth
            # system. We only do this for new logins into this system.
            request.migrate_user = user
        elif login_provider_id in social_accounts:
            # In this case, the existing user already has a social account
            # and is logging into it using the same provider.
            return
        else:
            # Here the user already has a Pulse social account (e.g. Google)
            # but is logging in through a different social network
            # (e.g. Github) that uses the same email for the first time.
            # We redirect them to the login view where they have to login
            # through their existing social account on Pulse before going to
            # the Social Account Connections view to connect their secondary
            # social account.
            url = reverse('account_login')
            qs = QueryDict(mutable=True)
            next_url = sociallogin.get_redirect_url(request)
            if next_url:
                # We encode the final destination url in the connection
                # view url so that users are correctly rerouted after
                # connecting their accounts.
                qs['next'] = next_url
            next_url = '{url}?{qs}'.format(
                url=reverse('socialaccount_connections'),
                qs=qs.urlencode()
            )
            qs = QueryDict(mutable=True)
            qs['next'] = next_url
            qs['promptconnection'] = True
            qs['provider'] = providers.registry.by_id(login_provider_id).name

            raise ImmediateHttpResponse(
                response=HttpResponseRedirect(f'{url}?{qs.urlencode()}')
            )
Example #55
0
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

    # Stop here if invitations are required
    if auth_settings.INVITATION_REQUIRED:
        # Check for valid invitation key in session
        if 'invitation_key' not in request.session \
            or not InvitationKey.objects.is_key_valid(request.session['invitation_key']):
            return HttpResponseRedirect(auth_settings.NO_INVITATION_REDIRECT)

    if not auto_signup:
        request.session['socialaccount_sociallogin'] = sociallogin
        url = reverse('socialaccount_signup')
        ret = HttpResponseRedirect(url)
    else:
        # If we're still on auto signup, stop if invitations are required
        if auth_settings.INVITATION_REQUIRED:
            # Check for valid invitation key in session
            if 'invitation_key' not in request.session \
                or not InvitationKey.objects.is_key_valid(request.session['invitation_key']):
                return HttpResponseRedirect(
                    auth_settings.NO_INVITATION_REDIRECT)
        # Continue with auto signup
        # 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)
        # Make sure the user has a primary email address
        if EmailAddress.objects.filter(user=u).count() == 0:
            setup_user_email(request, u)
        ret = complete_social_signup(request, sociallogin)
    return ret
 def is_auto_signup_allowed(self, request, sociallogin):
     # If email is specified, check for duplicate and if so, no auto signup.
     email = user_email(sociallogin.account.user)
     return email.endswith('@neuro.fchampalimaud.org') or email.endswith(
         '@research.fchampalimaud.org')
 def is_open_for_signup(self, request, sociallogin):
     email = user_email(sociallogin.account.user)
     return email.endswith('@neuro.fchampalimaud.org') or email.endswith(
         '@research.fchampalimaud.org')
Example #58
0
    def custom_signup(self, request, user, commit=True):
        """Sign up for person or company using data provided."""
        # user can be either Company or Person object.
        from allauth.account.utils import user_email
        data = self.cleaned_data

        if data.get('full_name'):
            try:
                first_name, last_name = data.get('full_name').split(' ', 1)
            except ValueError:
                first_name, last_name = data.get('full_name'), None
            user.first_name = first_name
            user.last_name = last_name
        if data.get('phone'):
            user.phone = data.get('phone')
        if data.get('gender'):
            user.gender = data.get('gender')
        username = data.get('username')
        pattern = re.compile("^\d{10,13}")
        match = pattern.match(username)
        if match:
            user.phone = username
        else:
            user_email(user, username)
        password_set_by_user = True
        password = data.get("password")
        if (password == '') or (password is None):
            password_set_by_user = False
            password = User.objects.make_random_password()

        user.set_password(password)
        # self.populate_username(request, user)
        if commit:
            # Ability not to commit makes it easier to derive from
            # this adapter by adding
            user.save()

        referral = create_referral(user)
        user.referral = referral
        # provide incentive to user who referred this user.
        request = self.context.get('request')
        if request and 'referral_code' in request.data:
            referrer_user = get_referrer_user(request, user=user)

        user.save()
        # saving user_type and person or company's type depending on user object.
        user.user_type = list(data['account_type'].keys())[0]

        user_account_type = list(data['account_type'].values())[0]

        if user.user_type == User.COMPANY:
            typ, created = CompanyType.objects.get_or_create(
                company_type=user_account_type)
        elif user.user_type == User.PERSON:
            typ, created = PersonType.objects.get_or_create(
                person_type=user_account_type)
        user.typ.add(typ)

        # send password to post_save signal so add it in email context
        if not password_set_by_user:
            user._password = password

        return user
 def setUp(self):
     self.user = get_user_model()()
     allauth_utils.user_username(self.user, 'spam')
     allauth_utils.user_email(self.user, '*****@*****.**')
     self.user.save()
     allauth_utils.sync_user_email_addresses(self.user)
Example #60
0
 def populate_user(self, request: HttpRequest, sociallogin: SocialLogin,
                   data: dict):
     user = super().populate_user(request, sociallogin, data)
     if not user_username(user):
         user_username(user, user_email(user))
     return user