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 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 user_submit(request): if not request.user.is_authenticated: raise Http404 try: if request.POST.get('id'): profile=UserProfile.objects.get(user_id=request.POST['id']) user=User.objects.get(id=request.POST['id']) else: profile=UserProfile() user=User() if request.POST['subscription_status']=='Registered': user.is_active=True else: user.is_active=False user.email=request.POST['email'] user.save() profile.user_id=user.id profile.school_id=request.POST['school_id'] profile.cohort_id=request.POST['cohort_id'] profile.district_id=request.POST['district_id'] profile.subscription_status=request.POST['subscription_status'] profile.save() except Exception as e: db.transaction.rollback() return HttpResponse(json.dumps({'success': False,'error':'%s' % e})) return HttpResponse(json.dumps({'success': True}))
def setUp(self): 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_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.course = CourseFactory.create() self.second_course = CourseFactory.create( number="899" ) self.client = SecureClient() 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_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 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 import_user_submit(request): message={} if request.method == 'POST': f=request.FILES['file'] try: count_success=0 # --- THIS FAILS ON SING COLUMN CVS --- # dialect = csv.Sniffer().sniff(f.read(1024), delimiters=";,") # f.seek(0) # r=csv.reader(f,dialect) r=csv.reader(f,delimiter='\t', quotechar='|', quoting=csv.QUOTE_MINIMAL) rl = [] rl.extend(r) cohort_id=request.POST.get("cohort_id") cohort=Cohort.objects.get(id=cohort_id) if cohort.licences < UserProfile.objects.filter(~Q(subscription_status = "Inactive"),cohort_id=cohort_id).count() + len(rl): raise Exception("Licences limit exceeded") for line in rl: exist=validate_user_cvs_line(line) # if(exist): # raise Exception("An user already exists, or duplicate lines.") email=line[USER_CSV_COL_EMAIL] import random username=random_mark(20) user = User(username=username, email=email, is_active=False) user.set_password(username) user.save() registration = Registration() registration.register(user) profile=UserProfile(user=user) # profile.transaction_id=transaction_id # profile.email=email # profile.username=username profile.cohort_id=cohort_id profile.subscription_status="Imported" profile.save() cea, _ = CourseEnrollmentAllowed.objects.get_or_create(course_id='PCG_Education/PEP101.1/S2016', email=email) cea.is_active = True cea.auto_enroll = True cea.save() count_success=count_success+1 # reg = Registration.objects.get(user=user) # d = {'name': profile.name, 'key': reg.activation_key} # subject = render_to_string('emails/activation_email_subject.txt', d) # subject = ''.join(subject.splitlines()) # message = render_to_string('emails/activation_emailh.txt', d) db.transaction.commit() message={"success": True, "message":"Success! %s users imported." % (count_success), "count_success":count_success, } except Exception as e: db.transaction.rollback() message={'success': False,'error':'Import error: %s. At cvs line: %s, Nobody imported.' % (e,count_success+1)} return HttpResponse(json.dumps(message))
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(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 import_user_submit(request): message = {} if request.method == "POST": f = request.FILES["file"] try: count_success = 0 count_exist = 0 # --- THIS FAILS ON SING COLUMN CVS --- # dialect = csv.Sniffer().sniff(f.read(1024), delimiters=";,") # f.seek(0) # r=csv.reader(f,dialect) r = csv.reader(f, delimiter="\t", quotechar="|", quoting=csv.QUOTE_MINIMAL) rl = [] rl.extend(r) cohort_id = request.POST.get("cohort_id") cohort = Cohort.objects.get(id=cohort_id) if cohort.licences < UserProfile.objects.filter(cohort_id=cohort_id).count() + len(rl): raise Exception("Licences limit exceeded") for line in rl: exist = validate_user_cvs_line(line) # if(exist): # raise Exception("An user already exists, or duplicate lines.") email = line[USER_CVS_COL_EMAIL] import random username = "".join(random.sample("abcdefg&#%^*f1234567890", 20)) user = User(username=username, email=email, is_active=True) user.set_password(username) user.save() registration = Registration() registration.register(user) profile = UserProfile(user=user) # profile.transaction_id=transaction_id # profile.email=email # profile.username=username profile.cohort_id = cohort_id profile.subscription_status = "Imported" profile.save() # reg = Registration.objects.get(user=user) # d = {'name': profile.name, 'key': reg.activation_key} # subject = render_to_string('emails/activation_email_subject.txt', d) # subject = ''.join(subject.splitlines()) # message = render_to_string('emails/activation_email.txt', d) db.transaction.commit() message = { "success": True, "message": "Success! %s users imported." % (count_success), "count_exist": count_exist, "count_success": count_success, } except Exception as e: db.transaction.rollback() message = { "success": False, "error": "Import error: %s. At cvs line: %s, Nobody imported." % (e, count_success + 1), } return HttpResponse(json.dumps(message))
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 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) 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 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 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 new_user_social(request): if not request.user.is_authenticated(): return HttpResponseRedirect('signin') try: userprofile=UserProfile(user=request.user) userprofile.save() except: return JsonResponse({"error": _("malformed JSON")}, 400) return HttpResponseRedirect('howitworks')
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 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): 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 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): """ 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 self.client = Client() cache.clear() self.session_url = '/api/server/sessions'
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 create_user_from_oauth(strategy, details, user, is_new, *args, **kwargs): if is_new: profile = UserProfile(user=user) profile.name = details.get('fullname') try: profile.save() except Exception: log.error("UserProfile creation failed for user {id}.".format(id=user.id)) raise ceas = CourseEnrollmentAllowed.objects.filter(email=user.email) for cea in ceas: if cea.auto_enroll: CourseEnrollment.enroll(user, cea.course_id) create_comments_service_user(user)
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_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
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 {id}.".format(id=user.id)) return (user, profile, registration) @ensure_csrf_cookie def create_account(request, post_override=None): ''' JSON call to create new edX account. Used by form in signup_modal.html, which is included into navigation.html ''' js = {'success': False} post_vars = post_override if post_override else request.POST
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_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 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)): # Translators: Domain is an email domain, such as "@gmail.com" msg += _('Email address must end in {domain}').format(domain="@{0}".format(email_domain)) return msg mit_domain = 'ssl:MIT' if ExternalAuthMap.objects.filter(external_id=email, external_domain=mit_domain): msg += _('Failed - email {email_addr} already exists as {external_id}').format( email_addr=email, external_id="external_id" ) 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 {user}, {error}').format( user=user, error="IntegrityError" ) 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 {user} created successfully!').format(user=user) return msg
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 _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 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 User.objects.filter(email=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 not gname 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 create_unknown_user(request, ms, data): '''Create the sso user who\'s not exists in pepper''' try: attribute_setting = ms.get('attributes') # Parse to mapped attribute parsed_data = {} for attr in attribute_setting: mapped_name = attr['map'] if 'map' in attr else attr['name'] if attr['name']: parsed_data[mapped_name] = data.get(attr['name']) print attribute_setting print data print parsed_data # Generate username if not provided if not parsed_data.get('username'): username = random_mark(20) else: username = parsed_data['username'] # Email must be profided email = parsed_data['email'] user = User(username=username, email=email, is_active=False) user.set_password(username) # Set password the same with username user.save() registration = Registration() registration.register(user) profile = UserProfile(user=user) profile.subscription_status = "Imported" profile.sso_type = ms.get('sso_type') profile.sso_idp = ms.get('sso_name') # Save mapped attributes for k, v in parsed_data.items(): if k == 'first_name': user.first_name = parsed_data['first_name'] elif k == 'last_name': user.last_name = parsed_data['last_name'] elif k == 'sso_user_id': profile.sso_user_id = parsed_data['sso_user_id'] elif k == 'district': profile.district = District.object.get(name=parsed_data['district']) elif k == 'school': profile.school = School.object.get(name=parsed_data['school']) elif k == 'grade_level': ids = GradeLevel.object.filter(name__in=parsed_data['grade_level'].split(',')).values_list('id', flat=True) profile.grade_level = ','.join(ids) elif k == 'major_subject_area': ids = SubjectArea.object.filter(name__in=parsed_data['major_subject_area'].split(',')).values_list('id', flat=True) profile.major_subject_area = ','.join(ids) elif k == 'years_in_education': profile.years_in_education = YearsInEducation.object.get(name=parsed_data['years_in_education']) elif k == 'percent_lunch': profile.percent_lunch = Enum.object.get(name='percent_lunch', content=parsed_data['percent_lunch']) elif k == 'percent_iep': profile.percent_iep = Enum.object.get(name='percent_iep', content=parsed_data['percent_iep']) elif k == 'percent_eng_learner': profile.percent_eng_learner = Enum.object.get(name='percent_eng_learner', content=parsed_data['percent_eng_learner']) user.save() profile.save() cea, _ = CourseEnrollmentAllowed.objects.get_or_create(course_id='PCG_Education/PEP101.1/S2016', email=email) cea.is_active = True cea.auto_enroll = True cea.save() return https_redirect(request, reverse('register_sso_user', args=[registration.activation_key])) except Exception as e: raise e db.transaction.rollback() log.error("error: failed to create SSO user: %s" % e)
def register_institute(request, post_override=None): """ JSON call to create new institute. """ js = {'success': False} post_vars = post_override if post_override else request.POST extra_fields = getattr(settings, 'REGISTRATION_EXTRA_FIELDS', {}) for a in ['name', 'state', 'city']: if a not in post_vars: js['value'] = _("Error (401 {field}). E-mail us.").format(field=a) js['field'] = a return JsonResponse(js, status=400) required_post_vars = ['name', 'state', 'city', 'pincode', 'address', 'website', 'headName', 'headEmail', 'headMobile', 'rccName', 'rccEmail', 'rccMobile', 'studentIdentity'] for field_name in required_post_vars: if field_name in ('state', 'city'): min_length = 1 else: min_length = 2 if len(post_vars[field_name]) < min_length: error_str = { 'name': _('Name must be minimum of two characters long'), 'state': _('A state is required'), 'address': _('Your address is required'), 'city': _('A city is required'), 'pincode' : _('Your Pincode is required'), 'website' : _('Your website is required'), 'headName' : _('Head Name must be minimum of two characters long'), 'headEmail' : _('A properly formatted e-mail is required'), 'headMobile' : _('Head Mobile must be of 10 digits'), 'rccName' : _('RCC Name must be minimum of two characters long'), 'rccEmail' : _('A properly formatted e-mail is required'), 'rccMobile' : _('RCC Mobile must be of 10 digits'), 'honor_code': _('Agreeing to the Honor Code is required'), 'terms_of_service': _('Accepting Terms of Service is required') } js['value'] = error_str[field_name] js['field'] = field_name return JsonResponse(js, status=400) try: validate_email(post_vars['headEmail']) except ValidationError: js['value'] = _("Valid e-mail is required.").format(field=a) js['field'] = 'email' return JsonResponse(js, status=400) try: validate_email(post_vars['rccEmail']) except ValidationError: js['value'] = _("Valid e-mail is required.").format(field=a) js['field'] = 'email' return JsonResponse(js, status=400) if extra_fields.get('honor_code', 'required') == 'required' and \ post_vars.get('honor_code', 'false') != u'true': js['value'] = _("To enroll, you must follow the honor code.").format(field=a) js['field'] = 'honor_code' return JsonResponse(js, status=400) if extra_fields.get('terms_of_service', 'required') == 'required' and \ post_vars.get('terms_of_service', 'false') != u'true': js['value'] = _("To enroll, you must accept terms of service.").format(field=a) js['field'] = 'terms_of_service' return JsonResponse(js, status=400) status=Institute_Status.objects.filter(name="Pending")[0].id institute = Institute_Registration( name=post_vars['name'], state_id=post_vars['state'], city_id=post_vars['city'], pincode=post_vars['pincode'], status_id=status, is_parent=False, address=post_vars['address'], website=post_vars['website']) if post_vars['headEmail'] == post_vars['rccEmail']: js['value'] = _("Please provide different emails for Head and Coordinator").format(email=post_vars['headEmail']) js['field'] = 'email' return JsonResponse(js,status=400) if len(User.objects.filter(email=str(post_vars['headEmail']))) > 0: js = {'success': False} js['value'] = _("An account with the Email '{email}' already exists.").format(email=post_vars['headEmail']) js['field'] = 'email' return JsonResponse(js,status=400) if len(User.objects.filter(email=str(post_vars['rccEmail']))) > 0: js = {'success': False} js['value'] = _("An account with the Email '{email}' already exists.").format(email=post_vars['rccEmail']) js['field'] = 'email' return JsonResponse(js,status=400) try: institute.save() except IntegrityError as e: js = {'success': False} if len(Institute_Registration.objects.filter(name=post_vars['name'])) > 0: js['value'] = _("An Institute with the name '{name}' already exists.").format(name=post_vars['name']) js['field'] = 'name' return JsonResponse(js,status=400) insti_id= institute.id accreditation = request.POST.getlist('accreditation') for index in accreditation: acc = Institute_Accreditation(accreditation_id=index , institute_id=insti_id) acc.save() headUsername = post_vars['headEmail'].split('@') headUsername = GenerateUsername(headUsername[0]) headPass = uuid.uuid4().hex[0:10] user = User(username=headUsername, email=post_vars['headEmail'], is_active=False) user.set_password(headPass) try: user.save() head_user_object = user except IntegrityError as e: js = {'success': False} # Figure out the cause of the integrity error if len(User.objects.filter(email=post_vars['headEmail'])) > 0: js['value'] = _("An account with the Email '{email}' already exists.").format(email=post_vars['headEmail']) js['field'] = 'email' return JsonResponse(js,status=400) profile = UserProfile(user=user) profile.name = post_vars['headName'] profile.year_of_birth = None person = Person(user=user) person.mobile = post_vars.get('headMobile') person.save() try: profile.save() except Exception: log.exception("UserProfile creation failed for user {id}.".format(id=user.id)) head_role_id = Role.objects.filter(name="Institute Head")[0].id designation = Institute_Designation(user=user, institute_id=insti_id, role_id=head_role_id, is_approved=False) designation.save() rccUsername = post_vars['rccEmail'].split('@') rccUsername = GenerateUsername(rccUsername[0]) rccPass = uuid.uuid4().hex[0:10] user = User(username=rccUsername, email=post_vars['rccEmail'], is_active=False) user.set_password(rccPass) try: user.save() rcc_user_object = user except IntegrityError as e: js = {'success': False} # Figure out the cause of the integrity error if len(User.objects.filter(email=post_vars['rccEmail'])) > 0: js['value'] = _("An account with the Email '{email}' already exists.").format(email=post_vars['rccEmail']) js['field'] = 'email' return JsonResponse(js,status=400) profile = UserProfile(user=user) profile.name = post_vars['rccName'] profile.year_of_birth = None person = Person(user=user) person.mobile = post_vars.get('rccMobile') person.save() try: profile.save() except Exception: log.exception("UserProfile creation failed for user {id}.".format(id=user.id)) ic_role_id = Role.objects.filter(name="Institute Coordinator")[0].id designation = Institute_Designation(user=user, institute_id=insti_id, role_id=ic_role_id, is_approved=False) designation.save() #identity_name = post_vars.get('studentIdentity') # student_identity = Identity(name=identity_name) # student_identity.save() # institute_id = Institute_Registration.objects.filter(name=post_vars.get('name'))[0].id #identity_id = Identity.objects.filter(name=identity_name)[0].id #institute_identity = Institute_Identity(institute_id=institute_id, identity_id=identity_id) #institute_identity.save() ''' context = {'name': "test",} # composes thank you email subject = render_to_string('emails/thankyou_email_subject.txt',context) # Email subject *must not* contain newlines subject = ''.join(subject.splitlines()) message = render_to_string('emails/thankyou_email_body.txt',context) # don't send email if we are doing load testing or random user generation for some reason if not (settings.FEATURES.get('AUTOMATIC_AUTH_FOR_TESTING')): from_address = MicrositeConfiguration.get_microsite_configuration_value( 'email_from_address', settings.DEFAULT_FROM_EMAIL ) try: if settings.FEATURES.get('REROUTE_ACTIVATION_EMAIL'): dest_addr = settings.FEATURES['REROUTE_ACTIVATION_EMAIL'] message = ("Thank you for mail %s (%s):\n" % (head_user_object, head_user_object.email) + '-' * 80 + '\n\n' + message) send_mail(subject, message, from_address, [dest_addr], fail_silently=False) else: _res = head_user_object.email_user(subject, message, from_address) _res1 = rcc_user_object.email_user(subject, message, from_address) except: log.warning('Unable to send thank you email to user', exc_info=True) js['value'] = _('Could not send thank you e-mail.') # What is the correct status code to use here? I think it's 500, because # the problem is on the server's end -- but also, the account was created. # Seems like the core part of the request was successful. return JsonResponse(js, status=500) return JsonResponse({'success': True,})
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 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 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
def import_user_submit(request): # http://www.cnblogs.com/yijun-boxing/archive/2011/04/18/2020155.html CONTRACT_CVS_COL_CONTRACT_ID=0 CONTRACT_CVS_COL_DISTRICT_ID=1 CONTRACT_CVS_COL_EMAIL=2 CONTRACT_CVS_COL_USERNAME=3 CONTRACT_CVS_COUNT_COL=4 message={} n=0 if request.method == 'POST': f=request.FILES['file'] dialect = csv.Sniffer().sniff(f.read(1024), delimiters=";,") f.seek(0) r=csv.reader(f,dialect) try: for i,line in enumerate(r): n=n+1 contract_id=line[CONTRACT_CVS_COL_CONTRACT_ID] district_id=line[CONTRACT_CVS_COL_DISTRICT_ID] email=line[CONTRACT_CVS_COL_EMAIL] username=line[CONTRACT_CVS_COL_USERNAME] for value in line: if len(value.strip())==0: raise Exception("Catch csv line with empty fields line") if len(line) != CONTRACT_CVS_COUNT_COL: raise Exception("Catch csv line of wrong fields count") user = User(username=username, email=email, is_active=True) user.set_password(username) registration = Registration() try: user.save() except IntegrityError: if len(User.objects.filter(username=username)) > 0: raise Exception("An account with the Public Username '{username}' already exists.".format(username=username)) if len(User.objects.filter(email=email)) > 0: raise Exception("An account with the Email '{email}' already exists.".format(email=email)) registration.register(user) profile=UserProfile(user=user) profile.contract_id=contract_id profile.district_id=district_id profile.email=email profile.username=username profile.save() reg = Registration.objects.get(user=user) d = {'name': profile.name, 'key': reg.activation_key} subject = render_to_string('emails/activation_email_subject.txt', d) subject = ''.join(subject.splitlines()) message = render_to_string('emails/activation_email.txt', d) try: _res = user.email_user(subject, message, settings.DEFAULT_FROM_EMAIL) except: log.warning('Unable to send reactivation email', exc_info=True) return HttpResponse(json.dumps({'success': False, 'error': _('Unable to send reactivation email')})) message={'success': True, "message":"Success! %s users imported." % (n)} except Exception as e: transaction.rollback() message={'success': False,'message':'Import error: %s, At cvs line: %s' % (e,n)} # title = forms.CharField(max_length=50) # file = forms.FileField() return HttpResponse(json.dumps(message))