def setUp(self): super().setUp() self.mitch = AppUser(phone_number=self.inviter_number, username='******', timezone=US_TIMEZONES['b']) self.db.session.add(self.mitch) self.billy = AppUser(phone_number=self.secondary_number, username='******', timezone=US_TIMEZONES['b']) self.db.session.add(self.billy) self.team = Team(founder=self.mitch, name='The Cherrys') self.db.session.add(self.team) self.mitch_member = TeamMember(user=self.mitch, team=self.team, inviter=self.mitch, status=Statuses.ACTIVE) self.db.session.add(self.mitch_member) self.billy_member = TeamMember(user=self.billy, team=self.team, inviter=self.mitch, status=Statuses.PENDING) self.db.session.add(self.billy_member) self.db.session.commit() self.mitch = self.mitch.to_dict() self.billy = self.billy.to_dict() self.team = self.team.to_dict()
def add_users(services): staff_role = Role.query.filter_by(name='Staff').first() patient_role = Role.query.filter_by(name='Patient').first() for service in services: user = AppUser(email=service.name.lower().replace(' ', '_') + '*****@*****.**', password=encrypt_password('password'), service_id=service.id, full_name=fake.name(), phone_number=formatted_phone_number()) db.session.add(user) user.roles.append(staff_role) patient_user = AppUser(email='*****@*****.**', password=encrypt_password('password'), full_name=fake.name(), phone_number=formatted_phone_number()) db.session.add(patient_user) patient_user.roles.append(patient_role) db.session.commit() app_users = AppUser.query.all() print "Added users" return app_users
def test_questions_evaluated_correctly(self): s = self.client.session newUser = AppUser(100000, "*****@*****.**", "notapassword", "Applicant", False, "Firstname", "Lastname") newUser.save() s.update({ "id": 100000, }) s.save() data = dict() testML = MLModel(1, "TestModel") testML.save() testOrganisation = Organisation(1, "TestOrg", True, "*****@*****.**", "01234567890") testOrganisation.save() testJob = Job(1, 1, 1, "TestJob", "TestDesc", "2019-03-15") testJob.save() testCV = CV(1, 1, '{"Name": "Bill", "Degree Qualification": "Computer Science BSc", "Degree Level": "1st", "University Attended": "University of Warwick", "Skills": [{"Skill": "Server setup", "Expertise": 10}, {"Skill": "Database Management", "Expertise": 10}], "Languages Known": [{"Language": "Python", "Expertise": 10}, {"Language": "Java", "Expertise": 10}, {"Language": "C#", "Expertise": 10}], "Hobbies": [{"Name": "Gaming", "Interest": 10}], "A-Level Qualifications": [{"Subject": "Computer Science", "Grade": "A"}, {"Subject": "Chemistry", "Grade": "A"}], "Previous Employment": [{"Company": "Microsoft", "Position": "CEO", "Length of Employment": 120}]}') test_question_one = TestQuestions(1, "What is 5 + 3?", "8", 1) test_question_one.save() test_question_two = TestQuestions(2, "What is 9 + 5?", "14", 1) test_question_two.save() test_question_three = TestQuestions(3, "What is 12 + 4?", "16", 1) test_question_three.save() test_question_four = TestQuestions(4, "What is 15 + 16?", "31", 1) test_question_four.save() data['extra_questionfield_0'] = "8" data['extra_questionfield_1'] = "14" data['extra_questionfield_2'] = "16" data['extra_questionfield_3'] = "73" response = self.client.post('/applicant/test/1/', data) self.assertEqual(200, response.status_code) newApplication = Application.objects.get(id=1) self.assertEqual(75.0, newApplication.answer_percent)
def test_store_existing_user(client, caplog): """End-to-end test of submitting the /validate-basic-info route with an existing user and an existing organization.""" existing_org = Organization(name='Foo Bar', financial_classification='', coverage_scope='', coverage_focus='', platform='', employee_range='', budget='', affiliations='') db.session.add(existing_org) existing_user = AppUser(name='Foo', email='*****@*****.**', email_hash='f3ada405ce890b6f8204094deb12d8a8', approved=True, orgs=[existing_org]) db.session.add(existing_user) db.session.commit() userform = ImmutableMultiDict([('name', 'bar'), ('email', '*****@*****.**'), ('news_org', 'foo bar')]) response = client.post('/validate-basic-info', data=userform) user = AppUser.query.filter_by(email='*****@*****.**').first() assert user.name == 'Bar' assert len(user.orgs) == 1 assert user.orgs[0].name == 'Foo Bar' assert response.get_json()['user'] == 'approved' assert ('Suppressing an email with the following params: ' 'Sender: [email protected]. Recipients: [\'[email protected]\']. ' 'Subject: You\'re all set to access our benchmarks!' in caplog.text)
def setUp(self): super().setUp() now = dt.datetime.now() self.mitch = AppUser(phone_number=self.inviter_number, username='******', timezone=US_TIMEZONES['b']) self.db.session.add(self.mitch) self.exchange = Exchange(router=RouterNames.DID_YOU_DO_IT, user=self.mitch) self.db.session.add(self.exchange) self.task1 = Task(description='clean', due_date=now - dt.timedelta(days=6), active=True, user=self.mitch, exchange=self.exchange) self.db.session.add(self.task1) self.task2 = Task(description='cook', due_date=now - dt.timedelta(days=8), active=True, user=self.mitch, exchange=self.exchange) self.db.session.add(self.task2) self.db.session.commit() self.mitch = self.mitch.to_dict()
def main(): app = create_app() with app.app_context(): db.metadata.create_all(db.engine) services = Service.query.all() staff_role = Role.query.filter_by(name='Staff').first() print 'Enter full name: ' full_name = raw_input() print 'Enter email address: ' email = raw_input() print 'Enter phone number: ' phone_number = raw_input() print 'Current organizations:' for service in services: print '%d %s' % (service.id, service.name) print 'Enter the id of the organization to associate with this user: '******'Is this a staff user? Enter y or n: ' staff_user_yn = raw_input() password = getpass() assert password == getpass('Password (again):') user = AppUser(email=email, password=encrypt_password(password), service_id=service_id, full_name=full_name, phone_number=phone_number) db.session.add(user) if staff_user_yn == 'y': user.roles.append(staff_role) db.session.commit() print 'User added.'
def store_user(name, email, email_hash, org): """Inserts a new user into the database. Args: name: name of the user. email: user's email address. email_hash: md5-hash of the email address. org: SQLAlchemy Organization object representing the news organization the user belongs to. """ user_info = {'name': name, 'email': email, 'email_hash': email_hash} # The new user isn't approved for access by default user = AppUser(**user_info, approved=False, orgs=[org]) # Do a bootleg upsert (due to lack of ORM support) db.session.add(user) try: db.session.commit() except IntegrityError: db.session.rollback() return update_user(user_info, org) except: db.session.rollback() raise return user
def reg(request): res = UserReg() if request.method == 'POST': res = UserReg(request.POST) if res.is_valid(): code = request.POST.get('msgcode') if code != request.session.get('smscode'): return render(request, 'register.html', context={ 'user': res, 'codeer': '验证码错误' }) else: request.session.flush() phone = request.POST.get('phone') email = request.POST.get('email') username = request.POST.get('user_name') password = request.POST.get('pwd') auser = AppUser() auser.u_username = username auser.u_password_has = hashlib.sha1( password.encode('utf8')).hexdigest() auser.u_email = email auser.u_phone = phone auser.u_sex = True auser.u_register_time = datetime.datetime.now() auser.u_type = 0 auser.u_credits = 50 auser.save() return redirect(reverse('app:login')) return render(request, 'register.html', context={'user': res}) return render(request, 'register.html', context={'user': res})
def setUp(self): super().setUp() # add a user self.mitch = AppUser(phone_number=self.inviter_number, username='******', timezone=US_TIMEZONES['b']) self.db.session.add(self.mitch) # self.db.session.add(self.blair) # add a notif self.notif = Notification(router=RouterNames.DID_YOU_DO_IT, hour=21, minute=0, active=True, user=self.mitch) self.db.session.add(self.notif) # add exchange self.exchange = Exchange(router=RouterNames.DID_YOU_DO_IT, outbound='Did you do it?', user=self.mitch, created=dt.datetime.now() - dt.timedelta(days=10)) self.db.session.add(self.exchange) # add point self.point = Point(value=10, user=self.mitch) # add task self.task = Task(description='Win today', due_date=dt.datetime.now(), active=True, exchange=self.exchange, user=self.mitch) self.db.session.add(self.task) self.inteam = Team(id=TEST_TEAM_ID, founder=self.mitch, name='inteam') self.db.session.add(self.inteam) self.pendingteam = Team(founder=self.mitch, name='pendingteam') self.db.session.add(self.pendingteam) self.mitch_member = TeamMember(user=self.mitch, team=self.inteam, inviter=self.mitch, status=Statuses.ACTIVE) self.db.session.add(self.mitch_member) self.mitch_member2 = TeamMember(user=self.mitch, team=self.pendingteam, inviter=self.mitch, status=Statuses.PENDING) self.db.session.add(self.mitch_member2)
def insert_user(): insert_roles() service = get_service() staff_role = Role.query.filter_by(name='Staff').first() app_user = AppUser(full_name='App User', email='*****@*****.**', password=encrypt_password('password'), service=service) db.session.add(app_user) app_user.roles.append(staff_role) db.session.commit() return app_user
def setUp(self): super().setUp() # the scenario is Mitch has received an invitation to a team # He has never used Bricks before self.inviter = AppUser( phone_number=self.inviter_number, username='******', timezone=US_TIMEZONES['b']) self.mitch = AppUser( phone_number=self.invitee_number, username='******', timezone=US_TIMEZONES['b']) self.team = Team( founder=self.inviter, name='The Cherrys') self.inviter_member = TeamMember( user=self.inviter, team=self.team, inviter=self.inviter, status=Statuses.ACTIVE) self.invitee_member = TeamMember( user=self.mitch, team=self.team, inviter=self.inviter, status=Statuses.PENDING) self.exchange = Exchange( user=self.mitch, router=InitOnboardingInvited.__name__) self.db.session.add(self.inviter) self.db.session.add(self.mitch) self.db.session.add(self.team) self.db.session.add(self.inviter_member) self.db.session.add(self.invitee_member)
def setUp(self): super().setUp() # add a user self.mitch = AppUser( phone_number=self.number, username='******', timezone=self.mitch_tz) self.db.session.add(self.mitch) # add exchange self.exchange = Exchange( router = RouterNames.DID_YOU_DO_IT, outbound = 'Did you do it?', user = self.mitch) self.db.session.add(self.exchange) # add a notif self.did_you_do_it_notif = Notification( router = RouterNames.DID_YOU_DO_IT, day_of_week = 'daily', hour = self.local_now.hour, minute = self.local_now.minute, active = True, user = self.mitch) self.db.session.add(self.did_you_do_it_notif) self.morning_conf_notif = Notification( router = RouterNames.MORNING_CONFIRMATION, day_of_week = 'daily', hour = self.local_now.hour, minute = self.local_now.minute, active = True, user = self.mitch) self.db.session.add(self.morning_conf_notif) self.week_reflection_notif = Notification( router = RouterNames.WEEK_REFLECTION, day_of_week = 'daily', hour = self.local_now.hour, minute = self.local_now.minute, active = True, user = self.mitch) self.db.session.add(self.week_reflection_notif) # add task self.task = Task( description='Win today', due_date = dt.datetime.now()+ dt.timedelta(minutes=1), active = True, exchange = self.exchange, user = self.mitch) self.db.session.add(self.task)
def query_user(fir_auth_id): """find the user that matches fir_auth_id, else generate new user""" try: user = db.session.query(AppUser).filter( AppUser.fir_auth_id == fir_auth_id).one() return user except: new_user = AppUser(fir_auth_id=fir_auth_id) db.session.add(new_user) db.session.commit() return new_user
def register(): if current_user.is_authenticated: return redirect(url_for('index')) form = RegistrationForm() if form.validate_on_submit(): # noinspection PyArgumentList app_user = AppUser(first_name=form.first_name.data, last_name=form.last_name.data, email=form.email.data) app_user.set_password(form.password.data) db.session.add(app_user) db.session.commit() flash('Congratulations, you are now a registered user!') return redirect(url_for('login')) return render_template('register.html', title='Register', form=form)
def test_JSON_formatted_correctly(self): #This function tests that data from the CV form is correctly inserted into the database in a format #that will be accepted by the machine learning s = self.client.session newUser = AppUser(100000, "*****@*****.**", "notapassword", "Applicant", False, "Firstname", "Lastname") newUser.save() s.update({ "id": 100000, }) s.save() data = dict() data['extra_field_count'] = 10 data['extra_language_count'] = 10 data['extra_hobby_count'] = 10 data['extra_qual_count'] = 10 data['extra_job_count'] = 10 data['name'] = "testname" data['degree'] = "testdegree" #data['degree_level'] = "1st" data['university'] = "testuniversity" for i in range(10): data['extra_charfield_' + str(i+1)] = "testchar"+str(i+1) data['extra_intfield_'+str(i+1)] = 10 data['extra_charfield_lang_' +str(i+1)] = "testlang"+str(i+1) data['extra_intfield_lang_'+str(i+1)] = 10 data['extra_charfield_hobby_'+str(i+1)] = "testhobby"+str(i+1) data['extra_intfield_hobby_'+str(i+1)] = 10 data['extra_charfield_qual_'+str(i+1)] = "testqual"+str(i+1) data['extra_intfield_qual_'+str(i+1)] = 10 data['extra_charfield_job_'+str(i+1)] = "testjob"+str(i+1) data['extra_intfield_job_'+str(i+1)] = "testpos"+str(i+1) data['extra_lenfield_job_'+str(i+1)] = 10 response = self.client.post('/applicant/cv/', data) self.assertEqual(200, response.status_code) testCv = json.loads(CV.objects.get(pk=0).cvData) skill = testCv['Skills'] language = testCv['Languages Known'] hobbies = testCv['Hobbies'] qualifications = testCv['A-Level Qualifications'] jobs = testCv['Previous Employment'] for i in range(10): self.assertEqual("testchar"+str(i+1), skill[i]["Skill"]) self.assertEqual("testlang"+str(i+1), language[i]["Language"]) self.assertEqual("testhobby"+str(i+1), hobbies[i]["Name"]) self.assertEqual("testqual"+str(i+1), qualifications[i]["Qualification"]) self.assertEqual("testjob"+str(i+1), jobs[i]["Company"])
def query_user_with_number(phone_number): ''' use phone number to find user in db, else add to db returns the user object ''' user = db.session.query(AppUser).filter( AppUser.phone_number == phone_number).first() if user is not None: return user.to_dict() else: new_user = AppUser(phone_number=phone_number) db.session.add(new_user) db.session.commit() new_user = new_user.to_dict() insert_notifications(new_user) return new_user
def setUp(self): super().setUp() self.mitch = AppUser(phone_number=self.inviter_number, username='******', timezone=US_TIMEZONES['a']) self.db.session.add(self.mitch) self.exchange = Exchange(router=RouterNames.DID_YOU_DO_IT, outbound='Did you do it?', user=self.mitch) self.db.session.add(self.exchange) self.task = Task(description=self.description, due_date=self.due_date, active=True, user=self.mitch, exchange=self.exchange) self.db.session.add(self.task) self.db.session.commit() self.mitch = self.mitch.to_dict()
def post(self, request, format=None): serializer = RegisterSerializer(data=request.data) if serializer.is_valid(): try: user = AppUser.objects.get(email=serializer.data['email']) admin_user = User.objects.get(email=serializer.data['email']) return Response({"status": "user exist"}, status=status.HTTP_400_BAD_REQUEST) except ObjectDoesNotExist: username = "" num = random.randint(4, 10) while True: username = "" for i in range(num): username += random.choice(seed) try: user = AppUser.objects.get(username=username) except AppUser.DoesNotExist: break password = serializer.data['password'] email = serializer.data['email'] admin_user = User.objects.create_user( username=username, password=password, last_login=datetime.datetime.now(), email=email) admin_user.save() user = AppUser() user.username = username user.password = password user.user = admin_user user.email = email user.save() return Response(status=status.HTTP_201_CREATED) return Response({"status": "format error"}, status=status.HTTP_400_BAD_REQUEST)
def add_app_user(data): add_user(data) user = User.objects.get(username=data['username']) p = AppUser(user=user, photo=data['photo'], user_type=data['type']) p.save() print "App user saved"
def init_list_analysis(list_id, list_name, count, open_rate, api_key, data_center, user_email): # Try to pull the list stats from database existing_list = (ListStats.query. filter_by(list_id=list_id).first()) # Placeholder for list stats stats = None if existing_list is None: stats = import_analyze_store_list(list_id, count, open_rate, api_key, data_center, user_email) else: # Get list stats from database results # Deserialize the histogram data stats = {'subscribers': existing_list.subscribers, 'open_rate': existing_list.open_rate, 'hist_bin_counts': json.loads(existing_list.hist_bin_counts), 'subscribed_pct': existing_list.subscribed_pct, 'unsubscribed_pct': existing_list.unsubscribed_pct, 'cleaned_pct': existing_list.cleaned_pct, 'pending_pct': existing_list.pending_pct, 'high_open_rt_pct': existing_list.high_open_rt_pct, 'cur_yr_inactive_pct': existing_list.cur_yr_inactive_pct} # Log that the request occured current_user = AppUser(user_email=user_email, list_id=list_id) db.session.add(current_user) db.session.commit() # Generate averages avg_stats = db.session.query(func.avg(ListStats.subscribers), func.avg(ListStats.open_rate), func.avg(ListStats.subscribed_pct), func.avg(ListStats.unsubscribed_pct), func.avg(ListStats.cleaned_pct), func.avg(ListStats.pending_pct), func.avg(ListStats.high_open_rt_pct), func.avg(ListStats.cur_yr_inactive_pct)).first() # Generate charts # Using OrderedDict (for now) as Pygal occasionally seems to break with # The Python 3.5 dictionary standard which preserves order by default # Export them as pngs to /charts list_size_chart = BarChart('Chart A: List Size vs. ' 'Database Average (Mean)', OrderedDict([ ('Your List', [stats['subscribers']]), ('Average (Mean)', [avg_stats[0]])]), percentage=False) list_size_chart.render_png(list_id + '_size') list_breakdown_chart = BarChart('Chart B: List Composition vs. ' 'Database Average (Mean)', OrderedDict([ ('Subscribed %', [stats['subscribed_pct'], avg_stats[2]]), ('Unsubscribed %', [stats['unsubscribed_pct'], avg_stats[3]]), ('Cleaned %', [stats['cleaned_pct'], avg_stats[4]]), ('Pending %', [stats['pending_pct'], avg_stats[5]])]), x_labels=('Your List', 'Average (Mean)')) list_breakdown_chart.render_png(list_id + '_breakdown') open_rate_chart = BarChart('Chart C: List Open Rate vs. ' 'Database Average (Mean)', OrderedDict([ ('Your List', [stats['open_rate']]), ('Average (Mean)', [avg_stats[1]])])) open_rate_chart.render_png(list_id + '_open_rate') open_rate_hist_chart = Histogram('Chart D: Distribution of ' 'User Unique Open Rates', OrderedDict([ ('Your List', stats['hist_bin_counts'])])) open_rate_hist_chart.render_png(list_id + '_open_rate_histogram') high_open_rt_pct_chart = BarChart('Chart E: Percentage of ' 'Subscribers with User Unique Open Rate >80% vs. ' 'Database Average (Mean)', OrderedDict([ ('Your List', [stats['high_open_rt_pct']]), ('Average (Mean)', [avg_stats[6]])])) high_open_rt_pct_chart.render_png(list_id + '_high_open_rt') cur_yr_member_pct_chart = BarChart('Chart F: Percentage of Subscribers ' 'who did not Open in last 365 Days vs. Database Average (Mean)', OrderedDict([ ('Your List', [stats['cur_yr_inactive_pct']]), ('Average (Mean)', [avg_stats[7]])])) cur_yr_member_pct_chart.render_png(list_id + '_cur_yr_inactive_pct') # Send charts as an email report # Due to the way Flask-Mail works, reimport app_context first with app.app_context(): msg = Message('Your Email Benchmarking Report is Ready!', sender='*****@*****.**', recipients=[user_email], html=render_template('report_email.html', title='We\'ve analyzed the {} List!'.format(list_name), list_id=list_id)) mail.send(msg)
def test_analysis(client, caplog): """End-to-end test of analyzing a list.""" existing_org = Organization(name='Foo Bar', financial_classification='', coverage_scope='', coverage_focus='', platform='', employee_range='', budget='', affiliations='') db.session.add(existing_org) existing_user = AppUser(name='Foo', email='*****@*****.**', email_hash='f3ada405ce890b6f8204094deb12d8a8', approved=True, orgs=[existing_org]) db.session.add(existing_user) db.session.commit() existing_org_id = existing_org.id existing_user_id = existing_user.id list_id = os.environ.get('TESTING_LIST_ID') api_key = os.environ.get('TESTING_API_KEY') data_center = api_key.rsplit('-', 1)[1] chart_files = glob.glob('app/static/charts/*.png') for file in chart_files: if list_id in file: os.remove(file) request_uri = 'https://{}.api.mailchimp.com/3.0/lists/{}'.format( data_center, list_id) params = (('fields', 'name,' 'stats.member_count,' 'stats.unsubscribe_count,' 'stats.cleaned_count,' 'stats.open_rate,' 'date_created,' 'stats.campaign_count'), ) response = requests.get(request_uri, params=params, auth=('email-benchmarks-testing', api_key)) data = response.json() request_data = { 'list_id': list_id, 'list_name': data['name'], 'total_count': (data['stats']['member_count'] + data['stats']['unsubscribe_count'] + data['stats']['cleaned_count']), 'open_rate': data['stats']['open_rate'], 'date_created': data['date_created'], 'campaign_count': data['stats']['campaign_count'] } with client as c: with c.session_transaction() as sess: sess['user_id'] = existing_user_id sess['email'] = '*****@*****.**' sess['key'] = api_key sess['data_center'] = data_center sess['monthly_updates'] = True sess['store_aggregates'] = True sess['org_id'] = existing_org_id response = c.post('/analyze-list', data=json.dumps(request_data), content_type='application/json') assert response.status == '200 OK' chart_files = glob.glob('app/static/charts/*.png') assert any(list_id + '_size_' in file for file in chart_files) assert any(list_id + '_breakdown_' in file for file in chart_files) assert any(list_id + '_open_rate_' in file for file in chart_files) assert any(list_id + '_open_rate_histogram_' in file for file in chart_files) assert any(list_id + '_high_open_rt_pct_' in file for file in chart_files) assert any(list_id + '_cur_yr_inactive_pct_' in file for file in chart_files) assert ('Suppressing an email with the following params: ' 'Sender: [email protected]. Recipients: [\'[email protected]\']. ' 'Subject: Your Email Benchmarking Report is Ready!' in caplog.text) email_list = EmailList.query.filter_by(list_id=list_id).first() assert email_list assert email_list.org.id == existing_org_id assert email_list.monthly_update_users[0].id == existing_user_id assert email_list.analyses[0] assert email_list.analyses[0].open_rate == data['stats']['open_rate']
def setUp(self): super().setUp() self.mitch = AppUser( phone_number=self.inviter_number, username='******', timezone=US_TIMEZONES['b']) self.db.session.add(self.mitch) self.billy = AppUser( phone_number=self.secondary_number, username='******', timezone=US_TIMEZONES['b']) self.db.session.add(self.billy) self.jonah = AppUser( phone_number=self.third_number, username='******', timezone=US_TIMEZONES['b']) self.db.session.add(self.jonah) self.allie = AppUser( phone_number=self.fourth_number, username='******', timezone=US_TIMEZONES['b']) self.db.session.add(self.allie) self.winnie = AppUser( phone_number=self.fifth_number, username='******', timezone=US_TIMEZONES['b']) self.db.session.add(self.winnie) self.full_team = Team( founder = self.mitch, name = 'The Fulls') self.db.session.add(self.full_team) self.open_team = Team( founder = self.mitch, name = 'The Opens') self.db.session.add(self.open_team) self.mitch_member = TeamMember( user = self.mitch, team = self.full_team, inviter = self.mitch, status = Statuses.ACTIVE) self.db.session.add(self.mitch_member) self.mitch_member_2 = TeamMember( user = self.mitch, team = self.open_team, inviter = self.mitch, status = Statuses.ACTIVE) self.db.session.add(self.mitch_member_2) self.billy_member = TeamMember( user = self.billy, team = self.full_team, inviter = self.mitch, status = Statuses.ACTIVE) self.db.session.add(self.billy_member) self.jonah_member = TeamMember( user = self.jonah, team = self.full_team, inviter = self.mitch, status = Statuses.ACTIVE) self.db.session.add(self.jonah_member) self.allie_member = TeamMember( user = self.allie, team = self.full_team, inviter = self.mitch, status = Statuses.ACTIVE) self.db.session.add(self.allie_member) self.winnie_member = TeamMember( user = self.winnie, team = self.full_team, inviter = self.mitch, status = Statuses.ACTIVE) self.db.session.add(self.winnie_member) self.db.session.commit() self.mitch = self.mitch.to_dict() self.billy = self.billy.to_dict()
def aaron_signup(request): #This function creates a new user from the data entered into the sign up form form = AddUserForm() context = {'form': form, 'signup_page': 'active'} if request.method == 'POST': form = AddUserForm(request.POST) if form.is_valid(): email = form.cleaned_data[ 'email'] # TODO check email is unique, only store unique emails password = form.cleaned_data['password'] check_password = form.cleaned_data['confirm_password'] first_name = form.cleaned_data['first_name'] last_name = form.cleaned_data['last_name'] if AppUser.objects.filter(email=email).exists(): context = { 'form': form, 'signup_page': 'active', 'error_message': '<p style="color:red">This email already exsists.</p>' } return render(request, 'applicantportal/signup.html', context) if len(password) < 8: context = { 'form': form, 'signup_page': 'active', 'error_message': '<p style="color:red">Password length is too short. Password must be greater than 8 characters.</p>' } return render(request, 'applicantportal/signup.html', context) if password != check_password: context = { 'form': form, 'signup_page': 'active', 'error_message': '<p style="color:red">Passwords do not match.</p>' } return render(request, 'applicantportal/signup.html', context) if any(x.isupper() for x in password) == False: context = { 'form': form, 'signup_page': 'active', 'error_message': '<p style="color:red">Password needs one uppercase letter.</p>' } return render(request, 'applicantportal/signup.html', context) hashed_password = make_password(password) user = AppUser(email=email, password=hashed_password, userType='Applicant', first_name=first_name, last_name=last_name) user.save() # TODO create session key request.session['id'] = AppUser.objects.get(email=email).id return applicant_jobs(request) return render(request, 'applicantportal/signup.html', context)