def forgot_password_email(request): if request.method == 'POST': try: u = User.objects.get(username=request.POST['username']) userProfile = UserProfile.objects.get(user = u) except ObjectDoesNotExist: u = None if u is not None: bum = BaseUserManager() tempPass = bum.make_random_password() u.set_password(tempPass) userProfile.hasTempPassword = True userProfile.save() u.save() subject = 'AC3 Forgotten Password Request' message = 'User: {0}\n You have requested to reset your password\nYour temporary password is: {1}' \ ''.format(u.username, tempPass) EmailMessage(subject, message, to=[u.email]).send(fail_silently=True) messages.add_message(request, messages.SUCCESS, 'An email has been sent!') return HttpResponseRedirect('/ac3app/') else: messages.add_message(request, messages.ERROR, 'The user {0} could not be found' .format(request.POST['username'])) return HttpResponseRedirect('/ac3app/')
def add_cands(request): if request.method != ATTR.POST: raise Http404() next_page = request.POST.get(ATTR.NEXT, '/') cand_csv_file = request.FILES.get(ATTR.CAND_CSV, None) if not cand_csv_file.name.endswith(ATTR.CSV_ENDING): messages.error(request, "Please input a csv file!") decoded_cand_csv_file = cand_csv_file.read().decode( ATTR.UTF8SIG).splitlines() cand_csv = csv.DictReader(decoded_cand_csv_file) candidate_group = Group.objects.get(name=ATTR.CANDIDATE) for row in cand_csv: try: candidatedto = CandidateDTO(row) except AssertionError as e: messages.error(request, "Invalid candidate information: " + str(e)) return redirect(next_page) password = BaseUserManager.make_random_password( None, length=DEFAULT_RANDOM_PASSWORD_LENGTH) new_cand = User.objects.create_user( candidatedto.username, email=candidatedto.email, password=password, ) new_cand.first_name = candidatedto.first_name new_cand.last_name = candidatedto.last_name new_cand.save() candidate_group.user_set.add(new_cand) subject = "[HKN] Candidate account" html_content = render_to_string( "candidate/new_candidate_account_email.html", { "subject": subject, "first_name": candidatedto.first_name, "username": candidatedto.username, "password": password, "website_link": request.build_absolute_uri("/accounts/login/"), "img_link": get_rand_photo(), }) msg = EmailMultiAlternatives(subject, subject, "*****@*****.**", [candidatedto.email]) msg.attach_alternative(html_content, "text/html") msg.send() messages.success(request, "Successfully added candidates!") return redirect(next_page)
def create_user(self, su_id, first_name, last_name, email, phone_number, password=None): """ Creates and saves a User with the given su_id, first_name, last_name, email, phone_number and password. """ if not email and not su_id: #to contact SU students at least student id or email address is required raise ValueError('Users must have an email address or SU ID') user = self.model( su_id=su_id, first_name=first_name, last_name=last_name, phone_number=phone_number, email=self.normalize_email(email), password=BaseUserManager.make_random_password(length=8)) user.set_password(password) user.save(using=self._db) return user
def handle(self, *args, **options): fail_list = [] success_list = [] user_manager = BaseUserManager() data = pd.read_csv(options['csv']) for index, line in data.iterrows(): # pylint: disable=no-member,unused-variable received_offer = line['Invited'] == 'YES' if line["Research Classification"] == "N/A - I do not do research": jacs = "Y0" else: jacs = line["Research Classification"][1:3] applicants_dict = { "application_year": 2018, "fellow": False, "received_offer": received_offer, "forenames": line["First name"], "surname": line["Surname"], "affiliation": line["Home Institution"], "department": line["Department"] if pd.notnull(line["Department"]) else "", "group": line["Group within Department"] if pd.notnull(line["Group within Department"]) else "", "career_stage_when_apply": line["Career stage"][6], "job_title_when_apply": line["Job Title"], "research_area": line["Area of work"], "research_area_code": jacs, "email": line["Email Address"], "phone": line["Telephone number"], "gender": line["Gender"][0] if pd.notnull(line["Gender"]) else 'R', "home_country": "GB", "home_city": "Unknow", "funding": line["Which primary funding body/charity/organisation would you normally turn to if seeking financial support for your research/work"], "funding_notes": line["Which additional funding body/charity/organisation would you probably turn to if seeking financial support for your research/work"] if pd.notnull(line["Which additional funding body/charity/organisation would you probably turn to if seeking financial support for your research/work"]) else "", "claimantship_grant": 3000 if received_offer else 0, "institutional_website": line["Please specify your Institutional webpage"] if pd.notnull(line["Please specify your Institutional webpage"]) else "", "website": line["Please specify your blog"] if pd.notnull(line["Please specify your blog"]) else "", "orcid": line["Please specify your ORCID"] if pd.notnull(line["Please specify your ORCID"]) else "", "google_scholar": line["Please specify your Google Scholar"] if pd.notnull(line["Please specify your Google Scholar"]) else "", "twitter": line["Please specify your Twitter handle"] if pd.notnull(line["Please specify your Twitter handle"]) else "", "screencast_url": line["Application Screencast URL"] if pd.notnull(line["Application Screencast URL"]) else "", "example_of_writing_url": line["Example of writing"] if pd.notnull(line["Example of writing"]) else "", } try: applicant = Claimant(**applicants_dict) applicant.save() success_list.append(index) if received_offer: new_user = User.objects.create_user( username=applicant.slug, email=applicant.email, password=user_manager.make_random_password(), first_name=line["First name"], last_name=line["Surname"] ) applicant.user = new_user applicant.save() except IntegrityError as exception: try: applicant = Claimant.objects.get( email=applicants_dict["email"] ) for key, value in applicants_dict.items(): applicant[key] = value applicant.save() success_list.append(index) if received_offer: new_user = User.objects.create_user( username=applicant.slug, email=applicant.email, password=user_manager.make_random_password(), first_name=line["First name"], last_name=line["Surname"] ) applicant.user = new_user applicant.save() except BaseException as exception: print("Error: {}\n{}\n{}".format(exception, line, 80 * "-")) fail_list.append(index) except BaseException as exception: print("Error: {}\n{}\n{}".format(exception, line, 80 * "-")) fail_list.append(index) print(80 * "-") print("Success: {}".format(success_list)) print("Fail: {}".format(fail_list))
def handle(self, *args, **options): fail_list = [] success_list = [] user_manager = BaseUserManager() data = pd.read_csv(options['csv']) for index, line in data.iterrows(): # pylint: disable=no-member,unused-variable received_offer = line['Invited'] == 'YES' if line["Research Classification"] == "N/A - I do not do research": jacs = "Y0" else: jacs = line["Research Classification"][1:3] applicants_dict = { "application_year": 2018, "fellow": False, "received_offer": received_offer, "forenames": line["First name"], "surname": line["Surname"], "affiliation": line["Home Institution"], "department": line["Department"] if pd.notnull(line["Department"]) else "", "group": line["Group within Department"] if pd.notnull(line["Group within Department"]) else "", "career_stage_when_apply": line["Career stage"][6], "job_title_when_apply": line["Job Title"], "research_area": line["Area of work"], "research_area_code": jacs, "email": line["Email Address"], "phone": line["Telephone number"], "gender": line["Gender"][0] if pd.notnull(line["Gender"]) else 'R', "home_country": "GB", "home_city": "Unknow", "funding": line[ "Which primary funding body/charity/organisation would you normally turn to if seeking financial support for your research/work"], "funding_notes": line[ "Which additional funding body/charity/organisation would you probably turn to if seeking financial support for your research/work"] if pd.notnull(line[ "Which additional funding body/charity/organisation would you probably turn to if seeking financial support for your research/work"] ) else "", "claimantship_grant": 3000 if received_offer else 0, "institutional_website": line["Please specify your Institutional webpage"] if pd.notnull( line["Please specify your Institutional webpage"]) else "", "website": line["Please specify your blog"] if pd.notnull(line["Please specify your blog"]) else "", "orcid": line["Please specify your ORCID"] if pd.notnull(line["Please specify your ORCID"]) else "", "google_scholar": line["Please specify your Google Scholar"] if pd.notnull( line["Please specify your Google Scholar"]) else "", "twitter": line["Please specify your Twitter handle"] if pd.notnull( line["Please specify your Twitter handle"]) else "", "screencast_url": line["Application Screencast URL"] if pd.notnull(line["Application Screencast URL"]) else "", "example_of_writing_url": line["Example of writing"] if pd.notnull(line["Example of writing"]) else "", } try: applicant = Claimant(**applicants_dict) applicant.save() success_list.append(index) if received_offer: new_user = get_user_model().objects.create_user( username=applicant.slug, email=applicant.email, password=user_manager.make_random_password(), first_name=line["First name"], last_name=line["Surname"]) applicant.user = new_user applicant.save() except IntegrityError: try: applicant = Claimant.objects.get( email=applicants_dict["email"]) for key, value in applicants_dict.items(): applicant[key] = value applicant.save() success_list.append(index) if received_offer: new_user = get_user_model().objects.create_user( username=applicant.slug, email=applicant.email, password=user_manager.make_random_password(), first_name=line["First name"], last_name=line["Surname"]) applicant.user = new_user applicant.save() except BaseException as exception: print("Error: {}\n{}\n{}".format(exception, line, 80 * "-")) fail_list.append(index) except BaseException as exception: print("Error: {}\n{}\n{}".format(exception, line, 80 * "-")) fail_list.append(index) print(80 * "-") print("Success: {}".format(success_list)) print("Fail: {}".format(fail_list))
def handle(self, *args, **options): fail_list = [] success_list = [] user_manager = BaseUserManager() data = pd.read_csv(options['csv']) for index, line in data.iterrows(): # pylint: disable=no-member,unused-variable try: received_offer = line['Fellow'] == 'Yes' jacs = line["Research Classification"][1:3] applicants_dict = { "application_year": 2017, "fellow": False, "received_offer": received_offer, "forenames": line["First name"], "surname": line["Surname"], "affiliation": line["Home institution"], "department": line["Department"] if pd.notnull(line["Department"]) else "", "group": line["Group within Department (if any)"] if pd.notnull(line["Group within Department (if any)"]) else "", "career_stage_when_apply": line["Career stage"][6], "job_title_when_apply": line["Job Title"], "research_area": line["Area of work"], "research_area_code": jacs, "email": line["Email Address"], "phone": line["Telephone number"], "gender": line["Gender"][0] if pd.notnull(line["Gender"]) else 'R', "home_country": "GB", "home_city": "Unknow", "funding": line["Which primary funding body/charity/organisation would you normally turn to if seeking financial support for your research/work?"], "funding_notes": line["Any additional funders?"] if pd.notnull(line["Any additional funders?"]) else "", "claimantship_grant": 3000 if received_offer else 0, "institutional_website": line["Institutional web page"] if pd.notnull(line["Institutional web page"]) else "", "website": line["Personal web page"] if pd.notnull(line["Personal web page"]) else "", "orcid": line["ORCID"] if pd.notnull(line["ORCID"]) else "", "google_scholar": line["Google Scholar"] if pd.notnull(line["Google Scholar"]) else "", "github": line["GitHub"] if pd.notnull(line["GitHub"]) else "", "gitlab": line["GitLab"] if pd.notnull(line["GitLab"]) else "", "twitter": line["Twitter handle"] if pd.notnull(line["Twitter handle"]) else "", "is_into_training": line["Have training in plans - added by AN"] == "Yes", "carpentries_instructor": line["Carpentry instructor - added by AN"] == "Yes", "research_software_engineer": line["RSE - added by AN"] == "Yes", "screencast_url": line["Application Screencast URL"] if pd.notnull(line["Application Screencast URL"]) else "", "example_of_writing_url": line["Example of writing"] if pd.notnull(line["Example of writing"]) else "", } applicant = Claimant(**applicants_dict) applicant.save() success_list.append(index) if received_offer: new_user = User.objects.create_user( username=applicant.slug, email=applicant.email, password=user_manager.make_random_password(), first_name=line["First name"], last_name=line["Surname"] ) applicant.user = new_user applicant.save() except BaseException as exception: print("Error: {}\n{}\n{}".format(exception, line, 80 * "-")) fail_list.append(index) print(80 * "-") print("Success: {}".format(success_list)) print("Fail: {}".format(fail_list))
def _generate_cart_id(): user = BaseUserManager() cart_id = user.make_random_password(50) return cart_id
def handle(self, *args, **options): fail_list = [] success_list = [] user_manager = BaseUserManager() data = pd.read_csv(options['csv']) for index, line in data.iterrows(): # pylint: disable=no-member,unused-variable try: received_offer = line['Fellow'] == 'Yes' jacs = line["Research Classification"][1:3] applicants_dict = { "application_year": 2017, "fellow": False, "received_offer": received_offer, "forenames": line["First name"], "surname": line["Surname"], "affiliation": line["Home institution"], "department": line["Department"] if pd.notnull(line["Department"]) else "", "group": line["Group within Department (if any)"] if pd.notnull( line["Group within Department (if any)"]) else "", "career_stage_when_apply": line["Career stage"][6], "job_title_when_apply": line["Job Title"], "research_area": line["Area of work"], "research_area_code": jacs, "email": line["Email Address"], "phone": line["Telephone number"], "gender": line["Gender"][0] if pd.notnull(line["Gender"]) else 'R', "home_country": "GB", "home_city": "Unknow", "funding": line[ "Which primary funding body/charity/organisation would you normally turn to if seeking financial support for your research/work?"], "funding_notes": line["Any additional funders?"] if pd.notnull(line["Any additional funders?"]) else "", "claimantship_grant": 3000 if received_offer else 0, "institutional_website": line["Institutional web page"] if pd.notnull(line["Institutional web page"]) else "", "website": line["Personal web page"] if pd.notnull(line["Personal web page"]) else "", "orcid": line["ORCID"] if pd.notnull(line["ORCID"]) else "", "google_scholar": line["Google Scholar"] if pd.notnull(line["Google Scholar"]) else "", "github": line["GitHub"] if pd.notnull(line["GitHub"]) else "", "gitlab": line["GitLab"] if pd.notnull(line["GitLab"]) else "", "twitter": line["Twitter handle"] if pd.notnull(line["Twitter handle"]) else "", "is_into_training": line["Have training in plans - added by AN"] == "Yes", "carpentries_instructor": line["Carpentry instructor - added by AN"] == "Yes", "research_software_engineer": line["RSE - added by AN"] == "Yes", "screencast_url": line["Application Screencast URL"] if pd.notnull(line["Application Screencast URL"]) else "", "example_of_writing_url": line["Example of writing"] if pd.notnull(line["Example of writing"]) else "", } applicant = Claimant(**applicants_dict) applicant.save() success_list.append(index) if received_offer: new_user = get_user_model().objects.create_user( username=applicant.slug, email=applicant.email, password=user_manager.make_random_password(), first_name=line["First name"], last_name=line["Surname"]) applicant.user = new_user applicant.save() except BaseException as exception: print("Error: {}\n{}\n{}".format(exception, line, 80 * "-")) fail_list.append(index) print(80 * "-") print("Success: {}".format(success_list)) print("Fail: {}".format(fail_list))
def add_cands_and_email(cand_csv, num_rows, website_login_link, task=None): candidate_group = Group.objects.get(name=ATTR.CANDIDATE) progress_float = 0.0 # lgtm [py/multiple-definition] CAND_ACC_WEIGHT = 0.75 EMAIL_WEIGHT = 0.25 # Sanity check progress if task is not None: task.progress = 1.0 task.save() # Pre-screen and validate data new_cand_list = [] email_set = set() username_set = set() current_cand_semester = get_current_cand_semester() email_passwords = {} if current_cand_semester is None: error_msg = "Inform CompServ the following: Please add the current semester in CourseSemester." error_msg += " " error_msg += NO_ACTION_PLS_FIX return False, error_msg for i, row in enumerate(cand_csv): try: candidatedto = CandidateDTO(row) except AssertionError as e: error_msg = "Invalid CSV format. Check that your columns are correctly labeled, there are NO blank rows, and filled out for each row." error_msg += " " error_msg += NO_ACTION_PLS_FIX error_msg += " " error_msg += "Candidate error message: {}.".format(e) error_msg += " " error_msg += "Row Information at row {}: {}.".format(i + 1, row) return False, error_msg password = BaseUserManager.make_random_password( None, length=DEFAULT_RANDOM_PASSWORD_LENGTH) duplicate, error_msg = check_duplicates(candidatedto, row, email_set, username_set, i) if duplicate: return False, error_msg new_cand = User( username=candidatedto.username, email=candidatedto.email, ) email_set.add(candidatedto.email) username_set.add(candidatedto.username) new_cand.first_name = candidatedto.first_name new_cand.last_name = candidatedto.last_name new_cand.set_password(password) new_cand_list.append(new_cand) email_passwords[new_cand.email] = password progress_float = CAND_ACC_WEIGHT * 100 * (i + 1) / num_rows if task is not None: task.progress = round(progress_float) task.save() # Reset to CAND_ACC_WEIGHT in case floating point errors progress_float = CAND_ACC_WEIGHT * 100 if task is not None: task.progress = round(progress_float) task.save() num_of_accounts = len(email_set) if num_of_accounts != num_rows: error_msg = ( "Internal Error: number of accounts ({}) != number of rows ({})". format(num_of_accounts, num_rows)) error_msg += " " error_msg += NO_ACTION_PLS_FIX return False, error_msg # Release the memory once done del email_set del username_set email_errors = [] for i, new_cand in enumerate(new_cand_list): if i != 0 and i % 50 == 0: time.sleep(10) new_cand.save() candidate_group.user_set.add(new_cand) profile = Profile.objects.get(user=new_cand) profile.candidate_semester = current_cand_semester profile.save() subject = "[HKN] Candidate account" html_content = render_to_string( "candidate/new_candidate_account_email.html", { "subject": subject, "first_name": new_cand.first_name, "username": new_cand.username, "password": email_passwords[new_cand.email], "website_link": website_login_link, "img_link": get_rand_photo(), }, ) if settings.DEBUG: print("\n") print(new_cand.first_name, new_cand.username, new_cand.email) print(html_content) print("\n") else: msg = EmailMultiAlternatives(subject, subject, settings.NO_REPLY_EMAIL, [new_cand.email]) msg.attach_alternative(html_content, "text/html") try: msg.send() except Exception as e: email_errors.append((new_cand_list[i].email, str(e))) progress_float = (CAND_ACC_WEIGHT * 100) + (EMAIL_WEIGHT * 100 * (i + 1) / num_of_accounts) if task is not None: task.progress = round(progress_float) task.save() # If gone through everything and no errors if len(email_errors) > 0: error_msg = ( "An error occured during the sending of emails. " + "Candidate Email and Error Messages: " + str(email_errors) + " --- " + "Inform CompServ of the errors, and inform the candidates " + "to access their accounts by resetting their password " + 'using "Forget your password?" in the Login page. ' + "All {} candidates added!".format(num_of_accounts)) return False, error_msg else: return True, "Successfully added {} candidates!".format( num_of_accounts)