def create_user_and_user_profile(self, email, username, password, custom_field, complete_name, first_name, last_name): """ Create a new user, add a new Registration instance for letting user verify its identity and create a user profile. :param email: user's email address :param username: user's username :param name: user's name :param country: user's country :param password: user's password :return: User instance of the new user. """ user = User( username=username, email=email, is_active=True, first_name=first_name, last_name=last_name, ) user.set_password(password) user.save() registration = Registration() registration.register(user) """ reg = Registration() reg.register(user) """ #user.save() profile = UserProfile(user=user) profile.custom_field = json.dumps(custom_field) profile.name = complete_name profile.save() return user
def test_do_not_send_email_and_do_activate(self): """ Tests that when an inactive user logs-in using the social auth, an activation email is not sent. """ pipeline_partial = { 'kwargs': { 'social': { 'uid': 'fake uid' } } } user = UserFactory(is_active=False) Registration().register(user) request = RequestFactory().get(settings.SOCIAL_AUTH_INACTIVE_USER_URL) request.user = user with patch('student.views.management.compose_and_send_activation_email') as email: with patch('third_party_auth.provider.Registry.get_from_pipeline') as reg: with patch('third_party_auth.pipeline.get', return_value=pipeline_partial): with patch('third_party_auth.pipeline.running', return_value=True): with patch('third_party_auth.is_enabled', return_value=True): reg.skip_email_verification = True inactive_user_view(request) self.assertEquals(user.is_active, True) self.assertEquals(email.called, False, msg='method should not have been called')
def _do_create_account(post_vars): """ Given cleaned post variables, create the User and UserProfile objects, as well as the registration for this user. Returns a tuple (User, UserProfile, Registration). Note: this function is also used for creating test users. """ user = User(username=post_vars['username'], email=post_vars['email'], is_active=False) user.set_password(post_vars['password']) registration = Registration() # TODO: Rearrange so that if part of the process fails, the whole process fails. # Right now, we can have e.g. no registration e-mail sent out and a zombie # account try: user.save() except IntegrityError: js = {'success': False} # Figure out the cause of the integrity error if len(User.objects.filter(username=post_vars['username'])) > 0: js['value'] = "An account with the Public Username '" + post_vars[ 'username'] + "' already exists." js['field'] = 'username' return HttpResponse(json.dumps(js)) if len(User.objects.filter(email=post_vars['email'])) > 0: js['value'] = "An account with the Email '" + post_vars[ 'email'] + "' already exists." js['field'] = 'email' return HttpResponse(json.dumps(js)) raise registration.register(user) profile = UserProfile(user=user) profile.name = post_vars['name'] profile.level_of_education = post_vars.get('level_of_education') profile.gender = post_vars.get('gender') profile.mailing_address = post_vars.get('mailing_address') profile.goals = post_vars.get('goals') try: profile.year_of_birth = int(post_vars['year_of_birth']) except (ValueError, KeyError): # If they give us garbage, just ignore it instead # of asking them to put an integer. profile.year_of_birth = None try: profile.save() except Exception: log.exception("UserProfile creation failed for user {0}.".format( user.id)) return (user, profile, registration)
def do_create_account_no_registration(data): """ Given cleaned post variables, create the User and UserProfile objects, as well as the registration for this user. Returns a tuple (User, UserProfile, Registration). Note: this function is also used for creating test users. """ # Check if ALLOW_PUBLIC_ACCOUNT_CREATION flag turned off to restrict user account creation proposed_username = data["username"] user = User(username=proposed_username, email=data["phone_number"] + settings.DEFAULT_EMAIL_ACCOUNT_DOMAIN, is_active=True) log.warning("phone: " + data["phone_number"]) password = normalize_password(data["password"]) user.set_password(password) registration = Registration() try: with transaction.atomic(): user.save() except IntegrityError: # Figure out the cause of the integrity error # TODO duplicate email is already handled by form.errors above as a ValidationError. # The checks for duplicate email/username should occur in the same place with an # AccountValidationError and a consistent user message returned (i.e. both should # return "It looks like {username} belongs to an existing account. Try again with a # different username.") if username_exists_or_retired(user.username): raise AccountValidationError( USERNAME_EXISTS_MSG_FMT.format(username=proposed_username), field="username") elif email_exists_or_retired(user.email): raise AccountValidationError(_( "An account with the Email '{email}' already exists.").format( email=user.email), field="email") else: raise registration.register(user) profile_fields = [ "name", "level_of_education", "gender", "mailing_address", "city", "country", "goals", "year_of_birth", "phone_number", "web_accelerator_name", "web_accelerator_link" ] profile = UserProfile(user=user, **{key: data.get(key) for key in profile_fields}) profile.save() # except Exception: # log.exception("UserProfile creation failed for user {id}.".format(id=user.id)) # raise log.warning("Testing the process to register {id}".format(id=user.id)) return user, profile
def setUp(self): super(TestActivateAccount, self).setUp() self.username = "******" self.email = "*****@*****.**" self.user = User.objects.create(username=self.username, email=self.email, is_active=False) # Set Up Registration self.registration = Registration() self.registration.register(self.user) self.registration.save()
def setUp(self): """ Setup components used by each test.""" super(SendActivationEmailTestCase, self).setUp() self.student = UserFactory() registration = Registration() registration.register(self.student) self.msg = compose_activation_email("http://www.example.com", self.student, registration)
def test_send_email_to_inactive_user(self, email): """ Tests that when an inactive user logs-in using the social auth, system sends an activation email to the user. """ inactive_user = UserFactory(is_active=False) Registration().register(inactive_user) request = RequestFactory().get(settings.SOCIAL_AUTH_INACTIVE_USER_URL) request.user = inactive_user with patch('edxmako.request_context.get_current_request', return_value=request): with patch('third_party_auth.pipeline.running', return_value=False): inactive_user_view(request) self.assertEqual(email.called, True, msg='method should have been called')
def setUp(self): super(TestActivateAccount, self).setUp() self.username = "******" self.email = "*****@*****.**" self.password = "******" self.user = UserFactory.create( username=self.username, email=self.email, password=self.password, is_active=False, ) # Set Up Registration self.registration = Registration() self.registration.register(self.user) self.registration.save()
def create_user(username, password, email, name): user = User( username=username, email=email, is_active=True, ) user.set_password(password) user.save() registration = Registration() registration.register(user) profile = UserProfile(user=user) profile.name = name profile.save()
def test_send_email_to_inactive_user(self, mock_log): """ Tests that when an inactive user logs-in using the social auth, system sends an activation email to the user. """ inactive_user = UserFactory(is_active=False) Registration().register(inactive_user) request = RequestFactory().get(settings.SOCIAL_AUTH_INACTIVE_USER_URL) request.user = inactive_user with patch('edxmako.request_context.get_current_request'): inactive_user_view(request) mock_log.info.assert_called_with( "Activation Email has been sent to User {user_email}".format( user_email=inactive_user.email))
def setUp(self): update_email_marketing_config(enabled=False) self.request_factory = RequestFactory() self.user = UserFactory.create(username='******', email=TEST_EMAIL) self.registration = Registration() self.registration.register(self.user) self.request = self.request_factory.get("foo") update_email_marketing_config(enabled=True) # create some test course objects self.course_id_string = 'edX/toy/2012_Fall' self.course_id = CourseKey.from_string(self.course_id_string) self.course_url = 'http://testserver/courses/edX/toy/2012_Fall/info' self.site = Site.objects.get_current() self.request.site = self.site super(EmailMarketingTests, self).setUp()
def setUp(self): super(TestActivateAccount, self).setUp() self.username = "******" self.email = "*****@*****.**" self.password = "******" self.user = UserFactory.create( username=self.username, email=self.email, password=self.password, is_active=False, ) # Set Up Registration self.registration = Registration() self.registration.register(self.user) self.registration.save() self.platform_name = configuration_helpers.get_value('PLATFORM_NAME', settings.PLATFORM_NAME) self.activation_email_support_link = configuration_helpers.get_value( 'ACTIVATION_EMAIL_SUPPORT_LINK', settings.ACTIVATION_EMAIL_SUPPORT_LINK ) or settings.SUPPORT_SITE_LINK
def create_user(self, uname, name, password=None): """ Creates a user """ if not uname: return _('Must provide username') if not name: return _('Must provide full name') msg = u'' if not password: return _('Password must be supplied') email = uname if '@' not in email: msg += _('email address required (not username)') return msg new_password = password user = User(username=uname, email=email, is_active=True) user.set_password(new_password) try: user.save() except IntegrityError: msg += _(u'Oops, failed to create user {user}, {error}').format( user=user, error="IntegrityError" ) return msg reg = Registration() reg.register(user) profile = UserProfile(user=user) profile.name = name profile.save() msg += _(u'User {user} created successfully!').format(user=user) return msg
def do_create_account(form, custom_form=None): """ Given cleaned post variables, create the User and UserProfile objects, as well as the registration for this user. Returns a tuple (User, UserProfile, Registration). Note: this function is also used for creating test users. """ # Check if ALLOW_PUBLIC_ACCOUNT_CREATION flag turned off to restrict user account creation if not configuration_helpers.get_value( 'ALLOW_PUBLIC_ACCOUNT_CREATION', settings.FEATURES.get('ALLOW_PUBLIC_ACCOUNT_CREATION', True) ): raise PermissionDenied() errors = {} errors.update(form.errors) if custom_form: errors.update(custom_form.errors) if errors: raise ValidationError(errors) proposed_username = form.cleaned_data["username"] user = User( username=proposed_username, email=form.cleaned_data["email"], is_active=False ) password = normalize_password(form.cleaned_data["password"]) user.set_password(password) registration = Registration() # TODO: Rearrange so that if part of the process fails, the whole process fails. # Right now, we can have e.g. no registration e-mail sent out and a zombie account try: with transaction.atomic(): user.save() if custom_form: custom_model = custom_form.save(commit=False) custom_model.user = user custom_model.save() except IntegrityError: # Figure out the cause of the integrity error # TODO duplicate email is already handled by form.errors above as a ValidationError. # The checks for duplicate email/username should occur in the same place with an # AccountValidationError and a consistent user message returned (i.e. both should # return "It looks like {username} belongs to an existing account. Try again with a # different username.") if username_exists_or_retired(user.username): raise AccountValidationError( USERNAME_EXISTS_MSG_FMT.format(username=proposed_username), field="username" ) elif email_exists_or_retired(user.email): raise AccountValidationError( _("An account with the Email '{email}' already exists.").format(email=user.email), field="email" ) else: raise registration.register(user) profile_fields = [ "name", "level_of_education", "gender", "mailing_address", "city", "country", "goals", "year_of_birth" ] profile = UserProfile( user=user, **{key: form.cleaned_data.get(key) for key in profile_fields} ) extended_profile = form.cleaned_extended_profile if extended_profile: profile.meta = json.dumps(extended_profile) try: profile.save() except Exception: log.exception("UserProfile creation failed for user {id}.".format(id=user.id)) raise return user, profile, registration
def create_account(username, password, email): """Create a new user account. This will implicitly create an empty profile for the user. WARNING: This function does NOT yet implement all the features in `student/views.py`. Until it does, please use this method ONLY for tests of the account API, not in production code. In particular, these are currently missing: * 3rd party auth * External auth (shibboleth) * Complex password policies (ENFORCE_PASSWORD_POLICY) In addition, we assume that some functionality is handled at higher layers: * Analytics events * Activation email * Terms of service / honor code checking * Recording demographic info (use profile API) * Auto-enrollment in courses (if invited via instructor dash) Args: username (unicode): The username for the new account. password (unicode): The user's password. email (unicode): The email address associated with the account. Returns: unicode: an activation key for the account. Raises: errors.AccountUserAlreadyExists errors.AccountUsernameInvalid errors.AccountEmailInvalid errors.AccountPasswordInvalid errors.UserAPIInternalError: the operation failed due to an unexpected error. """ # Check if ALLOW_PUBLIC_ACCOUNT_CREATION flag turned off to restrict user account creation if not configuration_helpers.get_value( 'ALLOW_PUBLIC_ACCOUNT_CREATION', settings.FEATURES.get('ALLOW_PUBLIC_ACCOUNT_CREATION', True)): return HttpResponseForbidden(_("Account creation not allowed.")) if waffle().is_enabled(PREVENT_AUTH_USER_WRITES): raise errors.UserAPIInternalError(SYSTEM_MAINTENANCE_MSG) # Validate the username, password, and email # This will raise an exception if any of these are not in a valid format. _validate_username(username) _validate_password(password, username) _validate_email(email) # Create the user account, setting them to "inactive" until they activate their account. user = User(username=username, email=email, is_active=False) user.set_password(password) try: user.save() except IntegrityError: raise errors.AccountUserAlreadyExists # Create a registration to track the activation process # This implicitly saves the registration. registration = Registration() registration.register(user) # Create an empty user profile with default values UserProfile(user=user).save() # Return the activation key, which the caller should send to the user return registration.activation_key
def create_user(self, uname, name, password=None): """ Creates a user (both SSL and regular)""" if not uname: return _('Must provide username') if not name: return _('Must provide full name') email_domain = getattr(settings, 'SSL_AUTH_EMAIL_DOMAIN', 'MIT.EDU') msg = u'' if settings.FEATURES['AUTH_USE_CERTIFICATES']: if not '@' in uname: email = '{0}@{1}'.format(uname, email_domain) else: email = uname if not email.endswith('@{0}'.format(email_domain)): msg += u'{0} @{1}'.format(_('email must end in'), email_domain) return msg mit_domain = 'ssl:MIT' if ExternalAuthMap.objects.filter(external_id=email, external_domain=mit_domain): msg += _('Failed - email {0} already exists as ' 'external_id').format(email) return msg new_password = generate_password() else: if not password: return _('Password must be supplied if not using certificates') email = uname if not '@' in email: msg += _('email address required (not username)') return msg new_password = password user = User(username=uname, email=email, is_active=True) user.set_password(new_password) try: user.save() except IntegrityError: msg += _('Oops, failed to create user {0}, ' 'IntegrityError').format(user) return msg reg = Registration() reg.register(user) profile = UserProfile(user=user) profile.name = name profile.save() if settings.FEATURES['AUTH_USE_CERTIFICATES']: credential_string = getattr( settings, 'SSL_AUTH_DN_FORMAT_STRING', '/C=US/ST=Massachusetts/O=Massachusetts Institute of Technology/OU=Client CA v1/CN={0}/emailAddress={1}' ) credentials = credential_string.format(name, email) eamap = ExternalAuthMap( external_id=email, external_email=email, external_domain=mit_domain, external_name=name, internal_password=new_password, external_credentials=json.dumps(credentials), ) eamap.user = user eamap.dtsignup = timezone.now() eamap.save() msg += _('User {0} created successfully!').format(user) return msg
def handle(self, *args, **options): while True: uname = raw_input('username: '******'Create MIT ExternalAuth? [n] ').lower() == 'y': email = '*****@*****.**' % uname if not email.endswith('@MIT.EDU'): print "Failed - email must be @MIT.EDU" sys.exit(-1) mit_domain = 'ssl:MIT' if ExternalAuthMap.objects.filter(external_id=email, external_domain=mit_domain): print "Failed - email %s already exists as external_id" % email sys.exit(-1) make_eamap = True password = GenPasswd(12) # get name from kerberos try: kname = os.popen("finger %s | grep 'name:'" % email).read().strip().split('name: ')[1].strip() except: kname = '' name = raw_input('Full name: [%s] ' % kname).strip() if name == '': name = kname print "name = %s" % name else: while True: password = getpass() password2 = getpass() if password == password2: break print "Oops, passwords do not match, please retry" while True: email = raw_input('email: ') if email_exists_or_retired(email): print "email %s already taken" % email else: break name = raw_input('Full name: ') user = User(username=uname, email=email, is_active=True) user.set_password(password) try: user.save() except IntegrityError: print "Oops, failed to create user %s, IntegrityError" % user raise r = Registration() r.register(user) up = UserProfile(user=user) up.name = name up.save() if make_eamap: credentials = "/C=US/ST=Massachusetts/O=Massachusetts Institute of Technology/OU=Client CA v1/CN=%s/emailAddress=%s" % (name, email) eamap = ExternalAuthMap( external_id=email, external_email=email, external_domain=mit_domain, external_name=name, internal_password=password, external_credentials=json.dumps(credentials), ) eamap.user = user eamap.dtsignup = datetime.datetime.now(UTC) eamap.save() print "User %s created successfully!" % user if not raw_input('Add user %s to any groups? [n] ' % user).lower() == 'y': sys.exit(0) print "Here are the groups available:" groups = [str(g.name) for g in Group.objects.all()] print groups completer = MyCompleter(groups) readline.set_completer(completer.complete) readline.parse_and_bind('tab: complete') while True: gname = raw_input("Add group (tab to autocomplete, empty line to end): ") if not gname: break if gname not in groups: print "Unknown group %s" % gname continue g = Group.objects.get(name=gname) user.groups.add(g) print "Added %s to group %s" % (user, g) print "Done!"
def _do_create_account_custom(form, custom_form=None): """ Given cleaned post variables, create the User and UserProfile objects, as well as the registration for this user. Returns a tuple (User, UserProfile, Registration). Note: this function is also used for creating test users. """ errors = {} errors.update(form.errors) if custom_form: errors.update(custom_form.errors) if errors: raise ValidationError(errors) user = User(username=form.cleaned_data["username"], email=form.cleaned_data["email"], is_active=False) user.set_password(form.cleaned_data["password"]) registration = Registration() # TODO: Rearrange so that if part of the process fails, the whole process fails. # Right now, we can have e.g. no registration e-mail sent out and a zombie account try: with transaction.atomic(): user.save() custom_model = custom_form.save(user=user, commit=True) # Fix: recall user.save to avoid transaction management related exception, if we call user.save under atomic block # (in custom_from.save )a random transaction exception generated if custom_model.organization: custom_model.organization.save() user.save() except IntegrityError: # Figure out the cause of the integrity error if len(User.objects.filter(username=user.username)) > 0: raise AccountValidationError(_( "An account with the Public Username '{username}' already exists." ).format(username=user.username), field="username") elif len(User.objects.filter(email=user.email)) > 0: raise AccountValidationError(_( "An account with the Email '{email}' already exists.").format( email=user.email), field="email") else: raise # add this account creation to password history # NOTE, this will be a NOP unless the feature has been turned on in configuration password_history_entry = PasswordHistory() password_history_entry.create(user) registration.register(user) profile_fields = [ "name", "level_of_education", "gender", "mailing_address", "city", "country", "goals", "year_of_birth" ] profile = UserProfile( user=user, **{key: form.cleaned_data.get(key) for key in profile_fields}) extended_profile = form.cleaned_extended_profile if extended_profile: profile.meta = json.dumps(extended_profile) try: profile.save() except Exception: # pylint: disable=broad-except log.exception( "UserProfile creation failed for user {id}.".format(id=user.id)) raise return (user, profile, registration)
def _create_sample_data(self): """ Creates the users and register them. """ for __ in range(3): Registration().register(UserFactory.create())
def create_account(username, password, email): """Create a new user account. This will implicitly create an empty profile for the user. WARNING: This function does NOT yet implement all the features in `student/views.py`. Until it does, please use this method ONLY for tests of the account API, not in production code. In particular, these are currently missing: * 3rd party auth * External auth (shibboleth) * Complex password policies (ENFORCE_PASSWORD_POLICY) In addition, we assume that some functionality is handled at higher layers: * Analytics events * Activation email * Terms of service / honor code checking * Recording demographic info (use profile API) * Auto-enrollment in courses (if invited via instructor dash) Args: username (unicode): The username for the new account. password (unicode): The user's password. email (unicode): The email address associated with the account. Returns: unicode: an activation key for the account. Raises: AccountUserAlreadyExists AccountUsernameInvalid AccountEmailInvalid AccountPasswordInvalid UserAPIInternalError: the operation failed due to an unexpected error. """ # Validate the username, password, and email # This will raise an exception if any of these are not in a valid format. _validate_username(username) _validate_password(password, username) _validate_email(email) # Create the user account, setting them to "inactive" until they activate their account. user = User(username=username, email=email, is_active=False) user.set_password(password) try: user.save() except IntegrityError: raise AccountUserAlreadyExists # Create a registration to track the activation process # This implicitly saves the registration. registration = Registration() registration.register(user) # Create an empty user profile with default values UserProfile(user=user).save() # Return the activation key, which the caller should send to the user return registration.activation_key
def create_user(self, uname, name, is_tempuser, password='******', request=None): """ Creates a user (both SSL and regular)""" if not uname: return _('Must provide username') if not name: return _('Must provide full name') msg = u'' if '@' not in uname: msg += _('Email address must contain @') return msg elif not password: msg += _('Password must be supplied if not using certificates') return msg email = uname new_password = password try: from django.db import transaction with transaction.atomic(): user = User(username=uname, email=email, is_active=True) user.set_password(new_password) user.save() except IntegrityError: msg += _('Oops, failed to create user {user}, {error}').format( user=uname, error="{} already exist.".format(email)) return msg reg = Registration() reg.register(user) profile = UserProfile(user=user) profile.name = name profile.save() mosouser = MosoUser(user=user, creted_by=request.user) mosouser.save() msg += _('User {user} created successfully!').format(user=user) if is_tempuser: try: task_result = deactivate_task(user.id) if task_result: msg += "<br> Configure Deactivate Task successfully!" print("*" * 50) print("Configure Deactivate Task successfully!") except: msg += "<br> Failed to Configure Deactivate Task!" print("Failed to Configure Deactivate Task!") else: msg += "<br> Failed to Configure Deactivate Task!" return msg