def setUp(self): super(OrganizationsApiTests, self).setUp() self.test_server_prefix = 'https://testserver' self.base_organizations_uri = '/api/server/organizations/' self.base_users_uri = '/api/server/users' self.base_groups_uri = '/api/server/groups' self.test_organization_name = str(uuid.uuid4()) self.test_organization_display_name = 'Test Org' self.test_organization_contact_name = 'John Org' self.test_organization_contact_email = '*****@*****.**' self.test_organization_contact_phone = '+1 332 232 24234' self.test_organization_logo_url = 'org_logo.jpg' self.test_user_email = str(uuid.uuid4()) self.test_user_username = str(uuid.uuid4()) self.test_user = User.objects.create(email=self.test_user_email, username=self.test_user_username) profile = UserProfile(user=self.test_user) profile.city = 'Boston' profile.save() self.test_user2 = User.objects.create(email=str(uuid.uuid4()), username=str(uuid.uuid4())) profile2 = UserProfile(user=self.test_user2) profile2.city = 'NYC' profile2.save() self.course = CourseFactory.create() self.second_course = CourseFactory.create(number="899") cache.clear()
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 create_lti_user(lti_user_id, lti_consumer): """ Generate a new user on the edX platform with a random username and password, and associates that account with the LTI identity. """ edx_password = str(uuid.uuid4()) created = False while not created: try: edx_user_id = generate_random_edx_username() edx_email = "{}@{}".format(edx_user_id, settings.LTI_USER_EMAIL_DOMAIN) edx_user = User.objects.create_user( username=edx_user_id, password=edx_password, email=edx_email, ) # A profile is required if PREVENT_CONCURRENT_LOGINS flag is set. # TODO: We could populate user information from the LTI launch here, # but it's not necessary for our current uses. edx_user_profile = UserProfile(user=edx_user) edx_user_profile.save() created = True except IntegrityError: # The random edx_user_id wasn't unique. Since 'created' is still # False, we will retry with a different random ID. pass lti_user = LtiUser(lti_consumer=lti_consumer, lti_user_id=lti_user_id, edx_user=edx_user) lti_user.save() return lti_user
def create_new_user(name=''): """ new user :return: """ def create_(): password = TIANYUYUN_PASSWORD username = gen_union_username() email = '*****@*****.**' % username user = User(username=username, email=email, is_active=True) user.set_password(password) try: user.save() except: return None return user user = create_() if not user: while True: user = create_() if user: break # TODO UserProfile try: from student.models import UserProfile profile_name = name or 'someone' profile = UserProfile(user=user, name='someone') profile.save() except: pass return user
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 make_student(self, block, name, make_state=True, **state): """ Create a student along with submission state. """ answer = {} module = None for key in ('sha1', 'mimetype', 'filename', 'finalized'): if key in state: answer[key] = state.pop(key) score = state.pop('score', None) with transaction.atomic(): user = User(username=name, email='{}@example.com'.format(name)) user.save() profile = UserProfile(user=user, name=name) profile.save() if make_state: module = StudentModule( module_state_key=block.location, student=user, course_id=self.course_id, state=json.dumps(state)) module.save() anonymous_id = anonymous_id_for_user(user, self.course_id) item = StudentItem( student_id=anonymous_id, course_id=self.course_id, item_id=block.block_id, item_type='sga') item.save() if answer: student_id = block.get_student_item_dict(anonymous_id) submission = submissions_api.create_submission(student_id, answer) if score is not None: submissions_api.set_score( submission['uuid'], score, block.max_score()) else: submission = None self.addCleanup(item.delete) self.addCleanup(profile.delete) self.addCleanup(user.delete) if make_state: self.addCleanup(module.delete) return { 'module': module, 'item': item, 'submission': submission } return { 'item': item, 'submission': submission }
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 new_user_social(request): if not request.user.is_authenticated(): return HttpResponseRedirect('signin') try: userprofile = UserProfile(user=request.user) userprofile.save() except: pass return index(request)
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 setUp(self): # pylint: disable=E7601 """ Create one user and save it to the database """ self.user = UserFactory.build(username='******', email='*****@*****.**') self.user.set_password('test_password') self.user.save() profile = UserProfile(user=self.user) profile.city = 'Boston' profile.save() # Create the test client cache.clear() self.session_url = '/api/server/sessions'
def setUp(self): self.reset_setting_cache_variables() super(SelfPacedDateOverrideTest, self).setUp() SelfPacedConfiguration(enabled=True).save() self.non_staff_user, __ = self.create_non_staff_user() # create a UserProfile for user so user doesn't look like sneak_peek user nonstaff_user_profile = UserProfile(user=self.non_staff_user) nonstaff_user_profile.save() self.now = datetime.datetime.now(pytz.UTC).replace(microsecond=0) self.future = self.now + datetime.timedelta(days=30)
def make_student_module(self, block, name, **state): user = User(username=name) user.save() profile = UserProfile(user=user, name=name) profile.save() module = StudentModule( module_state_key=block.location, student=user, course_id=self.course_id, state=json.dumps(state)) module.save() self.addCleanup(profile.delete) self.addCleanup(module.delete) self.addCleanup(user.delete) return module
def make_student(self, block, name, **state): answer = {} for key in ('sha1', 'mimetype', 'filename'): if key in state: answer[key] = state.pop(key) score = state.pop('score', None) user = User(username=name) user.save() profile = UserProfile(user=user, name=name) profile.save() module = StudentModule( module_state_key=block.location, student=user, course_id=self.course_id, state=json.dumps(state)) module.save() anonymous_id = anonymous_id_for_user(user, self.course_id) item = StudentItem( student_id=anonymous_id, course_id=self.course_id, item_id=block.block_id, item_type='sga') item.save() if answer: student_id = block.student_submission_id(anonymous_id) submission = submissions_api.create_submission(student_id, answer) if score is not None: submissions_api.set_score( submission['uuid'], score, block.max_score()) else: submission = None self.addCleanup(item.delete) self.addCleanup(profile.delete) self.addCleanup(module.delete) self.addCleanup(user.delete) return { 'module': module, 'item': item, 'submission': submission, }
def cas_login(request, next_page=None, required=False): """ Uses django_cas for authentication. CAS is a common authentcation method pioneered by Yale. See http://en.wikipedia.org/wiki/Central_Authentication_Service Does normal CAS login then generates user_profile if nonexistent, and if login was successful. We assume that user details are maintained by the central service, and thus an empty user profile is appropriate. """ ret = django_cas_login(request, next_page, required) if request.user.is_authenticated(): user = request.user if not UserProfile.objects.filter(user=user): user_profile = UserProfile(name=user.username, user=user) user_profile.save() return ret
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 update_profile_info(request): """ """ # Get the user data = request.POST.copy() user = request.user post_registration_fields = [('gender', str), ('country', str), ('year_of_birth', int)] try: user_profile = UserProfile.objects.get(user=user) user_has_profile = True except UserProfile.DoesNotExist: # Handle when no profile for the user, create a new one user_profile = UserProfile(user=user) user_has_profile = False for field in post_registration_fields: field_name = field[0] field_type = field[1] value = field_type(data.get(field_name)) if value: setattr(user_profile, field_name, value) try: user_profile.save(update_fields=list( field[0] for field in post_registration_fields ) if user_has_profile else None) return JsonResponse({"is_success": True}, status=200) except (DatabaseError, ValidationError, TypeError) as e: log.error('Failed to save post auth data for {user}, exception is {e}'. format(user=user.username, e=e)) return JsonResponse({"is_success": False}, status=400)
def import_user(u): user_info = u['u'] up_info = u['up'] # HACK to handle dates user_info['last_login'] = dateutil.parser.parse(user_info['last_login']) user_info['date_joined'] = dateutil.parser.parse(user_info['date_joined']) user_keys = ['id', 'username', 'email', 'password', 'is_staff', 'is_active', 'is_superuser', 'last_login', 'date_joined', 'password'] up_keys = ['language', 'location', 'meta', 'name', 'id', 'user_id'] u = User() for key in user_keys: u.__setattr__(key, user_info[key]) u.save() up = UserProfile() up.user = u for key in up_keys: up.__setattr__(key, up_info[key]) up.save()
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 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
def _get_or_create_oauth_user(strategy, detail, request=None, mobile_client=False, created_on='web'): ''' strategy -- strategy obj detail -- oauth登录拿到token时的response ''' backend = strategy.backend _created = False uid = get_uid(strategy, detail) # weibo新接口uid改名叫做id if not uid: uid = detail.get('id') # weixin if backend.name in ('weixin', 'weixinapp'): weixin_unionid = detail.get('unionid') if weixin_unionid: weixin_users = UserSocialAuth.objects.filter( weixin_unionid=weixin_unionid).order_by('id') weixin_users_count = weixin_users.count() # 微信只有一个UserSocialAuth时,使用这个 if weixin_users_count == 1: user = weixin_users[0].user user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) return (user, False) elif weixin_users_count > 1: # 有web则永远返回第一个web用户 for each in weixin_users: if each.created_on and each.created_on.startswith('web'): user = each.user user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) return (user, False) # 否则返回mobile用户 for each in weixin_users: if each.created_on and each.created_on.startswith( 'mobile'): user = each.user user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) return (user, False) # 否则返回weixin app用户(微信服务号活动生成) for each in weixin_users: if each.created_on and each.created_on.startswith('app'): user = each.user user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) return (user, False) # 没有第四种逻辑, 但是还是加上吧 user = weixin_users[0].user user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) return (user, False) if backend.name == 'chinamobile': extra_data = backend.extra_data(None, uid, detail, {}) phone_number = extra_data.get('phone_number', None) try: user_profile = UserProfile.objects.get(phone_number=phone_number) user = user_profile.user user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) return (user, False) except: pass result = social_user(strategy, uid) # 已有账户,直接登录 if result['user']: user = result['user'] # 否则创建用户,之后登录 else: user = User() user.username = str(uuid.uuid4()).replace('-', '')[:20] user.email = None # oauth的自动激活 user.is_active = True user.set_unusable_password() user.save() extra_data = backend.extra_data(user, uid, detail, {}) profile = UserProfile(user=user) nickname = get_validate_nickname(extra_data['username']) oauth_nickname = nickname # 重名加后缀,最多尝试10次 MAX_TRY_TIMES = 10 while MAX_TRY_TIMES: try: UserProfile.objects.get(nickname=nickname) suffix = str(uuid.uuid4().int)[:6] nickname = '{}{}'.format(oauth_nickname, suffix) MAX_TRY_TIMES = MAX_TRY_TIMES - 1 except UserProfile.DoesNotExist: break profile.phone_number = extra_data.get('phone_number', None) profile.nickname = nickname profile.unique_code = profile.get_unique_code() if request: profile.set_register_extra(request=request, cover_data={'channel': backend.name}) if extra_data.get('profile_image_url'): profile.avatar = extra_data['profile_image_url'] if extra_data.get('gender'): profile.gender = extra_data['gender'] if extra_data.get('year_of_birth'): profile.year_of_birth = extra_data['year_of_birth'] if backend.name == 'chinamobile': profile.register_type = 'migu' profile.register_auto = 1 profile.save() # TODO: AuthAlreadyAssociated # 此oauth账号之前已经绑定了学堂在线的账号 new_associate_user(strategy, uid, user, detail, created_on=created_on) _created = True # Track this user register event in oauth if not mobile_client: # do not track api client log 2015.5.26 event_type = 'weixinapp.user.register_success' if created_on == 'weixinapp' else 'oauth.user.register_success' track_log(request, event_type, { 'success': True, 'uid': user.id, 'provider': backend.name, }) user.backend = "%s.%s" % (backend.__module__, backend.__class__.__name__) return (user, _created)
def setUp(self): CourseFactory.create(org='TESTX', number='1', display_name='TEST1', start=datetime.datetime(2010, 5, 12, 2, 42, tzinfo=utc), end=datetime.datetime(2011, 5, 12, 2, 42, tzinfo=utc)) CourseFactory.create(org='TESTX', number='2', display_name='TEST2', start=datetime.datetime(2010, 5, 12, 2, 42, tzinfo=utc), end=datetime.datetime(2011, 5, 12, 2, 42, tzinfo=utc)) CourseFactory.create(org='TESTX', number='3', display_name='TEST3', start=datetime.datetime(2010, 5, 12, 2, 42, tzinfo=utc), end=datetime.datetime(2011, 5, 12, 2, 42, tzinfo=utc)) self.fred = fred = User(username='******', email='*****@*****.**') fred.save() UserProfile(user=fred, name='Fred Flintstone').save() LinkedIn(user=fred, has_linkedin_account=True).save() self.barney = barney = User(username='******', email='*****@*****.**') barney.save() LinkedIn(user=barney, has_linkedin_account=True).save() UserProfile(user=barney, name='Barney Rubble').save() self.adam = adam = User(username='******', email='*****@*****.**') adam.save() LinkedIn(user=adam, has_linkedin_account=True).save() UserProfile(user=adam, name='Adam (חיים פּלי)').save() self.cert1 = cert1 = GeneratedCertificate( status='downloadable', user=fred, course_id='TESTX/1/TEST1', name='TestX/Intro101', download_url='http://test.foo/test') cert1.save() cert2 = GeneratedCertificate(status='downloadable', user=fred, course_id='TESTX/2/TEST2') cert2.save() cert3 = GeneratedCertificate(status='downloadable', user=barney, course_id='TESTX/3/TEST3') cert3.save() cert5 = GeneratedCertificate(status='downloadable', user=adam, course_id='TESTX/3/TEST3') cert5.save()
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 _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_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 callback(request, next_page=None, required=False): try: if request.method != 'POST': raise PermissionDenied('0005') try: # Verifies signature and expiry time verified_jwt = jwt.decode( request.POST['assertion'], key=settings.AAF_SECRET, # audience=settings.AAF_AUDIENCE, # issuer=settings.AAF_ISSUER) ) except jwt.ExpiredSignature: # Security cookie has expired raise PermissionDenied('0001') # for PyJWT > 0.4.1: ''' except jwt.InvalidAudience: # Not for this audience raise PermissionDenied('0004') ''' # for older PyJWT: if verified_jwt['aud'] != settings.AAF_AUDIENCE or verified_jwt['iss'] != settings.AAF_ISSUER: raise PermissionDenied('0004') import logging logging.warning(verified_jwt) # Verify that we haven't seen this jti value before (prevents replay # attacks) if 'jti' not in verified_jwt.keys(): raise PermissionDenied('0002') jti = verified_jwt['jti'] if JTILog.objects.filter(jti=jti).exists(): # looks like replay raise PermissionDenied('0003') # add jti to the log jl = JTILog(jti=jti) jl.save() attributes = verified_jwt['https://aaf.edu.au/attributes'] request.session['attributes'] = attributes request.session['jwt'] = verified_jwt request.session['jws'] = request.POST['assertion'] assert 'edupersonprincipalname' in attributes.keys(), 'edupersonprincipalname not in attributes' # If you want to restrict access to your institution, fill in PRINCIPAL_NAME_RE and uncomment # The first group should be the username ''' match = PRINCIPAL_NAME_RE.match(attributes['edupersonprincipalname']) if match is None: # Principal name not in expected format raise PermissionDenied('0006') username = match.groups()[0] ''' username = attributes['edupersonprincipalname'] # Remove this if you have a better/shorter username you'd like to use email = attributes['edupersonprincipalname'] try: user = User.objects.get(username=username) except User.DoesNotExist: user = User.objects.create_user( username=username, email=email, password=None) # non-usable password user.save() UserPreference.set_preference(user, LANGUAGE_KEY, get_language()) # blech - we're caching the user's name both in the Django User object # and the edX UserProfile object, and we don't really want either. # cache some attributes # Django shouldn't touch the database if they haven't changed, so no perf issue if 'givenname' in attributes.keys(): user.first_name = attributes['givenname'] if 'surname' in attributes.keys(): user.last_name = attributes['surname'] # This should only be done at user creation time. We do it here # because we have some old entries in the database that we'd like to # clean up automatically. if 'edupersonprincipalname' in attributes.keys(): user.email = attributes['edupersonprincipalname'] user.save() # Look up the UserProfile and update it try: profile = UserProfile.objects.get(user=user) except UserProfile.DoesNotExist: # create a new one profile = UserProfile(user=user) profile.save() # update the profile's name profile.update_name('%s %s' % (user.first_name, user.last_name)) create_comments_service_user(user) # Temporary workaround: http://stackoverflow.com/a/23771930 user.backend = 'django.contrib.auth.backends.ModelBackend' djauth.login(request, user) # done! if next_page: return redirect(next_page) else: # If we're in lms, we want to go to dashboard. For cms, go to homepage. print 'doing the fallback thing' try: return redirect('dashboard') except NoReverseMatch: return redirect('homepage') except PermissionDenied as e: if 'attributes' in request.session.keys(): del request.session['attributes'] djauth.logout(request) # messages.add_message(request, messages.ERROR, 'Could not log you in (error %s). Please try again.' % e.message) # bounce back to login page # TODO you could bounce to a message page if the messages thing above doesn't integrate nicely return redirect('dashboard') # TODO: probably better to send directly to index, but I can't find it