def add_group(api, assessment_id):
    """Create a test group."""
    logging.info("Adding Test Group")

    newGroup = Group()

    newGroup.name = "Test-" + assessment_id

    # Holds list of Users to be added to group.
    targets = list()

    target = User()
    target.first_name = get_input("Enter First Name: ")
    # Receives the file name and checks if it exists.
    while target.first_name != "done" or target.first_name == "":

        target.last_name = get_input("Enter Last Name: ")

        while True:
            target.email = get_input("Enter Email: ")
            if not validate_email(target.email):
                print("In Valid Email")
            else:
                break

        target.position = get_input("Enter Org: ")

        targets.append(target)

        target = User()
        target.first_name = get_input("Enter First Name or 'done': ")

    newGroup.targets = targets

    newGroup = api.groups.post(newGroup)

    return newGroup.name
Beispiel #2
0
def build_emails(domains, labels):
    """Build emails."""
    # Holds list of Users to be added to group.
    targets = list()
    domain_miss_match = list()
    format_error = list()

    # Receives the file name and checks if it exists.
    while True:
        try:
            email_file_name = get_input("    E-mail CSV name:")
            # Drops .csv if included so it can always be added as fail safe.
            email_file_name = email_file_name.split(".", 1)[0]

            with open(email_file_name + ".csv") as csv_file:
                read_csv = csv.reader(csv_file, delimiter=",")
                next(read_csv)

                for row in read_csv:
                    # Checks e-mail format, if false prints message.
                    if not validate_email(row[2]):
                        format_error.append(row)
                    # Checks that the domain matches, if false prints message,
                    elif not validate_domain(row[2], domains):
                        domain_miss_match.append(row)

                    else:
                        target = Target(first_name=row[0],
                                        last_name=row[1],
                                        email=row[2])
                        target = target_add_label(labels, row, target)
                        targets.append(target)

                # Works through emails found to include formatting errors.
                print("\n")
                if len(format_error) < 2:
                    for email in format_error:
                        email[2] = prompt(
                            "Correct Email Formatting: ",
                            default=email[2],
                            validator=EmailValidator(),
                        )
                        if not validate_domain(email[2], domains):
                            domain_miss_match.append(email)
                        else:
                            target = Target(first_name=email[0],
                                            last_name=email[1],
                                            email=email[2])
                            target = target_add_label(labels, email, target)
                            targets.append(target)
                else:
                    logging.error("{} Formatting Errors".format(
                        len(format_error)))
                    if yes_no_prompt(
                            "Would you like to correct each here") == "yes":
                        for email in format_error:
                            email[2] = prompt(
                                "Correct Email Formatting: ",
                                default=email[2],
                                validator=EmailValidator(),
                            )
                            if not validate_domain(email[2], domains):
                                domain_miss_match.append(email)
                            else:
                                target = Target(first_name=row[0],
                                                last_name=row[1],
                                                email=row[2])
                                target = target_add_label(
                                    labels, email, target)
                                targets.append(target)
                    else:
                        logging.warning(
                            "Incorrectly formatted Emails will not be added, continuing..."
                        )

                # Works through emails found to have domain miss match.
                if len(domain_miss_match) < 2:
                    for email in domain_miss_match:
                        email[2] = prompt(
                            "Correct Email Domain: ",
                            default=email[2],
                            validator=EmailValidator(),
                        )
                else:
                    logging.error("{} Domain Miss Match Errors".format(
                        len(format_error)))
                    if yes_no_prompt(
                            "Would you like to correct each here") == "yes":
                        for email in domain_miss_match:
                            while True:
                                email[2] = prompt(
                                    "Correct Email Domain: ",
                                    default=email[2],
                                    validator=EmailValidator(),
                                )
                                if validate_domain(email[2], domains):
                                    target = Target(
                                        first_name=row[0],
                                        last_name=row[1],
                                        email=row[2],
                                    )
                                    target = target_add_label(
                                        labels, email, target)
                                    targets.append(target)
                                    break
                    else:
                        logging.warning(
                            "Incorrectly formatted Emails will not be added, continuing..."
                        )

            if len(targets) == 0:
                raise Exception("No targets loaded")
            break
        except EnvironmentError:
            logging.critical(
                "Email File not found: {}.csv".format(email_file_name))
            print("\t Please try again...")
        except Exception:
            # Logs and indicates the user should correct before clicking ok which will re-run the import.
            logging.critical("No targets loaded")
            message_dialog(
                title="Missing Targets",
                text=
                "No targets loaded from file, please check file before clicking Ok.",
            )
            continue

    return targets
def add_new_user():
    data = request.json
    new = {}
    for obj in data:
        if obj['name'] not in new:
            new[obj['name']] = obj['value']
        elif isinstance(new[obj['name']], list):
            new[obj['name']].append(obj['value'])
        else:
            new[obj['name']] = [new[obj['name']], obj['value']]
    data = new
    rtoken = data['g-recaptcha-response']
    data.pop('g-recaptcha-response')

    recaptcha = post("https://www.google.com/recaptcha/api/siteverify",
                     data={
                         'secret': environ['recaptcha-secret-key'],
                         'response': rtoken
                     }).json()
    if not recaptcha['success'] and recaptcha['score'] < 0.5:
        return Response(status=403)

    service_map = {
        "1": "General Instruction",
        "2": "Standardized Testing Preparation",
        "3": "College Admissions Consultation",
        "4": "Personal Profile Development",
        "5": "Other"
    }
    i = 0
    if isinstance(data['service'], list):
        for service in data['service']:
            data['service'][i] = service_map[service]
            i += 1
    else:
        data['service'] = service_map[data['service']]
    data['type'] = "Parent" if data['type'] == 1 else "Student"
    if validate_email(data['email']) and validate_phone(data['phone']):
        try:
            new_id = data['fullname'].replace(" ", "") + str(int(time.time()))
            db.collection(u'registrants').document(new_id).set(data)
            send_email(
                "New Student, " + new_id, """
            New registrant
            Firebase ID: {}
            Full Name: {}
            Email: {}
            Phone: {}
            Type: {}
            Grade: {}
            Services: {}
            Resume: {}
            Other Questions: {}
            """.format(new_id, data['fullname'], data['email'], data['phone'],
                       data['type'], data['grade'], data['service'],
                       data['resume'], data['questions']), "*****@*****.**")
            return Response(status=200)
        except Exception as e:
            traceback.print_exc(file=sys.stdout)
            return Response(status=500)
    else:
        return Response(status=422)
def validate_requested_email():
    return validate_email(request.args.get("email"))
Beispiel #5
0
def test_validate_email_invalid(email):
    """Test an invalid email address."""
    with pytest.raises(FormatError):
        validate_email(email)
Beispiel #6
0
def test_validate_email_valid(email):
    """Test a valid email address."""
    assert validate_email(email)