class AuthRegisterHandoutHandler(AuthBasehandler):
    """User Creation"""

    def get(self):
        kit_counts = ag_data.getMapMarkers()
        countries = ag_data.get_countries()

        # defaults entries dict to be empty
        entries = defaultdict(str)
        self.render("register_user.html", kit_counts=kit_counts,
                    loginerror='', countries=countries, entries=entries)

    def post(self):
        # Check handout
        skid = self.get_argument("kit_id").strip()
        password = self.get_argument("password")

        is_handout = ag_data.handoutCheck(skid, password)
        if not is_handout:
            kit_counts = ag_data.getMapMarkers()
            countries = ag_data.get_countries()
            entries = {'kit_id': self.get_argument('kit_id'),
                       'email': self.get_argument('email'),
                       'email2': self.get_argument('email2'),
                       'participantname': self.get_argument('participantname'),
                       'address': self.get_argument('address'),
                       'city': self.get_argument('city'),
                       'state': self.get_argument('state'),
                       'zip': self.get_argument('zip'),
                       'country': self.get_argument('country')}
            self.render("register_user.html", kit_counts=kit_counts,
                        loginerror='', countries=countries, entries=entries)
            return

        # Register handout
        tl = text_locale['handlers']
        info = {
            "email": self.get_argument("email"),
            "participantname": self.get_argument("participantname")
        }
        for info_column in ("address", "city", "state", "zip", "country"):
            # Make sure that all fields were entered
            info[info_column] = self.get_argument(info_column, None)

        # create the user if needed
        ag_login_id = ag_data.addAGLogin(
            info['email'], info['participantname'], info['address'],
            info['city'], info['state'], info['zip'], info['country'])
        # Create the kit and add the kit to the user
        success = ag_data.registerHandoutKit(ag_login_id, skid)
        if not success:
            self.redirect(media_locale['SITEBASE'] + '/db_error/?err=regkit')
            return

        # log user in since registered successfully
        self.set_current_user(skid)
        self.redirect(media_locale['SITEBASE'] + "/authed/portal/")

        kitinfo = ag_data.getAGKitDetails(skid)

        # Email the verification code
        # send email after redirect since it takes so long
        subject = tl['AUTH_SUBJECT']
        addendum = ''
        if skid.startswith('PGP_'):
            addendum = tl['AUTH_REGISTER_PGP']

        body = tl['AUTH_REGISTER_BODY'].format(
            kitinfo['kit_verification_code'], addendum)
        try:
            send_email(body, subject, recipient=info['email'],
                       sender=media_locale['HELP_EMAIL'])
        except BaseException:
            logging.exception('Error on skid %s:' % skid) class AuthLoginHandler(AuthBasehandler):
    """user login, no page necessary"""

    def get(self, *args, **kwargs):
        self.redirect(media_locale['SITEBASE'] + "/")

    def post(self):
        skid = self.get_argument("skid", "").strip()
        password = self.get_argument("password", "")
        tl = text_locale['handlers']

        is_handout = ag_data.handoutCheck(skid, password)
        if is_handout:
            # have them register themselves
            self.redirect(media_locale['SITEBASE'] + '/?loginerror=' +
                          tl['REGISTER_KIT'])
            return

        login = ag_data.authenticateWebAppUser(skid, password)
        if login:
            # everything good so log in
            self.set_current_user(skid)
            default_redirect = media_locale['SITEBASE'] + '/authed/portal/'
            self.redirect(self.get_argument('next', default_redirect))
            return
        else:
            msg = tl['INVALID_KITID']
            kit_counts = ag_data.getMapMarkers()
            self.render("index.html", user=None, loginerror=msg,
                        kit_counts=kit_counts)
            return class AuthLogoutHandler(AuthBasehandler):
    """Logout handler, no page necessary"""
    @authenticated
    def get(self):
        self.set_current_user()
        self.redirect(media_locale['SITEBASE'] + "/") class HelpRequestHandler(BaseHandler):
    @authenticated
    def get(self):
        self.render('help_request.html', skid=self.current_user, result='')

    @authenticated
    def post(self):
        email_address = self.get_argument('email_address')
        skid = self.current_user[-2:]  # last two letters of kit id
        first_name = self.get_argument('first_name')
        last_name = self.get_argument('last_name')
        message = self.get_argument('message_body')

        if email_address:
            SUBJECT = """AGHELP: %s %s %s""" % (first_name, last_name, skid)

            MESSAGE = """Contact: %s %s
            Reply to: %s
            --------------------------------------------------------------------------------
            Message:
            %s
            --------------------------------------------------------------------------------
            """ % (first_name, last_name, email_address, message)

            try:
                send_email(MESSAGE, SUBJECT, sender=email_address)
                result = media_locale["EMAIL_SENT"]
            except BaseException:
                result = media_locale['EMAIL_ERROR']

            self.render('help_request.html', skid=self.current_user,
                        result=result) class SampleOverviewHandler(BaseHandler):
    def _sample_overview_renderer(self):
        barcode = self.get_argument('barcode', None)
        if barcode is None:
            self.redirect(media_locale['SITEBASE'] + '/authed/portal/')
            return

        has_access = ag_data.check_access(self.current_user, barcode)
        if not has_access:
            self.set_status(403)
            self.render("403.html", skid=self.current_user)
            return

        sample_data = ag_data.getAGBarcodeDetails(barcode)

        if not sample_data:
            self.set_status(404)
            self.render("404.html", skid=self.current_user)
            return

        web_barcode_pdf, web_barcode_txt = _get_data_path(barcode)
        unidentified_results = _get_per_sample_results(barcode)
        per_sample_data = _get_per_sample_data(barcode)

        sample_time = sample_data['sample_time']
        sample_date = sample_data['sample_date']

        status = sample_data['status']
        if status is None:
            bgcolor = '#FFF'
            status = 'Submitted'
        elif status == 'Received':
            bgcolor = '#AFA'
        else:
            bgcolor = '#FFF'

        sample_origin = sample_data['site_sampled']
        if sample_origin is None:
            sample_origin = sample_data['environment_sampled']

        notes = sample_data['notes']
        if notes is None:
            notes = ''

        self.render('sample_overview.html', skid=self.current_user,
                    barcode_pdf=web_barcode_pdf, barcode_txt=web_barcode_txt,
                    bgcolor=bgcolor, status=status, barcode=barcode,
                    sample_origin=sample_origin, sample_date=sample_date,
                    sample_time=sample_time, notes=notes,
                    unidentified_results=unidentified_results,
                    per_sample_data=per_sample_data)

    @authenticated
    def get(self):
        self._sample_overview_renderer()

    @authenticated
    def post(self):
        bc_to_remove = self.get_argument("remove", None)
        if bc_to_remove:
            ag_login_id = ag_data.get_user_for_kit(self.current_user)
            ag_data.deleteSample(bc_to_remove, ag_login_id)
            self.redirect(media_locale['SITEBASE'] + "/authed/portal/")
            return

        self._sample_overview_renderer() class BasicReportHandler(BaseHandler):
    @authenticated
    def get(self, barcode):
        if barcode is None:
            self.redirect(media_locale['SITEBASE'] + '/authed/portal/')
            return

        has_access = ag_data.check_access(self.current_user, barcode)
        if not has_access:
            self.set_status(403)
            self.render("403.html", skid=self.current_user)
            return

        self.render('basic_report.html', skid=self.current_user,
                    barcode=barcode) class InteractiveReportHandler(BaseHandler):
    @authenticated
    def get(self, barcode):
        if barcode is None:
            self.redirect(media_locale['SITEBASE'] + '/authed/portal/')
            return

        has_access = ag_data.check_access(self.current_user, barcode)
        if not has_access:
            self.set_status(403)
            self.render("403.html", skid=self.current_user)
            return

        self.render('interactive_report.html', skid=self.current_user,
                    barcode=barcode) class IntroductionHandler(BaseHandler):
    page = 'introduction.html'

    def get(self):
        self.render(self.page, loginerror='') class AnimalSurveyHandler(BaseHandler):
    animal_survey = make_survey_class(primary_animal_survey.groups[0],
                                      survey_type='AnimalSurvey')

    @authenticated
    def get(self):
        skid = self.current_user
        survey_id = self.get_argument('survey', '')

        form = self.animal_survey()
        if survey_id:
            form.process(data=primary_animal_survey.fetch_survey(survey_id))
        self.render('animal_survey.html', skid=skid,
                    the_form=form, survey_id=survey_id)

    @authenticated
    def post(self):
        skid = self.current_user
        tl = text_locale['handlers']
        ag_login_id = ag_data.get_user_for_kit(skid)
        ag_login_info = ag_data.get_login_info(ag_login_id)[0]
        animal_survey_id = self.get_argument('survey_id', None)
        sitebase = media_locale['SITEBASE']

        form = self.animal_survey()
        form.process(data=self.request.arguments)
        data = {'questions': form.data}
        participant_name = form['Pet_Information_127_0'].data[0]

        if not animal_survey_id:
            animal_survey_id = ag_data.get_new_survey_id()

            new_survey = True
        else:
            new_survey = False

        # If the participant already exists, stop them outright
        if new_survey and \
                ag_data.check_if_consent_exists(ag_login_id, participant_name):
            errmsg = url_escape(tl['PARTICIPANT_EXISTS'] % participant_name)
            url = sitebase + "/authed/portal/?errmsg=%s" % errmsg
            self.redirect(url)
            return

        consent = {
            'login_id': ag_login_id,
            'participant_name': participant_name,
            'participant_email': ag_login_info['email'],
            'assent_obtainer': 'ANIMAL_SURVEY',
            'parent_1_name': 'ANIMAL_SURVEY',
            'parent_2_name': 'ANIMAL_SURVEY',
            'survey_id': animal_survey_id,
            'is_juvenile': True,
            'deceased_parent': False,
            'obtainer_name': 'ANIMAL_SURVEY',
            'age_range': 'ANIMAL_SURVEY'
        }
        redis.hset(animal_survey_id, 'consent', dumps(consent))
        redis.hset(animal_survey_id, 0, dumps(data))
        redis.expire(animal_survey_id, 86400)

        store_survey(primary_animal_survey, animal_survey_id)
        if not new_survey:
            message = urlencode([('errmsg', tl['SUCCESSFULLY_EDITED'] %
                                 participant_name)])
        else:
            message = urlencode([('errmsg', tl['SUCCESSFULLY_ADDED'] %
                                 participant_name)])

        url = sitebase + '/authed/portal/?%s' % message
        self.redirect(url) class CheckParticipantName(WebSocketHandler, BaseHandler):
    @authenticated
    def on_message(self, msg):
        tl = text_locale['handlers']
        skid = self.current_user
        participant_name = msg

        ag_login_id = ag_data.get_user_for_kit(skid)
        human_participants = ag_data.getHumanParticipants(ag_login_id)
        animal_participants = ag_data.getAnimalParticipants(ag_login_id)

        if participant_name in (human_participants + animal_participants):
            # if the participant already exists in the system, fail nicely
            output_message = (tl['PARTICIPANT_EXISTS'] % participant_name)
        else:
            # otherwise, success!
            output_message = 'success'

        self.write_message(output_message) class HumanSurveyHandler(BaseHandler):
    @authenticated
    def post(self):
        # see if we're coming from an edit
        human_survey_id = self.get_argument('survey_id', None)
        page_number = int(self.get_argument('page_number'))
        sitebase = media_locale['SITEBASE']

        if human_survey_id is None:
            # we came from consent
            human_survey_id = self.get_secure_cookie('human_survey_id')
            if human_survey_id is None:
                err_msg = url_escape("There was an unexpected error.")
                self.redirect(sitebase + "/authed/portal/?errmsg=%s" % err_msg)
                return
        else:
            # we came from participant_overview
            consent = ag_data.getConsent(human_survey_id)
            # make sure is string so can be serialized
            consent['date_signed'] = str(consent['date_signed'])
            self.set_secure_cookie('human_survey_id', human_survey_id)
            data = primary_human_survey.fetch_survey(human_survey_id)
            redis.hset(human_survey_id, 'consent', dumps(consent))
            redis.hset(human_survey_id, 'existing', dumps(data))
            redis.expire(human_survey_id, 86400)

        next_page_number = page_number + 1

        if page_number >= 0:
            form_data = surveys[page_number]()
            form_data.process(data=self.request.arguments)
            data = {'questions': form_data.data}

            redis.hset(human_survey_id, page_number, dumps(data))

        progress = int(100.0 * (page_number + 2) / (len(phs_groups) + 1))

        # if this is not the last page, render the next page
        if next_page_number < len(surveys):
            the_form = surveys[next_page_number]()

            existing_responses = redis.hget(human_survey_id, 'existing')
            if existing_responses:
                existing_responses = loads(existing_responses)
                the_form = surveys[next_page_number](data=existing_responses)

            title = phs_groups[next_page_number].name

            self.render('human_survey.html', the_form=the_form,
                        skid=self.current_user, TITLE=title,
                        page_number=next_page_number,
                        progress=progress)
        else:
            # only get the cookie if you complete the survey
            self.clear_cookie('human_survey_id')
            self.set_secure_cookie('completed_survey_id', human_survey_id)
            store_survey(primary_human_survey, human_survey_id)
            existing = redis.hget(human_survey_id, 'existing')
            if existing is None:
                # Send consent info email since new participant
                consent_info = ag_data.getConsent(human_survey_id)
                try:
                    message = build_consent_form(consent_info)
                    send_email(message, 'American Gut-Signed Consent Form(s)',
                               recipient=consent_info['participant_email'],
                               sender='donotreply@americangut.com', html=True)
                except BaseException:
                    logging.exception('Error sending signed consent form for '
                                      'survey ID: %s to email: %s' %
                                      (human_survey_id,
                                       consent_info['participant_email']))
            self.redirect(sitebase + '/authed/human_survey_completed/')

    @authenticated
    def get(self, *args, **kwargs):
        self.redirect(media_locale['SITEBASE'] + "/") class HumanSurveyCompletedHandler(BaseHandler):
    @authenticated
    def get(self):
        human_survey_id = self.get_secure_cookie('completed_survey_id')

        if human_survey_id is None:
            self.clear_cookie('completed_survey_id')
            self.redirect(media_locale['SITEBASE'] + '/authed/portal/')

        else:
            consent_info = ag_data.getConsent(human_survey_id)
            internal_surveys = ag_data.get_participants_surveys(
                consent_info['ag_login_id'], consent_info['participant_name'])
            surveys = [f(human_survey_id, consent_info, internal_surveys)
                       for f in external_surveys]

            self.render('human_survey_completed.html', skid=self.current_user,
                        surveys=surveys)

    @authenticated
    def post(self):
        self.clear_cookie('completed_survey_id')
        self.redirect(media_locale['SITEBASE'] + '/authed/portal/') class AddHumanSampleHandler(AddSample):
    _sample_sites = ag_data.human_sites
    page_type = 'add_sample_human' class AddHumanFFQHandler(BaseHandler):
    @authenticated
    def post(self):
        self.redirect(media_locale['SITEBASE'] + '/authed/portal/')

    @authenticated
    def get(self):
        ag_login_id = ag_data.get_user_for_kit(self.current_user)
        barcode = self.get_secure_cookie('barcode')
        participant_name = self.get_secure_cookie('participant_name')
        self.clear_cookie('barcode')
        self.clear_cookie('participant_name')

        if barcode is None or participant_name is None:
            self.set_status(404)
            self.redirect(media_locale['SITEBASE'] + '/authed/portal/')
            return
        else:
            barcode = escape.json_decode(barcode)
            participant_name = escape.json_decode(participant_name)

        new_survey_id = ag_data.get_new_survey_id()
        ag_data.associate_barcode_to_survey_id(ag_login_id, participant_name,
                                               barcode, new_survey_id)
        ag_data.updateVioscreenStatus(new_survey_id, 0)  # 0 -> not started
        dat = survey_vioscreen(new_survey_id, None, None)

        self.render('human_sample_specific_survey.html',
                    skid=self.current_user,
                    surveys=[dat]) class AddGeneralSampleHandler(AddSample):
    _sample_sites = ag_data.general_sites
    page_type = 'add_sample_general' class AddAnimalSampleHandler(AddSample):
    _sample_sites = ag_data.animal_sites
    page_type = 'add_sample_animal' class NewParticipantHandler(BaseHandler):
    """"""
    @authenticated
    def get(self):
        self.render("new_participant.html", skid=self.current_user, message='')

    @authenticated
    def post(self):
        tl = text_locale['handlers']
        participant_name = self.get_argument("participant_name").strip()
        participant_email = self.get_argument("participant_email").strip()
        age_range = self.get_argument("age_range")
        parent_1_name = self.get_argument("parent_1_name", None)
        parent_2_name = self.get_argument("parent_2_name", None)
        obtainer_name = self.get_argument("obtainer_name", None)
        deceased_parent = self.get_argument("deceased_parent", 'No')
        sitebase = media_locale['SITEBASE']

        if not participant_name or not participant_email:
            self.render("new_participant.html", skid=self.current_user,
                        message=tl['MISSING_NAME_EMAIL'])
            return

        ag_login_id = ag_data.get_user_for_kit(self.current_user)

        # If the participant already exists, stop them outright
        if ag_data.check_if_consent_exists(ag_login_id, participant_name):
            errmsg = url_escape(tl['PARTICIPANT_EXISTS'] % participant_name)
            url = sitebase + "/authed/portal/?errmsg=%s" % errmsg
            self.redirect(url)
            return

        human_survey_id = ag_data.get_new_survey_id()

        consent = {'participant_name': participant_name,
                   'participant_email': participant_email,
                   'parent_1_name': parent_1_name,
                   'parent_2_name': parent_2_name,
                   'is_juvenile': True if age_range != '18-plus' else False,
                   'deceased_parent': deceased_parent,
                   'obtainer_name': obtainer_name,
                   'age_range': age_range,
                   'login_id': ag_login_id,
                   'survey_id': human_survey_id}

        redis.hset(human_survey_id, 'consent', dumps(consent))
        redis.expire(human_survey_id, 86400)

        self.set_secure_cookie('human_survey_id', human_survey_id)
        self.redirect(sitebase + "/authed/survey_main/") class SecondarySurveyHandler(BaseHandler):
    sec_surveys = {'fermented': fermented_survey,
                   'surf': surf_survey,
                   'personal_microbiome': personal_microbiome_survey}

    @authenticated
    def get(self):
        skid = self.current_user
        survey_id = self.get_argument('survey', '')
        survey_type = self.get_argument('type')
        participant_name = url_unescape(self.get_argument('participant_name'))

        sec_survey = self.sec_surveys[survey_type]
        survey_class = make_survey_class(sec_survey.groups[0],
                                         survey_type='SecondarySurvey')

        form = survey_class()
        if survey_id:
            form.process(data=sec_survey.fetch_survey(survey_id))

        # load existing information into the form
        if survey_id != '':
            data = sec_survey.fetch_survey(survey_id)
            form = survey_class(data=data)

        self.render('secondary_survey.html', skid=skid,
                    the_form=form, survey_id=survey_id,
                    type=survey_type, participant_name=participant_name)

    @authenticated
    def post(self):
        skid = self.current_user
        tl = text_locale['handlers']
        ag_login_id = ag_data.get_user_for_kit(skid)
        survey_id = self.get_argument('survey_id', None)
        survey_type = self.get_argument('type')
        participant_name = url_unescape(self.get_argument('participant_name'))
        sitebase = media_locale['SITEBASE']

        if not survey_id:
            survey_id = ag_data.get_new_survey_id()

        sec_survey = self.sec_surveys[survey_type]
        survey_class = make_survey_class(sec_survey.groups[0],
                                         survey_type='SecondarySurvey')

        form = survey_class()
        form.process(data=self.request.arguments)
        data = {'questions': form.data}

        consent = {
            'login_id': ag_login_id,
            'participant_name': participant_name,
            'survey_id': survey_id,
            'secondary': True
        }
        redis.hset(survey_id, 'consent', dumps(consent))
        redis.hset(survey_id, 0, dumps(data))
        redis.expire(survey_id, 86400)

        store_survey(sec_survey, survey_id)
        if survey_id:
            message = urlencode([('errmsg', tl['SUCCESSFULLY_EDITED'] %
                                 participant_name)])
        else:
            message = urlencode([('errmsg', tl['SUCCESSFULLY_ADDED'] %
                                 participant_name)])

        url = '%s/authed/portal/?%s' % (sitebase, message)
        self.redirect(url) class PersonalMicrobiomeOverviewHandler(BaseHandler):
    """"""
    @authenticated
    def get(self):
        participant_name = self.get_argument('participant_name')
        self.render("personal_microbiome_overview.html",
                    skid=self.current_user,
                    participant_name=participant_name) class PortalHandler(BaseHandler):
    @authenticated
    def get(self):
        errmsg = self.get_argument('errmsg', "")
        kit_id = self.current_user

        user_info = ag_data.get_user_info(kit_id)

        if not user_info:
            self.redirect(media_locale['SITEBASE'] + '/auth/logout/')
            return

        user_name = user_info['name']

        kit_details = ag_data.getAGKitDetails(kit_id)
        kit_verified = True if kit_details['kit_verified'] == 'y' else False

        results = ag_data.get_barcode_results(kit_id)
        has_results = len(results) != 0

        barcodes = ag_data.getBarcodesByKit(kit_id)

        kit_ver_error = False
        verification_textbox = ''
        unconsented = ag_data.get_nonconsented_scanned_barcodes(kit_id)

        self.render("portal.html", skid=kit_id, user_name=user_name,
                    errmsg=errmsg, kit_verified=kit_verified,
                    has_results=has_results, results=results,
                    barcodes=barcodes, kit_ver_error=kit_ver_error,
                    verification_textbox=verification_textbox,
                    unconsented=unconsented)

    @authenticated
    def post(self):
        kit_id = self.current_user
        errmsg = self.get_argument('errmsg', "")
        user_code = self.get_argument('user_verification_code', "")
        kit_details = ag_data.getAGKitDetails(kit_id)
        barcodes = ag_data.getBarcodesByKit(kit_id)
        user_info = ag_data.get_user_info(kit_id)
        user_name = user_info['name']
        results = ag_data.get_barcode_results(kit_id)
        has_results = len(results) != 0
        unconsented = ag_data.get_nonconsented_scanned_barcodes(kit_id)

        kit_verified = True if kit_details['kit_verified'] == 'y' else False

        if not kit_verified and user_code == "":
            # Resend kit verification code
            tl = text_locale['handlers']
            subject = tl['AUTH_SUBJECT']
            addendum = ''
            if self.current_user.startswith('PGP_'):
                addendum = tl['AUTH_REGISTER_PGP']

            body = tl['AUTH_REGISTER_BODY'].format(
                kit_details['kit_verification_code'], addendum)

            kit_ver_error = False
            verification_textbox = ''
            try:
                send_email(body, subject, recipient=user_info['email'],
                           sender=media_locale['HELP_EMAIL'])
            except BaseException:
                errmsg = media_locale['EMAIL_ERROR']
        else:
            # Verify the given kit verification code
            if kit_details['kit_verification_code'] == user_code:
                ag_data.verifyKit(kit_id)
                kit_ver_error = False
                verification_textbox = ''
            else:
                kit_ver_error = True
                verification_textbox = ' highlight'

        self.render("portal.html", skid=kit_id, user_name=user_name,
                    errmsg=errmsg, kit_verified=kit_verified,
                    has_results=has_results, results=results,
                    barcodes=barcodes,
                    verification_textbox=verification_textbox,
                    kit_ver_error=kit_ver_error, unconsented=unconsented) class KitIDHandler(BaseHandler):
    def get(self):
        kit_counts = ag_data.getMapMarkers()
        self.render('retrieve_kitid.html', message='', output='form',
                    loginerror='', kit_counts=kit_counts)

    def post(self):
        kit_counts = ag_data.getMapMarkers()
        email = self.get_argument('email')
        tl = text_locale['handlers']
        if email:
            kitids = ag_data.getAGKitIDsByEmail(email)
        try:
            if len(kitids) > 0:
                MESSAGE = tl['KIT_IDS_BODY'] % ", ".join(kitids)
                try:
                    send_email(MESSAGE, tl['KIT_IDS_SUBJECT'], email)
                    self.render('retrieve_kitid.html', message='',
                                output='success', loginerror='',
                                kit_counts=kit_counts)
                except BaseException:
                    self.render('retrieve_kitid.html', message=MESSAGE,
                                output='noemail', loginerror='',
                                kit_counts=kit_counts)
            else:
                self.render('retrieve_kitid.html', message='nokit',
                            output='form', loginerror='',
                            kit_counts=kit_counts)

        except BaseException:
            self.render('retrieve_kitid.html', message='', output='exception',
                        loginerror='', kit_counts=kit_counts) class ForgotPasswordHandler(BaseHandler):
    def get(self):
        email = self.get_argument('email', None)
        kitid = self.get_argument('kitid', None)
        kit_counts = ag_data.getMapMarkers()
        self.render('forgot_password.html', email=email, kitid=kitid,
                    result=None, messaage='',
                    kit_counts=kit_counts, loginerror='')

    def post(self):
        email = self.get_argument('email', None)
        kitid = self.get_argument('kitid', None)
        self.create_passcode_and_send_email(email, kitid)

    def create_passcode_and_send_email(self, email, kit_id):
        kitids = ag_data.getAGKitIDsByEmail(email)
        kit_counts = ag_data.getMapMarkers()
        tl = text_locale['handlers']
        # if the kit id matches the email generate and send an email
        if kit_id in kitids:
            alphabet = letters + digits
            new_act_code = ''.join([choice(alphabet) for i in range(20)])
            # add new pass to the database
            ag_data.ag_set_pass_change_code(email, kit_id, new_act_code)
            MESSAGE = (tl['RESET_PASS_BODY'] % (kit_id, quote(email), kit_id,
                                                quote(new_act_code)))

            # send the user an email and tell them to change their password
            try:
                send_email(MESSAGE, tl['CHANGE_PASS_SUBJECT'], email)
                self.render('forgot_password.html', email='', kitid='',
                            result=1, message='',
                            kit_counts=kit_counts, loginerror='')
            except BaseException:
                self.render('forgot_password.html', email='', kitid='',
                            result=2, message=MESSAGE,
                            kit_counts=kit_counts, loginerror='')

        else:
            self.render('forgot_password.html', email='', kitid='',
                        result=3, message='',
                        kit_counts=kit_counts, loginerror='') class ChangePassVerifyHandler(BaseHandler):

    def get(self):
        email = self.get_argument('email', None)
        if email is not None:
            email = unquote(email)
        kitid = self.get_argument('kitid', None)
        passcode = self.get_argument('passcode', None)
        new_password = self.get_argument('new_password', None)
        confirm_password = self.get_argument('confirm_password', None)

        if self.is_valid(email, kitid, passcode):
            result = 'valid'
        else:
            result = 'notvalid'
        kit_counts = ag_data.getMapMarkers()
        self.render('change_pass_verify.html', email=email, kitid=kitid,
                    passcode=passcode, new_password=new_password,
                    confirm_password=confirm_password,
                    result=result, message=None, kit_counts=kit_counts,
                    loginerror='')

    def post(self):
        email = self.get_argument('email', None)
        kit_id = self.get_argument('kitid', None)
        if email is not None:
            email = unquote(email)
        new_password = self.get_argument('new_password', None)
        confirm_password = self.get_argument('confirm_password', None)
        self.reset_pass_and_email(new_password, confirm_password, email,
                                  kit_id)

    def is_valid(self, email, kitid, passcode):
        return ag_data.ag_verify_kit_password_change_code(email, kitid,
                                                          passcode)

    def reset_pass_and_email(self, new_password, confirm_password, email,
                             supplied_kit_id):
        ag_data.ag_update_kit_password(supplied_kit_id, new_password)
        kit_counts = ag_data.getMapMarkers()
        tl = text_locale['handlers']
        MESSAGE = tl['CHANGE_PASS_BODY'] % supplied_kit_id
        try:
            send_email(MESSAGE, tl['CHANGE_PASS_SUBJECT'], email)
            # result=4 is for showing message in if statement of
            # change_pass_verify.html
            self.render('change_pass_verify.html', email='', kitid='',
                        passocde='', new_password='',
                        confirm_password='', result=4, message='',
                        kit_counts=kit_counts, loginerror='')
        except BaseException:
            # result=5 is for showing message in if statement of
            # change_pass_verify.html
            self.render('change_pass_verify.html', email='', kitid='',
                        passocde='', new_password='',
                        confirm_password='', result=5, message='',
                        kit_counts=kit_counts, loginerror='') class ChangePasswordHandler(BaseHandler):
    @authenticated
    def get(self):
        user_info = ag_data.get_user_info(self.current_user)
        self.render('change_password.html', email=user_info['email'],
                    skid=self.current_user, new_password=None,
                    confirm_password=None, result='valid', message=None)

    @authenticated
    def post(self):
        email = self.get_argument('email', None)
        if email is not None:
            email = unquote(email)
        new_password = self.get_argument('new_password', None)
        confirm_password = self.get_argument('confirm_password', None)
        self.reset_pass_and_email(new_password, confirm_password, email,
                                  self.current_user)

    def reset_pass_and_email(self, new_password, confirm_password, email,
                             supplied_kit_id):
        tl = text_locale['handlers']
        ag_data.ag_update_kit_password(supplied_kit_id, new_password)
        MESSAGE = tl['CHANGE_PASS_BODY'] % supplied_kit_id
        try:
            send_email(MESSAGE, tl['CHANGE_PASS_SUBJECT'], email)
            self.render('change_password.html', email='',
                        skid=self.current_user,
                        new_password='', confirm_password='', result=4,
                        message='')
        except BaseException:
            self.render('change_password.html', email='',
                        skid=self.current_user,
                        new_password='', confirm_password='', result=5,
                        message='')
from os.path import dirname, join
from tornado.httpserver import HTTPServer
from tornado.ioloop import IOLoop
from tornado.web import Application
from tornado.options import define, options, parse_command_line
from amgut import media_locale
from amgut.handlers.base_handlers import (
    MainHandler, NoPageHandler, DBErrorHandler, BaseStaticFileHandler)
from amgut import AMGUT_CONFIG
from amgut.handlers.auth_handlers import (
    AuthRegisterHandoutHandler, AuthLoginHandler, AuthLogoutHandler)
from amgut.handlers.help_request import HelpRequestHandler
from amgut.handlers.addendum import AddendumHandler
from amgut.handlers.sample_overview import SampleOverviewHandler
from amgut.handlers.basic_report import BasicReportHandler
from amgut.handlers.interactive_report import InteractiveReportHandler
from amgut.handlers.FAQ import FAQHandler
from amgut.handlers.introduction import IntroductionHandler
from amgut.handlers.participant_overview import ParticipantOverviewHandler
from amgut.handlers.international import InternationalHandler
from amgut.handlers.animal_survey import (AnimalSurveyHandler,
                                          CheckParticipantName)
from amgut.handlers.human_survey import HumanSurveyHandler
from amgut.handlers.human_survey_completed import HumanSurveyCompletedHandler
from amgut.handlers.vioscreen import VioscreenPassthroughHandler
from amgut.handlers.add_sample import (AddHumanSampleHandler,
                                       AddHumanFFQHandler,
                                       AddGeneralSampleHandler,
                                       AddAnimalSampleHandler)
from amgut.handlers.new_participant import NewParticipantHandler
from amgut.handlers.new_participant_overview import (
    NewParticipantOverviewHandler)
from amgut.handlers.taxa_summary import TaxaSummaryHandler
from amgut.handlers.survey import SurveyMainHandler
from amgut.handlers.secondary_survey import SecondarySurveyHandler
from amgut.handlers.personal_microbiome_overview import \
        PersonalMicrobiomeOverviewHandler
from amgut.handlers.portal import PortalHandler
from amgut.handlers.retrieve_kitid import KitIDHandler
from amgut.handlers.forgot_password import ForgotPasswordHandler
from amgut.handlers.add_sample_overview import AddSampleOverviewHandler
from amgut.handlers.change_pass_verify import ChangePassVerifyHandler
from amgut.handlers.change_password import ChangePasswordHandler
from amgut.handlers.nojs import NoJSHandler
from amgut.handlers.download import DownloadHandler
from amgut.handlers.open_humans import (OpenHumansHandler,
                                        OpenHumansLoginHandler)
from amgut.lib.startup_tests import startup_tests
#!/usr/bin/env python







define("port", default=8888, help="run on the given port", type=int)


DIRNAME = dirname(__file__)
STATIC_PATH = join(DIRNAME, "static")
TEMPLATE_PATH = join(DIRNAME, "templates")  # base folder for webpages
RES_PATH = join(DIRNAME, "results")
DEBUG = True


class AGWebApplication(Application):
    def __init__(self):
        handlers = [
            (r"/static/(.*)", BaseStaticFileHandler, {"path": STATIC_PATH}),
            (r"/", MainHandler),
            (r"/db_error/", DBErrorHandler),
            (r"/auth/login/", AuthLoginHandler),
            (r"/auth/logout/", AuthLogoutHandler),
            (r"/auth/register/", AuthRegisterHandoutHandler),
            (r"/authed/help_request/", HelpRequestHandler),
            (r"/authed/addendum/", AddendumHandler),
            (r"/authed/new_participant/", NewParticipantHandler),
            (r"/authed/new_participant_overview/",
             NewParticipantOverviewHandler),
            (r"/authed/sample_overview/", SampleOverviewHandler),
            (r"/authed/add_sample_overview/", AddSampleOverviewHandler),
            (r"/authed/survey_main/", SurveyMainHandler),
            (r"/authed/human_survey/", HumanSurveyHandler),
            (r"/authed/human_survey_completed/", HumanSurveyCompletedHandler),
            (r"/authed/vspassthrough/", VioscreenPassthroughHandler),
            (r"/authed/secondary_survey/", SecondarySurveyHandler),
            (r"/authed/personal_microbiome_overview/",
             PersonalMicrobiomeOverviewHandler),
            (r"/authed/portal/", PortalHandler),
            (r"/authed/add_sample_human/", AddHumanSampleHandler),
            (r"/authed/add_sample_human_ffq/", AddHumanFFQHandler),
            (r"/authed/add_sample_animal/", AddAnimalSampleHandler),
            (r"/authed/add_sample_general/", AddGeneralSampleHandler),
            (r"/authed/change_password/", ChangePasswordHandler),
            (r"/authed/add_animal/", AnimalSurveyHandler),
            (r"/authed/open-humans/", OpenHumansHandler),
            (r"/authed/connect/open-humans/", OpenHumansLoginHandler),
            (r"/authed/download/(.*)", DownloadHandler),
            (r"/faq/", FAQHandler),
            (r"/introduction/", IntroductionHandler),
            (r"/participants/(.*)", ParticipantOverviewHandler),
            (r"/international_shipping/", InternationalHandler),

            (r"/check_participant_name/", CheckParticipantName),