def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs): """Load extra data from provider and store it on current UserSocialAuth extra_data field. """ social_user = social_user or \ UserSocialAuth.get_social_auth(backend.name, uid) if kwargs['is_new'] and PROFILE_EMAIL_CONFIRMATION: emailaddress = EmailAddress(**{ 'user': user, 'email': user.email, 'verified': True, 'primary': True }) emailaddress.save() if social_user: extra_data = backend.extra_data(user, uid, response, details) if kwargs.get('original_email') and 'email' not in extra_data: extra_data['email'] = kwargs.get('original_email') if extra_data and social_user.extra_data != extra_data: if social_user.extra_data: social_user.extra_data.update(extra_data) else: social_user.extra_data = extra_data social_user.save() if backend.name == 'facebook' and kwargs['is_new']: response = json.loads( requests.get( 'https://graph.facebook.com/%s?access_token=%s' % (extra_data['id'], extra_data['access_token'])).content) try: user.city, user.country = response.get('hometown').get( 'name').split(', ') except AttributeError: pass try: user.birth_date = datetime.strptime(response.get('birthday'), '%m/%d/%Y').date() except AttributeError: pass user.save() return {'social_user': social_user}
def create_primary_email(user, email): ea = EmailAddress() ea.user=user ea.email=email ea.verified=True ea.primary=True ea.save()
def get_email_address(email, exclude_user=None): """ Returns an EmailAddress instance matching the given email. Both User.email and EmailAddress.email are considered candidates. This was done to deal gracefully with inconsistencies that are inherent due to the duplication of the email field in User and EmailAddress. In case a User.email match is found the result is returned in a temporary EmailAddress instance. """ try: emailaddresses = EmailAddress.objects if exclude_user: emailaddresses = emailaddresses.exclude(user=exclude_user) ret = emailaddresses.get(email__iexact=email) except EmailAddress.DoesNotExist: try: users = User.objects if exclude_user: users = users.exclude(user=exclude_user) usr = users.get(email__iexact=email) ret = EmailAddress(user=usr, email=email, verified=False, primary=True) except User.DoesNotExist: ret = None return ret
def save(self): username = self.cleaned_data["usuario"] nome = self.cleaned_data["nome"] sobrenome = self.cleaned_data["sobrenome"] email = self.cleaned_data["email"] password = self.cleaned_data["password1"] confirm = settings.ACCOUNT_EMAIL_VERIFICATION # @@@ clean up some of the repetition below -- DRY! if confirm: new_user = User.objects.create_user(username, email, password) if email: EmailAddress.objects.add_email(new_user, email) else: new_user = User.objects.create_user(username, email, password) EmailAddress(user=new_user, email=email, verified=True, primary=True).save() if settings.ACCOUNT_EMAIL_VERIFICATION: new_user.is_active = False new_user.first_name = nome new_user.last_name = sobrenome new_user.save() new_user.message_set.create(message=ugettext( u"<b>@%(username)s</b> seja bem vindo ao iellos!\nCrie seus elos, convide seus amigos e compartilhe informações." ) % {'username': new_user.username}) return username, password # required for authenticate()
def save(self, request=None): # don't assume a username is available. it is a common removal if # site developer wants to use email authentication. username = self.cleaned_data.get("username") email = self.cleaned_data["email"] if self.cleaned_data["confirmation_key"]: from friends.models import JoinInvitation # @@@ temporary fix for issue 93 try: join_invitation = JoinInvitation.objects.get(confirmation_key=self.cleaned_data["confirmation_key"]) confirmed = True except JoinInvitation.DoesNotExist: confirmed = False else: confirmed = False # @@@ clean up some of the repetition below -- DRY! if confirmed: if email == join_invitation.contact.email: new_user = self.create_user(username) join_invitation.accept(new_user) # should go before creation of EmailAddress below if request: messages.add_message(request, messages.INFO, ugettext(u"Your email address has already been verified") ) # already verified so can just create EmailAddress(user=new_user, email=email, verified=True, primary=True).save() else: new_user = self.create_user(username) join_invitation.accept(new_user) # should go before creation of EmailAddress below if email: if request: messages.add_message(request, messages.INFO, ugettext(u"Confirmation email sent to %(email)s") % { "email": email, } ) EmailAddress.objects.add_email(new_user, email) else: new_user = self.create_user(username) if email: if request and not EMAIL_VERIFICATION: messages.add_message(request, messages.INFO, ugettext(u"Confirmation email sent to %(email)s") % { "email": email, } ) EmailAddress.objects.add_email(new_user, email) if EMAIL_VERIFICATION: new_user.is_active = False new_user.save() self.after_signup(new_user) return new_user
def save(self): # assign email as user name username = self.cleaned_data["username"].lower() email = self.cleaned_data["email"].lower() password = self.cleaned_data["password1"] if self.cleaned_data["confirmation_key"]: from friends.models import JoinInvitation # @@@ temporary fix for issue 93 try: join_invitation = JoinInvitation.objects.get(confirmation_key = self.cleaned_data["confirmation_key"]) confirmed = True except JoinInvitation.DoesNotExist: confirmed = False else: confirmed = False # @@@ clean up some of the repetition below -- DRY! if confirmed: if email == join_invitation.contact.email: new_user = User.objects.create_user(username, email, password) join_invitation.accept(new_user) # should go before creation of EmailAddress below new_user.message_set.create(message=ugettext(u"Your email address has already been verified")) # already verified so can just create EmailAddress(user=new_user, email=email, verified=True, primary=True).save() else: new_user = User.objects.create_user(username, "", password) join_invitation.accept(new_user) # should go before creation of EmailAddress below if email: new_user.message_set.create(message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email}) EmailAddress.objects.add_email(new_user, email) else: new_user = User.objects.create_user(username, "", password) if email: new_user.message_set.create(message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email}) EmailAddress.objects.add_email(new_user, email) if settings.ACCOUNT_EMAIL_VERIFICATION: new_user.is_active = False new_user.save() zipcode_obj = ZipCode.objects.get(code=self.cleaned_data["zip_code"]) phone = parse_phone_number(self.cleaned_data["phone"], zipcode_obj.city.region.country.code) t = TxtTemplates() msg = t.render(TxtTemplates.templates["CUSTOMER"]["VERIFY_PHONE"], {}) sms_notify(phone, msg) new_customer = Customer.objects.create(user=new_user, address_1=self.cleaned_data["address_1"], # address_2=self.cleaned_data["address_2"], # phone=phone, zipcode=zipcode_obj, verified=True, ) new_customer.set_location_from_address() p = CustomerPhone.objects.create(number=phone ,customer = new_customer) return username, password # required for authenticate()
def load_extra_data(backend, details, response, uid, user, social_user=None, *args, **kwargs): """Load extra data from provider and store it on current UserSocialAuth extra_data field. """ social_user = social_user or \ UserSocialAuth.get_social_auth(backend.name, uid) if kwargs['is_new'] and PROFILE_EMAIL_CONFIRMATION: emailaddress = EmailAddress(**{ 'user': user, 'email': user.email, 'verified': True, 'primary': True }) emailaddress.save() if social_user: extra_data = backend.extra_data(user, uid, response, details) if kwargs.get('original_email') and 'email' not in extra_data: extra_data['email'] = kwargs.get('original_email') if extra_data and social_user.extra_data != extra_data: if social_user.extra_data: social_user.extra_data.update(extra_data) else: social_user.extra_data = extra_data social_user.save() if backend.name == 'facebook' and kwargs['is_new']: response = json.loads(requests.get('https://graph.facebook.com/%s?access_token=%s' % (extra_data['id'], extra_data['access_token'])).content) try: user.city, user.country = response.get('hometown').get('name').split(', ') except AttributeError: pass try: user.birth_date = datetime.strptime(response.get('birthday'), '%m/%d/%Y').date() except AttributeError: pass user.save() return {'social_user': social_user}
def save(self): username = self.cleaned_data["username"] email = self.cleaned_data["email"] password = self.cleaned_data["password1"] if self.cleaned_data["confirmation_key"]: from friends.models import JoinInvitation # @@@ temporary fix for issue 93 try: join_invitation = JoinInvitation.objects.get( confirmation_key=self.cleaned_data["confirmation_key"]) confirmed = True except JoinInvitation.DoesNotExist: confirmed = False else: confirmed = False # @@@ clean up some of the repetition below -- DRY! if confirmed: if email == join_invitation.contact.email: new_user = User.objects.create_user(username, email, password) join_invitation.accept( new_user ) # should go before creation of EmailAddress below new_user.message_set.create(message=ugettext( u"Your email address has already been verified")) # already verified so can just create EmailAddress(user=new_user, email=email, verified=True, primary=True).save() else: new_user = User.objects.create_user(username, "", password) join_invitation.accept( new_user ) # should go before creation of EmailAddress below if email: new_user.message_set.create(message=ugettext( u"Confirmation email sent to %(email)s") % {'email': email}) EmailAddress.objects.add_email(new_user, email) else: new_user = User.objects.create_user(username, "", password) if email: new_user.message_set.create( message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email}) EmailAddress.objects.add_email(new_user, email) if settings.ACCOUNT_EMAIL_VERIFICATION: new_user.is_active = False new_user.save() return username, password # required for authenticate()
def save(self, speaker, request=None): # don't assume a username is available. it is a common removal if # site developer wants to use e-mail authentication. username = self.cleaned_data.get("username") email = self.cleaned_data["email"] new_user = self.create_user(username) if speaker.invite_email == new_user.email: # already verified so can just create EmailAddress(user=new_user, email=email, verified=True, primary=True).save() else: if request: messages.info(request, u"Confirmation e-mail sent to %(email)s" % {"email": email}) EmailAddress.objects.add_email(new_user, email) new_user.is_active = False new_user.save() self.after_signup(new_user) return new_user
def test_verify_email_for_bulk_user(self): new_network = Network.objects.create(slug='new-net', name='new network', creator=self.superman) self.assertTrue( self.client.login(username='******', password='******')) response = self.client.post('/networks/new-net/bulkimport/', {'emails': '*****@*****.**'}) bulk_user = get_email_user('*****@*****.**') self.joe.emailaddress_set.add(EmailAddress(email='*****@*****.**')) email_address = self.joe.emailaddress_set.get(email='*****@*****.**') email_address.verified = True email_address.save() joe_member = new_network.members.get(user=self.joe) # joe should be accepted self.assertTrue(joe_member.is_accepted) # old dummy user should be gone self.assertRaises(User.DoesNotExist, User.objects.get, id=bulk_user.id) self.assertEquals(new_network.members.bulk().count(), 0) new_network.delete()
def test_account_password_reset_API(self): url = reverse('api_account_password_reset') # GET 403 - user must not be authenticated response = self.client.get(url) self.assertEqual(403, response.status_code) self.client.logout() # GET 405 response = self.client.get(url) self.assertEqual(405, response.status_code) # POST 400: missing required field response = self.client.post(url) self.assertContains(response, 'required', status_code=400) # POST 400: email not found in the DB response = self.client.post(url, { 'email': '*****@*****.**' }) self.assertContains(response, 'address not verified for any', status_code=400) # POST 200 user = User.objects.get(username='******') if PROFILE_EMAIL_CONFIRMATION: email_address = EmailAddress(user=user, email=user.email, verified=True, primary=True) email_address.save() response = self.client.post(url, { 'email': user.email }) self.assertEqual(200, response.status_code) self.assertEqual(PasswordReset.objects.filter(user=user).count(), 1, 'dummy email outbox should contain 1 email message') self.assertEqual(len(mail.outbox), 1, 'dummy email outbox should contain 1 email message') password_reset = PasswordReset.objects.get(user=user) uid_36 = int_to_base36(user.id) url = reverse('api_account_password_reset_key', kwargs={ 'uidb36': uid_36, 'key': password_reset.temp_key }) # POST 400: wrong password params = { 'password1': 'new_password', 'password2': 'wrong' } response = self.client.post(url, params) self.assertContains(response, '"password2"', status_code=400) # correct params['password2'] = 'new_password' response = self.client.post(url, json.dumps(params), content_type='application/json') self.assertContains(response, '"detail"') # ensure password has been changed user = User.objects.get(username='******') self.assertTrue(user.check_password('new_password')) # ensure password reset object has been used password_reset = PasswordReset.objects.get(user=user) self.assertTrue(password_reset.reset) # request a new password reset key response = self.client.post(reverse('api_account_password_reset'), { 'email': user.email }) self.assertEqual(200, response.status_code) # test HTML version of password reset from key password_reset = PasswordReset.objects.get(user=user, reset=False) uid = int_to_base36(password_reset.user_id) key = password_reset.temp_key url = reverse('account_password_reset_key', args=[uid, key]) response = self.client.get(url) self.assertEqual(200, response.status_code) response = self.client.post(url, { 'password1': 'changed', 'password2': 'changed' } ) self.assertEqual(200, response.status_code) # ensure password has been changed user = User.objects.get(username='******') self.assertTrue(user.check_password('changed')) # ensure password reset object has been used password_reset = PasswordReset.objects.filter(user=user).order_by('-id')[0] self.assertTrue(password_reset.reset)
def import_users(self): """ save users to local DB """ self.message('saving users into local DB') saved_users = [] # loop over all extracted unique email addresses for email in self.email_set: owner = self.users_dict[email].get('owner') # if owner is not specified, build username from email if owner.strip() == '': owner, domain = email.split('@') # replace any points with a space owner = owner.replace('.', ' ') # if owner has a space, assume he specified first and last name if ' ' in owner: owner_parts = owner.split(' ') first_name = owner_parts[0] last_name = owner_parts[1] else: first_name = owner last_name = '' # username must be slugified otherwise won't get into the DB username = slugify(owner) # create one user for each mail address user = User(**{ "username": username, "password": self.generate_random_password(), "first_name": first_name.capitalize(), "last_name": last_name.capitalize(), "email": email, "is_active": True }) # be sure username is unique counter = 1 original_username = username while True: if User.objects.filter(username=user.username).count() > 0: counter += 1 user.username = '******' % (original_username, counter) else: break try: # validate data and save user.full_clean() user.save() # store id self.users_dict[email]['id'] = user.id # append to saved users saved_users.append(user) self.verbose('Saved user %s (%s) with email <%s>' % (user.username, user.get_full_name(), user.email)) except Exception as e: self.message('Could not save user %s, got exception: %s' % (user.username, e)) # mark email address as confirmed if feature is enabled if EMAIL_ADDRESS_APP_INSTALLED: try: email_address = EmailAddress(user=user, email=user.email, verified=True, primary=True) email_address.full_clean() email_address.save() except Exception as e: self.message('Could not save email address for user %s, got exception: %s' % (user.username, e)) self.message('saved %d users into local DB' % len(saved_users)) self.saved_users = saved_users
def save(self, request=None): # don't assume a username is available. it is a common removal if # site developer wants to use e-mail authentication. # username = self.cleaned_data.get("username") email = self.cleaned_data["email"].strip().lower() password = self.cleaned_data.get("password1") profile_data = { 'first_name': self.cleaned_data["first_name"], 'last_name': self.cleaned_data["last_name"], 'zip_code': self.cleaned_data["zip_code"], 'gender': self.cleaned_data["gender"], 'source': request.session.get('source', settings.DEFAULT_SOURCE) } is_join_invitation = False if self.cleaned_data["confirmation_key"]: from friends.models import JoinInvitationEmail # @@@ temporary fix for issue 93 try: join_invitation = JoinInvitationEmail.objects.get( confirmation_key=self.cleaned_data["confirmation_key"]) is_join_invitation = True except JoinInvitationEmail.DoesNotExist: pass new_user = self.create_user(profile_data['first_name'], profile_data['last_name'], email, password) new_profile = None try: new_profile = self.create_profile(new_user, profile_data) except: pass if new_profile is None: new_user.delete() raise Exception('User creation failed. Please try again later') else: if is_join_invitation: join_invitation.accept( new_user ) # should go before creation of EmailAddress below if email == join_invitation.contact.email: EmailAddress(user=new_user, email=email, verified=True, primary=True).save() send_email(new_user.email, 'welcome_email', ctx={'actor': new_profile}, skip_footer=True) else: EmailAddress.objects.add_email(new_user, email) if EMAIL_VERIFICATION: new_user.is_active = False new_user.save() self.after_signup(new_user) return new_user
def test_account_password_reset_API(self): url = reverse('api_account_password_reset') # GET 403 - user must not be authenticated response = self.client.get(url) self.assertEqual(403, response.status_code) self.client.logout() # GET 405 response = self.client.get(url) self.assertEqual(405, response.status_code) # POST 400: missing required field response = self.client.post(url) self.assertContains(response, 'required', status_code=400) # POST 400: email not found in the DB response = self.client.post(url, {'email': '*****@*****.**'}) self.assertContains(response, 'address not verified for any', status_code=400) # POST 200 user = User.objects.get(username='******') if PROFILE_EMAIL_CONFIRMATION: email_address = EmailAddress(user=user, email=user.email, verified=True, primary=True) email_address.save() response = self.client.post(url, {'email': user.email}) self.assertEqual(200, response.status_code) self.assertEqual( PasswordReset.objects.filter(user=user).count(), 1, 'dummy email outbox should contain 1 email message') self.assertEqual(len(mail.outbox), 1, 'dummy email outbox should contain 1 email message') password_reset = PasswordReset.objects.get(user=user) uid_36 = int_to_base36(user.id) url = reverse('api_account_password_reset_key', kwargs={ 'uidb36': uid_36, 'key': password_reset.temp_key }) # POST 400: wrong password params = {'password1': 'new_password', 'password2': 'wrong'} response = self.client.post(url, params) self.assertContains(response, '"password2"', status_code=400) # correct params['password2'] = 'new_password' response = self.client.post(url, json.dumps(params), content_type='application/json') self.assertContains(response, '"detail"') # ensure password has been changed user = User.objects.get(username='******') self.assertTrue(user.check_password('new_password')) # ensure password reset object has been used password_reset = PasswordReset.objects.get(user=user) self.assertTrue(password_reset.reset) # request a new password reset key response = self.client.post(reverse('api_account_password_reset'), {'email': user.email}) self.assertEqual(200, response.status_code) # test HTML version of password reset from key password_reset = PasswordReset.objects.get(user=user, reset=False) uid = int_to_base36(password_reset.user_id) key = password_reset.temp_key url = reverse('account_password_reset_key', args=[uid, key]) response = self.client.get(url) self.assertEqual(200, response.status_code) response = self.client.post(url, { 'password1': 'changed', 'password2': 'changed' }) self.assertEqual(200, response.status_code) # ensure password has been changed user = User.objects.get(username='******') self.assertTrue(user.check_password('changed')) # ensure password reset object has been used password_reset = PasswordReset.objects.filter( user=user).order_by('-id')[0] self.assertTrue(password_reset.reset)
def save(self): # username = self.cleaned_data["username"] firstname = self.cleaned_data['firstname'] lastname = self.cleaned_data['lastname'] email = self.cleaned_data["email"] password = self.cleaned_data["password1"] username = User.objects.make_random_password() # not a password per se, just a random string while User.objects.filter(username=username).count() > 0: # ensure uniqueness username = User.objects.make_random_password() if self.cleaned_data["confirmation_key"]: from friends.models import JoinInvitation # @@@ temporary fix for issue 93 (-- Pinax comment) try: join_invitation = JoinInvitation.objects.get(confirmation_key = self.cleaned_data["confirmation_key"]) confirmed = True except JoinInvitation.DoesNotExist: confirmed = False else: confirmed = False # @@@ clean up some of the repetition below -- DRY! (-- Pinax comment) add_email = None if confirmed: if email == join_invitation.contact.email: new_user = User.objects.create_user(username, email, password) join_invitation.accept(new_user) # should go before creation of EmailAddress below new_user.message_set.create(message=ugettext(u"Your email address has already been verified")) # already verified so can just create EmailAddress(user=new_user, email=email, verified=True, primary=True).save() else: new_user = User.objects.create_user(username, "", password) join_invitation.accept(new_user) # should go before creation of EmailAddress below if email: new_user.message_set.create(message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email}) add_email = email else: try: new_user = User.objects.get(email=email, is_bulk=True) signals.listupgrade.send(sender=new_user, user=new_user) except User.DoesNotExist: new_user = User.objects.create_user(username, "", password) signals.signup.send(sender=new_user, user=new_user) if email: # new_user.message_set.create(message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email}) add_email = email profile = new_user.get_profile() profile.first_name = firstname profile.last_name = lastname profile.save() new_user.first_name = firstname new_user.last_name = lastname if settings.ACCOUNT_EMAIL_VERIFICATION: new_user.is_active = False new_user.save() # needs to be moved down after user is saved, so that the email # confirmation message has the peron's actual name in it if add_email: # email already exists in system? re-send verification... email_address = get_object_or_none(EmailAddress, user=new_user, email=add_email) if email_address: EmailConfirmation.objects.send_confirmation(email_address, template="emailconfirmation/newuser.txt") # otherwise, create a new email (verification will be sent automatically) else: EmailAddress.objects.add_email(new_user, add_email, confirmation_template="emailconfirmation/newuser.txt") if self.cleaned_data['chapter'] != "none" and self.cleaned_data['chapter'] != "": chapter = get_object_or_404(Network, slug=self.cleaned_data['chapter']) chapter.add_member(new_user) return username, password # required for authenticate()
def save(self): username = self.cleaned_data["username"] email = self.cleaned_data["email"] password = self.cleaned_data["password1"] conn = bitcoind.connect_to_local() if self.cleaned_data["confirmation_key"]: from friends.models import JoinInvitation # @@@ temporary fix for issue 93 try: join_invitation = JoinInvitation.objects.get( confirmation_key=self.cleaned_data["confirmation_key"]) confirmed = True except JoinInvitation.DoesNotExist: confirmed = False else: confirmed = False # @@@ clean up some of the repetition below -- DRY! if confirmed: if email == join_invitation.contact.email: new_user = User.objects.create_user(username, email, password) join_invitation.accept( new_user ) # should go before creation of EmailAddress below new_user.message_set.create(message=ugettext( u"Your email address has already been verified")) # already verified so can just create EmailAddress(user=new_user, email=email, verified=True, primary=True).save() else: new_user = User.objects.create_user(username, "", password) join_invitation.accept( new_user ) # should go before creation of EmailAddress below if email: new_user.message_set.create(message=ugettext( u"Confirmation email sent to %(email)s") % {'email': email}) EmailAddress.objects.add_email(new_user, email) else: new_user = User.objects.create_user(username, "", password) if email: new_user.message_set.create( message=ugettext(u"Confirmation email sent to %(email)s") % {'email': email}) EmailAddress.objects.add_email(new_user, email) if settings.ACCOUNT_EMAIL_VERIFICATION: new_user.is_active = False new_user.save() # Create their bitcoin account. # By default we will be creating an account with only their username. # Subsequent accounts made via the JSON-RPC interface will be in the # format username+label, where username is their username and label # is the label passed in by the JSON-RPC call. address = conn.getnewaddress(util.getaccount(username, "")) addressObj = Address(user=new_user, address=address, label="", is_primary=True) addressObj.save() return username, password # required for authenticate()
def customer_register(email, username, zipcode, phone, password, address, method): data = {} # sanitize inputs if email is not None: email = check_email(email) if email is None: data["result"] = -1 data["result_msg"] = "Email address is used by another user." return data if zipcode is not None: zipcode = check_zipcode(zipcode) if zipcode is None: data["result"] = -2 data["result_msg"] = "Zip Code is invalid or not in the system." return data if phone is not None: phone = check_phone(phone) if phone is None: data["result"] = -3 data["result_msg"] = "Phone number is used by another user." return data if username is None: if email is not None: username = email elif phone is not None: username = phone else: data["result"] = -4 data["result_msg"] = "Either email address, phone number or username is required." return data is_random_password = False if password is None: s = string.lowercase + string.digits password = ''.join(random.sample(s,6)) is_random_password = True try: user = User.objects.create_user(username, "", password) user.save() except IntegrityError: data["result"] = -5 data["result_msg"] = "'" + username + "' is used by the other user." return data # create customer information c = Customer(user=user, zipcode=zipcode, verified=True) c.save() CustomerPhone.objects.create(customer=c, number = phone) c.set_location_from_address() num_merchants = c.count_merchants_within_miles() t = TxtTemplates() args = {"email": email, "number": num_merchants} if is_random_password: args["password"] = password, welcome_msg = t.render(TxtTemplates.templates["CUSTOMER"]["SIGNUP_SUCCESS"], args) else: welcome_msg = t.render(TxtTemplates.templates["CUSTOMER"]["SIGNUP_SUCCESS_NO_PASSWORD"], args) if email is not None: e = EmailAddress(user=user, email=email, verified=True, primary=True) e.save() send_mail('Welcome to Shoppley', welcome_msg, '*****@*****.**', [email], fail_silently=True) if phone is not None: if method == "SMS": sms_notify(phone, welcome_msg) else: # send verification sms verify_msg = t.render(TxtTemplates.templates["CUSTOMER"]["VERIFY_PHONE"], {}) sms_notify(phone, verify_msg) data["result"] = 1 data["result_msg"] = "User registered successfully." data["username"] = username data["password"] = password return data;
def import_users(self): """ save users to local DB """ self.message('saving users into local DB') saved_users = [] # loop over all extracted unique email addresses for email in self.email_set: owner = self.users_dict[email].get('owner') # if owner is not specified, build username from email if owner.strip() == '': owner, domain = email.split('@') # replace any points with a space owner = owner.replace('.', ' ') # if owner has a space, assume he specified first and last name if ' ' in owner: owner_parts = owner.split(' ') first_name = owner_parts[0] last_name = owner_parts[1] else: first_name = owner last_name = '' # username must be slugified otherwise won't get into the DB username = slugify(owner) # check if user exists first try: # try looking by email user = User.objects.get(email=email) except User.DoesNotExist: try: # try looking by username user = User.objects.get(username=username) except User.DoesNotExist: # otherwise init new user = User() # generate new password only for new users user.password = self.generate_random_password() # we'll create one user for each unique email address we've got user.username = username user.first_name = first_name.capitalize() user.last_name = last_name.capitalize() user.email = email user.is_active = True # extract date joined from old nodes # find the oldest node of this user oldest_node = OldNode.objects.filter( email=email).order_by('added')[0] user.date_joined = oldest_node.added # be sure username is unique counter = 1 original_username = username while True: # do this check only if user is new if not user.pk and User.objects.filter( username=user.username).count() > 0: counter += 1 user.username = '******' % (original_username, counter) else: break try: # validate data and save user.full_clean() user.save() except Exception as e: # if user already exists use that instance if (User.objects.filter(email=email).count() == 1): user = User.objects.get(email=email) # otherwise report error else: user = None tb = traceback.format_exc() self.message( 'Could not save user %s, got exception:\n\n%s' % (user.username, tb)) # if we got a user to add if user is not None: # store id self.users_dict[email]['id'] = user.id # append to saved users saved_users.append(user) self.verbose('Saved user %s (%s) with email <%s>' % (user.username, user.get_full_name(), user.email)) # mark email address as confirmed if feature is enabled if EMAIL_ADDRESS_APP_INSTALLED and EmailAddress.objects.filter( email=user.email).count() is 0: try: email_address = EmailAddress(user=user, email=user.email, verified=True, primary=True) email_address.full_clean() email_address.save() except Exception as e: tb = traceback.format_exc() self.message( 'Could not save email address for user %s, got exception:\n\n%s' % (user.username, tb)) self.message('saved %d users into local DB' % len(saved_users)) self.saved_users = saved_users