def get(self, request): email_address = request.GET['email_address'] api_response = IdentityGatewayActions().list('user', params={ 'email': email_address, 'service': 'NANNY' }) record = api_response.record[0] validation_link, email_expiry_date = utilities.generate_email_validation_link( email_address) record['magic_link_email'] = validation_link.split('/')[-1] record['email_expiry_date'] = email_expiry_date IdentityGatewayActions().put('user', params=record) # Set Nanny email template # If existing user if record['mobile_number'] != '': template_id = '5d983266-7efa-4978-9d4c-9099ed6ece28' # If new user else: template_id = '45c6b63e-1973-45e5-99d7-25f2877bebd9' # Send a Nanny email notify.send_email(email=email_address, personalisation={"link": validation_link}, template_id=template_id) return render(request, template_name='email-resent.html', context={'email_address': email_address})
def form_valid(self, form): application_id = self.request.GET['id'] record = IdentityGatewayActions().read('user', params={ 'application_id': application_id }).record record['sms_resend_attempts'] = 0 record['email_expiry_date'] = 0 IdentityGatewayActions().put('user', params=record) response = login_redirect_helper.redirect_by_status( record['application_id']) CustomAuthenticationHandler.create_session(response, {'email': record['email']}) # Update last accessed time when successfully signed in nanny_actions = NannyGatewayActions() app_response = nanny_actions.read( 'application', params={'application_id': application_id}) if app_response.status_code == 200 and hasattr(app_response, 'record'): # application might not exist yet, if user signed out before completing contact details task application = app_response.record application['date_last_accessed'] = datetime.datetime.now() application['application_expiry_email_sent'] = False nanny_actions.put('application', application) return response
def get(self, request, id): identity_actions = IdentityGatewayActions() api_response = identity_actions.list('user', params={ 'magic_link_email': id, 'service': "NANNY" }) if api_response.status_code == 200: self.record = api_response.record[0] if not self.link_has_expired(): # If user has come from the 'Change Email' journey if self.record['email'] != self.record[ 'change_email'] and self.record[ 'change_email'] is not None and self.record[ 'change_email'] != "": # Update the user's email update_email = self.record['change_email'] update_email_record = self.record update_email_record['email'] = update_email response = identity_actions.put('user', params=update_email_record) if response.status_code != 200: return HttpResponseRedirect( reverse('Service-Unavailable')) http_response = HttpResponseRedirect( self.get_success_url()) CustomAuthenticationHandler.create_session( http_response, {'email': update_email}) return http_response email = self.record['email'] http_response = HttpResponseRedirect(self.get_success_url()) CustomAuthenticationHandler.create_session( http_response, {'email': email}) return http_response else: return HttpResponseRedirect(reverse('Link-Used')) elif api_response.status_code == 404: return HttpResponseRedirect(reverse('Link-Used')) else: return HttpResponseRedirect(reverse('Service-Unavailable'))
def form_valid(self, email_form): if not utilities.test_notify(): return HttpResponseRedirect(reverse("Service-Unavailable")) email_address = email_form.cleaned_data["email_address"] self.email_address = ( email_address # Set such that success parameters can find value later. ) api_response = IdentityGatewayActions().list("user", params={ "email": email_address, "service": "NANNY" }) if api_response.status_code == 404: api_response = IdentityGatewayActions().create( "user", { "email": email_address, "application_id": uuid.uuid4(), "service": "NANNY", }, ) record = api_response.record else: record = api_response.record[0] validation_link, email_expiry_date = utilities.generate_email_validation_link( email_address) record["magic_link_email"] = validation_link.split("/")[-1] record["email_expiry_date"] = email_expiry_date IdentityGatewayActions().put("user", params=record) # Set Nanny email template # If existing user if record["mobile_number"] != "": template_id = "5d983266-7efa-4978-9d4c-9099ed6ece28" # If new user else: template_id = "45c6b63e-1973-45e5-99d7-25f2877bebd9" # Send Nanny email notify.send_email( email=email_address, personalisation={"link": validation_link}, template_id=template_id, ) return HttpResponseRedirect(self.get_success_url())
def form_valid(self, form): application_id = self.request.GET['id'] record = IdentityGatewayActions().read('user', params={ 'application_id': application_id }).record record['sms_resend_attempts'] = 0 IdentityGatewayActions().put('user', params=record) response = login_redirect_helper.redirect_by_status( record['application_id']) CustomAuthenticationHandler.create_session(response, {'email': record['email']}) return response
def get_form_kwargs(self): kwargs = super(SecurityCodeFormView, self).get_form_kwargs() kwargs['correct_sms_code'] = IdentityGatewayActions().read( 'user', params={ 'application_id': self.request.GET['id'] }).record['magic_link_sms'] return kwargs
def get_security_question_form(self): """ Grab the security question for a given applicant, depending upon the status of their application. """ application_id = self.request.GET['id'] app_record = NannyGatewayActions().read('application', params={ 'application_id': application_id }).record personal_details_record = IdentityGatewayActions().read( 'user', params={ 'application_id': application_id }).record if app_record is None: form = MobileNumberSecurityQuestionForm elif app_record['dbs_status'] == 'COMPLETED': form = DBSSecurityQuestionForm elif app_record['personal_details_status'] == 'COMPLETED': form = PersonalDetailsSecurityQuestionForm elif len(personal_details_record['mobile_number']) != 0: form = MobileNumberSecurityQuestionForm self.form_class = form return form
def get(self, request): if request.GET.get('id'): application_id = request.GET.get('id') user_details = IdentityGatewayActions().read('user', params={ 'application_id': application_id }).record change_email = user_details['change_email'] email_address = user_details['email'] if change_email is not None: application_id = request.GET.get('id') return render(request, 'check-email.html', context={ 'email_address': change_email, 'id': application_id }) else: return render(request, 'check-email.html', context={'email_address': email_address}) else: email_address = request.GET.get('email_address') return render(request, 'check-email.html', context={'email_address': email_address})
def get_initial(self): application_id = self.request.GET['id'] record = IdentityGatewayActions().read('user', params={'application_id': application_id}).record initial_values = { 'mobile_number': record['mobile_number'], 'other_phone_number': record['add_phone_number'] } return initial_values
def __call__(self, request): # Default the login url as being authentication exempt authentication_exempt_urls = [compile(settings.LOGIN_URL.lstrip('/'))] # If further login exempt URLs have been defined in the settings.py file, append these to # the collection if hasattr(settings, 'AUTHENTICATION_EXEMPT_URLS'): authentication_exempt_urls += [compile(expr) for expr in settings.AUTHENTICATION_EXEMPT_URLS] # Allow authentication exempt paths straight through middleware function if request.path_info == settings.AUTHENTICATION_URL or any( m.match(request.path_info) for m in authentication_exempt_urls): return self.get_response(request) # If path is not exempt, and user cookie does not exist (e.g. a bypass is being attempted) return # user to login page cookie_contents = self.get_signed_cookie(request) if cookie_contents is None: return HttpResponseRedirect(settings.LOGGED_OUT_URL) if not cookie_contents.get('email'): session_user = cookie_contents cookie_contents = {'email': session_user} else: session_user = cookie_contents['email'] if session_user is None: return HttpResponseRedirect(settings.AUTHENTICATION_URL) # If an application id has been supplied in the query string or post request application_id = None if request.method == 'GET' and 'id' in request.GET: application_id = request.GET['id'] if request.method == 'POST' and 'id' in request.POST: application_id = request.POST['id'] # If an application id is present fetch application from store if application_id is not None: # application = Application.objects.get(pk=application_id) # application = NannyGatewayActions().read('application', params={'application_id': application_id}).record user_identity_record = IdentityGatewayActions().read('user', params={'application_id': application_id}).record application_email = user_identity_record['email'] # Check the email address stored in the session matches that found on the application # and if not raise generic exception if application_email != self.get_session_user(request): raise Exception # If request has not been blocked at this point in the execution flow, allow # request to continue processing as normal response = self.get_response(request) if len(response.cookies) == 0 and cookie_contents is not None: CustomAuthenticationHandler.create_session(response, cookie_contents) return response
def form_valid(self, form): application_id = self.request.GET['id'] api_response = IdentityGatewayActions().read('user', params={'application_id': application_id}) record = api_response.record record['mobile_number'] = form.cleaned_data['mobile_number'] record['add_phone_number'] = form.cleaned_data['other_phone_number'] # Expire magic link record['email_expiry_date'] = 0 IdentityGatewayActions().put('user', params=record) response = HttpResponseRedirect(build_url('Contact-Details-Summary', get={'id': application_id})) COOKIE_IDENTIFIER = CustomAuthenticationHandler.get_cookie_identifier() if COOKIE_IDENTIFIER not in self.request.COOKIES: CustomAuthenticationHandler.create_session(response, {'email': record['email']}) return response return super(PhoneNumbersFormView, self).form_valid(form)
def get_success_url(self): # no phone number yet, skip sms validation if not self.record['mobile_number']: success_view = 'Phone-Number' # sms validation else: self.record = self.sms_magic_link(self.record) success_view = 'Security-Code' IdentityGatewayActions().put('user', params=self.record) return utilities.build_url(success_view, get={'id': self.record['application_id']})
def get(self, request): """ Handle GET request. Pass user details record, app_id and Bool for including change links to template as context.""" application_id = request.GET['id'] context = IdentityGatewayActions().read('user', params={ 'application_id': application_id }).record context['include_change_links'] = self.include_change_links( application_id) context['id'] = application_id return render(request, template_name='contact-details-summary.html', context=context)
def post(self, request): application_id = request.GET['id'] # Delete user information. NannyGatewayActions().delete('application', params={'application_id': application_id}) IdentityGatewayActions().delete( 'user', params={'application_id': application_id}) # Destroy session. variables = {'AUTHENTICATED': False} response = HttpResponseRedirect(reverse('Application-Cancelled'), variables) CustomAuthenticationHandler.destroy_session(response) return response
def get_context_data(self, **kwargs): kwargs = super(SecurityCodeFormView, self).get_context_data() application_id = self.request.GET['id'] record = IdentityGatewayActions().read('user', params={ 'application_id': application_id }).record kwargs['mobile_number_end'] = record['mobile_number'][-3:] kwargs[ 'application_id'] = application_id # Pass to context for the hyperlinks. kwargs['sms_resend_attempts'] = record['sms_resend_attempts'] # Template requires knowledge of whether or not the SMS was resent. # If they have come from email validation link, the request.META.get('HTTP_REFERER') is None. if self.request.META.get('HTTP_REFERER') is not None: kwargs['code_resent'] = True else: kwargs['code_resent'] = False return kwargs
def form_valid(self, form): application_id = app_id_finder(self.request) record = NannyGatewayActions().read('application', params={ 'application_id': application_id }).record record['information_correct_declare'] = form.cleaned_data[ 'confirm_declare'] record['date_updated'] = datetime.datetime.today() NannyGatewayActions().put('application', params=record) if record['application_status'] == 'FURTHER_INFORMATION': # TODO: create a list of updated tasks updated_list = generate_list_of_updated_tasks(record) # TODO: send a re-submission email pd_record = NannyGatewayActions().read( 'applicant-personal-details', params={ 'application_id': application_id }).record user_record = IdentityGatewayActions().read('user', params={ 'application_id': application_id }).record resubmission_confirmation_email(user_record['email'], record['application_reference'], pd_record['first_name'], updated_list) # TODO: clear statuses against Nanny application clear_arc_flagged_statuses(record) # TODO: redirect to resubmitted page self.success_url = 'declaration:confirmation' else: self.success_url = 'payment:gov-pay-send-handler' return super().form_valid(form)
def get_security_question_answer(self): application_id = self.request.GET['id'] if self.form_class == MobileNumberSecurityQuestionForm: return { 'mobile_number': IdentityGatewayActions().read('user', params={ 'application_id': application_id }).record['mobile_number'] } elif self.form_class == PersonalDetailsSecurityQuestionForm: personal_details_record = NannyGatewayActions().read( 'applicant-personal-details', params={ 'application_id': application_id }).record childcare_address_record = NannyGatewayActions().read( 'applicant-home-address', params={ 'application_id': application_id }).record return { 'date_of_birth': personal_details_record['date_of_birth'], 'postcode': childcare_address_record['postcode'], } elif self.form_class == DBSSecurityQuestionForm: return { 'dbs_number': NannyGatewayActions().read('dbs-check', params={ 'application_id': application_id }).record['dbs_number'] }
def _nanny_expiry_warnings(self, error_context): send_reminder_nanny = generate_expiring_applications_list_nanny_applications( ) for nanny_application in send_reminder_nanny: with error_context.sub(): if nanny_application['application_expiry_email_sent']: log.debug('Already sent') continue log.info( str(datetime.now()) + ' - Sending reminder email: ' + nanny_application['application_id']) log.info(nanny_application['application_id']) template_id = '3751bbf7-fbe7-4289-a3ed-6afbd2bab8bf' response = IdentityGatewayActions().read( 'user', params={ 'application_id': nanny_application['application_id'] }) if response.status_code != 200: raise ConnectionError(response.status_code) user = response.record response = NannyGatewayActions().read( 'applicant-personal-details', params={ 'application_id': nanny_application['application_id'] }) if response.status_code == 200: personal = response.record elif response.status_code == 404: personal = None else: raise ConnectionError(response.status_code) if personal and personal['first_name']: applicant_first_name = personal['first_name'] else: applicant_first_name = 'applicant' base_url = settings.NANNY_EMAIL_VALIDATION_URL user['magic_link_email'] = ''.join([ random.choice(string.ascii_letters + string.digits) for n in range(12) ]) user['magic_link_email'] = user['magic_link_email'].upper() # "expiry date" is actually creation time as epoch seconds user['email_expiry_date'] = int(time.time()) log.info((user, base_url, user['magic_link_email'])) personalisation = { "link": base_url + '/validate/' + user['magic_link_email'], "first_name": applicant_first_name } log.info(personalisation['link']) r = send_email(user['email'], personalisation, template_id, service_name='Nannies') if r.status_code not in (200, 201): raise ConnectionError(r.status_code) log.info(r) nanny_application['application_expiry_email_sent'] = True response = NannyGatewayActions().put('application', nanny_application) if response.status_code != 200: raise ConnectionError(response.status_code) response = IdentityGatewayActions().put('user', user) if response.status_code != 200: raise ConnectionError(response.status_code)
def get(self, request): email_address = request.GET['email_address'] application_id = request.GET['id'] # Create GatewayActions instances identity_actions = IdentityGatewayActions() nanny_actions = NannyGatewayActions() # Get relevant records user_identity_record = identity_actions.read('user', params={ 'application_id': application_id }).record # Get personal_details response, not record, and check if a record exists personal_details_response = nanny_actions.read( 'applicant-personal-details', params={'application_id': application_id}) try: personal_details_record_exists = personal_details_response.record is not None except AttributeError: personal_details_record_exists = False # Get first_name if it exists, otherwise use 'Applicant' if personal_details_record_exists: first_name = personal_details_response.record['first_name'] else: first_name = "Applicant" # Check if email already exists/in use existing_account_response = identity_actions.list('user', params={ 'email': email_address, 'service': 'NANNY' }) existing_account_response_status_code = existing_account_response.status_code email_in_use = existing_account_response_status_code == 200 if email_in_use: if settings.DEBUG: print( "You will not see an email validation link printed because an account already exists with that email." ) else: # Generate a new magic link and expiry date validation_link, email_expiry_date = utilities.generate_email_validation_link( email_address) magic_link = validation_link.split('/')[-1] validation_link += '?email=' + email_address # Create an update record with the magic_link information email_update_record = user_identity_record email_update_record['magic_link_email'] = magic_link email_update_record['email_expiry_date'] = email_expiry_date # Update the user record IdentityGatewayActions().put('user', params=email_update_record) # Send the 'Change Email' email if settings.DEBUG: print(validation_link) send_change_email_email(email_address, first_name, validation_link) return render(request, template_name='email-resent.html', context={ 'id': application_id, 'email_address': email_address })
def form_valid(self, form): if not utilities.test_notify(): return HttpResponseRedirect(reverse('Service-Unavailable')) application_id = self.request.GET.get('id') self.email_address = form.cleaned_data['email_address'] # Create GatewayActions instances identity_actions = IdentityGatewayActions() nanny_actions = NannyGatewayActions() # Get relevant records user_identity_record = identity_actions.read('user', params={ 'application_id': application_id }).record # Get personal_details response, not record, and check if a record exists personal_details_response = nanny_actions.read( 'applicant-personal-details', params={'application_id': application_id}) try: personal_details_record_exists = personal_details_response.record is not None except AttributeError: personal_details_record_exists = False # Get user's current email account_email = user_identity_record['email'] # Get first_name if it exists, otherwise use 'Applicant' if personal_details_record_exists: first_name = personal_details_response.record['first_name'] else: first_name = "Applicant" existing_account_response = identity_actions.list( 'user', params={ 'email': self.email_address, 'service': 'NANNY' }) existing_account_response_status_code = existing_account_response.status_code email_in_use = existing_account_response_status_code == 200 if self.email_address == account_email: # If email is unchanged, return to the sign-in details check-answers page same_email_redirect = utilities.build_url( self.check_answers_url, get={'id': application_id}) return HttpResponseRedirect(same_email_redirect) elif email_in_use: # If the email is already being used, if settings.DEBUG: print( "You will not see an email validation link printed because an account already exists with that email." ) not_sent_email_redirect = utilities.build_url( self.success_url, get={'id': application_id}) email_address = self.email_address return HttpResponseRedirect(not_sent_email_redirect) else: change_email = self.email_address # Generate a new magic link and expiry date validation_link, email_expiry_date = utilities.generate_email_validation_link( change_email) magic_link = validation_link.split('/')[-1] # Create an update record with the magic_link information email_update_record = user_identity_record email_update_record['magic_link_email'] = magic_link email_update_record['email_expiry_date'] = email_expiry_date email_update_record['change_email'] = change_email # Update the user record record = IdentityGatewayActions().put('user', params=email_update_record) # Send the 'Change Email' email if settings.DEBUG: print(validation_link) send_change_email_email(change_email, first_name, validation_link) sent_email_redirect = utilities.build_url( self.success_url, get={'id': application_id}) return HttpResponseRedirect(sent_email_redirect)