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 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_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 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 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 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!"
js['value'] = _("An account with the Public Username '{username}' already exists.").format( username=post_vars['username']) 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 '{email}' already exists.").format(email=post_vars['email']) 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 {id}.".format(id=user.id))
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 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 += _(u'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 += _( u'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 += _(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() 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 += _(u'User {user} created successfully!').format(user=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 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, 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