コード例 #1
0
    def register():  # register
        def error(msg):
            return {"success": False, "data": msg}

        name = request.json.get("name", "").strip()
        email_address = request.json.get("email", "").strip().lower()
        password = request.json.get("password", "").strip()

        name_len = len(name) == 0
        names = Users.query.add_columns(
            "name", "id").filter_by(name=name).first()
        emails = (
            Users.query.add_columns("email", "id")
                .filter_by(email=email_address)
                .first()
        )
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = validators.validate_email(email_address)
        team_name_email_check = validators.validate_email(name)

        if not valid_email:
            return error("Please enter a valid email address")
        if email.check_email_is_whitelisted(email_address) is False:
            return error("Only email addresses under {domains} may register".format(
                domains=get_config("domain_whitelist")
            ))
        if names:
            return error("That user name is already taken")
        if team_name_email_check is True:
            return error("Your user name cannot be an email address")
        if emails:
            return error("That email has already been used")
        if pass_short:
            return error("Pick a longer password")
        if pass_long:
            return error("Pick a shorter password")
        if name_len:
            return error("Pick a longer user name")

        with app.app_context():
            user = Users(name=name, email=email_address, password=password)
            db.session.add(user)
            db.session.commit()
            db.session.flush()
            login_user(user)
            if config.can_send_mail() and get_config(
                    "verify_emails"
            ):
                email.verify_email_address(user.email)
                db.session.close()
                return {"success": True, "data": url_for("auth.confirm")}
            else:
                if (config.can_send_mail()):
                    email.successful_registration_notification(user.email)
        db.session.close()
        return {"success": True, "data": None}
コード例 #2
0
ファイル: auth.py プロジェクト: Edgaraaa/DisPlatform
def reset_password(data=None):
    if data is not None:
        try:
            name = unserialize(data, max_age=1800)
        except (BadTimeSignature, SignatureExpired):
            return render_template("reset_password.html",
                                   errors=["Your link has expired"])
        except (BadSignature, TypeError, base64.binascii.Error):
            return render_template("reset_password.html",
                                   errors=["Your reset token is invalid"])

        if request.method == "GET":
            return render_template("reset_password.html", mode="set")
        if request.method == "POST":
            user = Users.query.filter_by(name=name).first_or_404()
            user.password = request.form["password"].strip()
            db.session.commit()
            log(
                "logins",
                format="[{date}] {ip} -  successful password reset for {name}",
                name=name,
            )
            db.session.close()
            return redirect(url_for("auth.login"))

    if request.method == "POST":
        email_address = request.form["email"].strip()
        team = Users.query.filter_by(email=email_address).first()

        get_errors()

        if config.can_send_mail() is False:
            return render_template(
                "reset_password.html",
                errors=[
                    "Email could not be sent due to server misconfiguration"
                ],
            )

        if not team:
            return render_template(
                "reset_password.html",
                errors=[
                    "If that account exists you will receive an email, please check your inbox"
                ],
            )

        email.forgot_password(email_address, team.name)

        return render_template(
            "reset_password.html",
            errors=[
                "If that account exists you will receive an email, please check your inbox"
            ],
        )
    return render_template("reset_password.html")
コード例 #3
0
def reset_password(data=None):
    if data is not None:
        try:
            name = unserialize(data, max_age=1800)
        except (BadTimeSignature, SignatureExpired):
            return render_template('reset_password.html',
                                   errors=['Your link has expired'])
        except (BadSignature, TypeError, base64.binascii.Error):
            return render_template('reset_password.html',
                                   errors=['Your reset token is invalid'])

        if request.method == "GET":
            return render_template('reset_password.html', mode='set')
        if request.method == "POST":
            team = Users.query.filter_by(name=name).first_or_404()
            team.password = bcrypt_sha256.encrypt(
                request.form['password'].strip())
            db.session.commit()
            log('logins',
                format="[{date}] {ip} -  successful password reset for {name}")
            db.session.close()
            return redirect(url_for('auth.login'))

    if request.method == 'POST':
        email_address = request.form['email'].strip()
        team = Users.query.filter_by(email=email_address).first()

        errors = get_errors()

        if config.can_send_mail() is False:
            return render_template(
                'reset_password.html',
                errors=[
                    'Email could not be sent due to server misconfiguration'
                ])

        if not team:
            return render_template(
                'reset_password.html',
                errors=[
                    'If that account exists you will receive an email, please check your inbox'
                ])

        email.forgot_password(email_address, team.name)

        return render_template(
            'reset_password.html',
            errors=[
                'If that account exists you will receive an email, please check your inbox'
            ])
    return render_template('reset_password.html')
コード例 #4
0
def reset_password(data=None):
    if data is not None:
        try:
            name = unserialize(data, max_age=1800)
        except (BadTimeSignature, SignatureExpired):
            return render_template('reset_password.html', errors=['Votre lien a expiré'])
        except (BadSignature, TypeError, base64.binascii.Error):
            return render_template('reset_password.html', errors=['Votre token de réinitialisation est inalide'])

        if request.method == "GET":
            return render_template('reset_password.html', mode='set')
        if request.method == "POST":
            user = Users.query.filter_by(name=name).first_or_404()
            user.password = request.form['password'].strip()
            db.session.commit()
            log('logins', format="[{date}] {ip} -  successful password reset for {name}", name=name)
            db.session.close()
            return redirect(url_for('auth.login'))

    if request.method == 'POST':
        email_address = request.form['email'].strip()
        team = Users.query.filter_by(email=email_address).first()

        errors = get_errors()

        if config.can_send_mail() is False:
            return render_template(
                'reset_password.html',
                errors=['Le courriel n\'a pas pu être envoyé en raison d\'une erreur de configuration du serveur']
            )

        if not team:
            return render_template(
                'reset_password.html',
                errors=['Si ce compte existe un courriel vous sera envoyé']
            )

        email.forgot_password(email_address, team.name)

        return render_template(
            'reset_password.html',
            errors=['Si ce compte existe un courriel vous sera envoyé']
        )
    return render_template('reset_password.html')
コード例 #5
0
ファイル: auth.py プロジェクト: Edgaraaa/DisPlatform
def register():
    errors = get_errors()
    if request.method == "POST":
        name = request.form["name"]
        email_address = request.form["email"]
        password = request.form["password"]

        name_len = len(name) == 0
        names = Users.query.add_columns("name",
                                        "id").filter_by(name=name).first()
        emails = (Users.query.add_columns(
            "email", "id").filter_by(email=email_address).first())
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = validators.validate_email(request.form["email"])
        team_name_email_check = validators.validate_email(name)

        if not valid_email:
            errors.append("Please enter a valid email address")
        if email.check_email_is_whitelisted(email_address) is False:
            errors.append(
                "Only email addresses under {domains} may register".format(
                    domains=get_config("domain_whitelist")))
        if names:
            errors.append("That user name is already taken")
        if team_name_email_check is True:
            errors.append("Your user name cannot be an email address")
        if emails:
            errors.append("That email has already been used")
        if pass_short:
            errors.append("Pick a longer password")
        if pass_long:
            errors.append("Pick a shorter password")
        if name_len:
            errors.append("Pick a longer user name")

        if len(errors) > 0:
            return render_template(
                "register.html",
                errors=errors,
                name=request.form["name"],
                email=request.form["email"],
                password=request.form["password"],
            )
        else:
            with app.app_context():
                user = Users(
                    name=name.strip(),
                    email=email_address.lower(),
                    password=password.strip(),
                )
                db.session.add(user)
                db.session.commit()
                db.session.flush()

                login_user(user)

                if config.can_send_mail() and get_config(
                        "verify_emails"
                ):  # Confirming users is enabled and we can send email.
                    log(
                        "registrations",
                        format=
                        "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}",
                    )
                    email.verify_email_address(user.email)
                    db.session.close()
                    return redirect(url_for("auth.confirm"))
                else:  # Don't care about confirming users
                    if (
                            config.can_send_mail()
                    ):  # We want to notify the user that they have registered.
                        email.sendmail(
                            request.form["email"],
                            "You've successfully registered for {}".format(
                                get_config("ctf_name")),
                        )

        log("registrations", "[{date}] {ip} - {name} registered with {email}")
        db.session.close()

        if is_teams_mode():
            return redirect(url_for("teams.private"))

        return redirect(url_for("challenges.listing"))
    else:
        return render_template("register.html", errors=errors)
コード例 #6
0
ファイル: auth.py プロジェクト: shareef12/CTFd
def register():
    errors = get_errors()
    if request.method == 'POST':
        name = request.form['name']
        email_address = request.form['email']
        password = request.form['password']

        name_len = len(name) == 0
        names = Users.query.add_columns('name', 'id').filter_by(name=name).first()
        emails = Users.query.add_columns('email', 'id').filter_by(email=email_address).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = validators.validate_email(request.form['email'])
        team_name_email_check = validators.validate_email(name)

        local_id, _, domain = email_address.partition('@')

        domain_whitelist = get_config('domain_whitelist')

        if not valid_email:
            errors.append("Please enter a valid email address")
        if domain_whitelist:
            domain_whitelist = domain_whitelist.split(',')
            if domain not in domain_whitelist:
                errors.append(
                    "Only email addresses under {domains} may register".format(
                        domains=', '.join(domain_whitelist))
                )
        if names:
            errors.append('That team name is already taken')
        if team_name_email_check is True:
            errors.append('Your team name cannot be an email address')
        if emails:
            errors.append('That email has already been used')
        if pass_short:
            errors.append('Pick a longer password')
        if pass_long:
            errors.append('Pick a shorter password')
        if name_len:
            errors.append('Pick a longer team name')

        if len(errors) > 0:
            return render_template(
                'register.html',
                errors=errors,
                name=request.form['name'],
                email=request.form['email'],
                password=request.form['password']
            )
        else:
            with app.app_context():
                user = Users(
                    name=name.strip(),
                    email=email_address.lower(),
                    password=password.strip()
                )
                db.session.add(user)
                db.session.commit()
                db.session.flush()

                login_user(user)

                if config.can_send_mail() and get_config('verify_emails'):  # Confirming users is enabled and we can send email.
                    log('registrations', format="[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}")
                    email.verify_email_address(user.email)
                    db.session.close()
                    return redirect(url_for('auth.confirm'))
                else:  # Don't care about confirming users
                    if config.can_send_mail():  # We want to notify the user that they have registered.
                        email.sendmail(
                            request.form['email'],
                            "You've successfully registered for {}".format(get_config('ctf_name'))
                        )

        log('registrations', "[{date}] {ip} - {name} registered with {email}")
        db.session.close()
        return redirect(url_for('challenges.listing'))
    else:
        return render_template('register.html', errors=errors)
コード例 #7
0
def reset_password(data=None):
    if data is not None:
        try:
            email_address = unserialize(data, max_age=1800)
        except (BadTimeSignature, SignatureExpired):
            return render_template("reset_password.html",
                                   errors=["Your link has expired"])
        except (BadSignature, TypeError, base64.binascii.Error):
            return render_template("reset_password.html",
                                   errors=["Your reset token is invalid"])

        if request.method == "GET":
            return render_template("reset_password.html", mode="set")
        if request.method == "POST":
            password = request.form.get("password", "").strip()
            user = Users.query.filter_by(email=email_address).first_or_404()
            if user.oauth_id:
                return render_template(
                    "reset_password.html",
                    errors=[
                        "Your account was registered via an authentication provider and does not have an associated password. Please login via your authentication provider."
                    ],
                )

            pass_short = len(password) == 0
            if pass_short:
                return render_template(
                    "reset_password.html",
                    errors=["Please pick a longer password"])

            user.password = password
            db.session.commit()
            clear_user_session(user_id=user.id)
            log(
                "logins",
                format="[{date}] {ip} -  successful password reset for {name}",
                name=user.name,
            )
            db.session.close()
            email.password_change_alert(user.email)
            return redirect(url_for("auth.login"))

    if request.method == "POST":
        email_address = request.form["email"].strip()
        user = Users.query.filter_by(email=email_address).first()

        get_errors()

        if config.can_send_mail() is False:
            return render_template(
                "reset_password.html",
                errors=[
                    "Email could not be sent due to server misconfiguration"
                ],
            )

        if not user:
            return render_template(
                "reset_password.html",
                errors=[
                    "If that account exists you will receive an email, please check your inbox"
                ],
            )

        if user.oauth_id:
            return render_template(
                "reset_password.html",
                errors=[
                    "The email address associated with this account was registered via an authentication provider and does not have an associated password. Please login via your authentication provider."
                ],
            )

        email.forgot_password(email_address)

        return render_template(
            "reset_password.html",
            errors=[
                "If that account exists you will receive an email, please check your inbox"
            ],
        )
    return render_template("reset_password.html")
コード例 #8
0
def register():
    errors = get_errors()
    if request.method == "POST":
        name = request.form.get("name", "").strip()
        email_address = request.form.get("email", "").strip().lower()
        password = request.form.get("password", "").strip()
        phone = request.form.get("phone", "").strip()
        student_id = request.form.get("student_id", "").strip()
        realname = request.form.get("realname", "").strip()

        name_len = len(name) == 0
        names = Users.query.add_columns("name",
                                        "id").filter_by(name=name).first()
        emails = (Users.query.add_columns(
            "email", "id").filter_by(email=email_address).first())
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = validators.validate_email(email_address)
        team_name_email_check = validators.validate_email(name)

        phone_valid = len(phone) == 11

        student_id_exist = Users.query.add_columns(
            'student_id', 'id').filter_by(student_id=student_id).first()

        student_id_valid = StudentID.query.add_columns(
            'student_id', 'id').filter_by(student_id=student_id).first()

        phone_exist = Users.query.add_columns(
            'phone', 'id').filter_by(phone=phone).first()
        realname_empty = len(realname) == 0

        if not valid_email:
            errors.append("Please enter a valid email address")
        if email.check_email_is_whitelisted(email_address) is False:
            errors.append(
                "Only email addresses under {domains} may register".format(
                    domains=get_config("domain_whitelist")))
        if names:
            errors.append("That user name is already taken")
        if team_name_email_check is True:
            errors.append("Your user name cannot be an email address")
        if emails:
            errors.append("That email has already been used")
        if pass_short:
            errors.append("Pick a longer password")
        if pass_long:
            errors.append("Pick a shorter password")
        if name_len:
            errors.append("Pick a longer user name")
        if not phone_valid:
            errors.append("Wrong phone number format")
        if not student_id_valid:
            errors.append("Invalid student id")

        if realname_empty:
            errors.append("Realname can't be empty")
        if student_id_exist:
            errors.append("That student id is already taken")
        if phone_exist:
            errors.append("That phone number is already taken")

        if len(errors) > 0:
            return render_template("register.html",
                                   errors=errors,
                                   name=request.form["name"],
                                   email=request.form["email"],
                                   password=request.form["password"],
                                   student_id=student_id,
                                   realname=realname,
                                   phone=phone)
        else:
            with app.app_context():
                user = Users(name=name,
                             email=email_address,
                             password=password,
                             student_id=student_id,
                             realname=realname,
                             phone=phone)
                db.session.add(user)
                db.session.commit()
                db.session.flush()

                login_user(user)

                if config.can_send_mail() and get_config(
                        "verify_emails"
                ):  # Confirming users is enabled and we can send email.
                    log(
                        "registrations",
                        format=
                        "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}",
                    )
                    email.verify_email_address(user.email)
                    db.session.close()
                    return redirect(url_for("auth.confirm"))
                else:  # Don't care about confirming users
                    if (
                            config.can_send_mail()
                    ):  # We want to notify the user that they have registered.
                        email.successful_registration_notification(user.email)

        log("registrations", "[{date}] {ip} - {name} registered with {email}")
        db.session.close()

        if is_teams_mode():
            return redirect(url_for("teams.private"))

        return redirect(url_for("challenges.listing"))
    else:
        return render_template("register.html", errors=errors)
コード例 #9
0
ファイル: auth.py プロジェクト: Gu-f/CTFd_chinese_CN
def register():
    errors = get_errors()
    if current_user.authed():
        return redirect(url_for("challenges.listing"))

    if request.method == "POST":
        name = request.form.get("name", "").strip()
        email_address = request.form.get("email", "").strip().lower()
        password = request.form.get("password", "").strip()

        website = request.form.get("website")
        affiliation = request.form.get("affiliation")
        country = request.form.get("country")
        registration_code = request.form.get("registration_code", "")

        name_len = len(name) == 0
        names = Users.query.add_columns("name",
                                        "id").filter_by(name=name).first()
        emails = (Users.query.add_columns(
            "email", "id").filter_by(email=email_address).first())
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = validators.validate_email(email_address)
        team_name_email_check = validators.validate_email(name)

        if get_config("registration_code"):
            if (registration_code.lower() != get_config("registration_code",
                                                        default="").lower()):
                errors.append(
                    "The registration code you entered was incorrect")

        # Process additional user fields
        fields = {}
        for field in UserFields.query.all():
            fields[field.id] = field

        entries = {}
        for field_id, field in fields.items():
            value = request.form.get(f"fields[{field_id}]", "").strip()
            if field.required is True and (value is None or value == ""):
                errors.append("Please provide all required fields")
                break

            # Handle special casing of existing profile fields
            if field.name.lower() == "affiliation":
                affiliation = value
                break
            elif field.name.lower() == "website":
                website = value
                break

            if field.field_type == "boolean":
                entries[field_id] = bool(value)
            else:
                entries[field_id] = value

        if country:
            try:
                validators.validate_country_code(country)
                valid_country = True
            except ValidationError:
                valid_country = False
        else:
            valid_country = True

        if website:
            valid_website = validators.validate_url(website)
        else:
            valid_website = True

        if affiliation:
            valid_affiliation = len(affiliation) < 128
        else:
            valid_affiliation = True

        if not valid_email:
            errors.append("Please enter a valid email address")
        if email.check_email_is_whitelisted(email_address) is False:
            errors.append(
                "Only email addresses under {domains} may register".format(
                    domains=get_config("domain_whitelist")))
        if names:
            errors.append("该用户名已被使用")
        if team_name_email_check is True:
            errors.append("您的用户名不能是电子邮件地址")
        if emails:
            errors.append("电子邮件地址已被使用")
        if pass_short:
            errors.append("密码长度不够")
        if pass_long:
            errors.append("密码过长")
        if name_len:
            errors.append("用户名长度不够")
        if valid_website is False:
            errors.append("Blog/网站 必须是以http或https开头的正确URL")
        if valid_country is False:
            errors.append("无效的地区")
        if valid_affiliation is False:
            errors.append("单位/组织 过长")

        if len(errors) > 0:
            return render_template(
                "register.html",
                errors=errors,
                name=request.form["name"],
                email=request.form["email"],
                password=request.form["password"],
            )
        else:
            with app.app_context():
                user = Users(name=name, email=email_address, password=password)

                if website:
                    user.website = website
                if affiliation:
                    user.affiliation = affiliation
                if country:
                    user.country = country

                db.session.add(user)
                db.session.commit()
                db.session.flush()

                for field_id, value in entries.items():
                    entry = UserFieldEntries(field_id=field_id,
                                             value=value,
                                             user_id=user.id)
                    db.session.add(entry)
                db.session.commit()

                login_user(user)

                if request.args.get("next") and validators.is_safe_url(
                        request.args.get("next")):
                    return redirect(request.args.get("next"))

                if config.can_send_mail() and get_config(
                        "verify_emails"
                ):  # Confirming users is enabled and we can send email.
                    log(
                        "registrations",
                        format=
                        "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}",
                        name=user.name,
                        email=user.email,
                    )
                    email.verify_email_address(user.email)
                    db.session.close()
                    return redirect(url_for("auth.confirm"))
                else:  # Don't care about confirming users
                    if (
                            config.can_send_mail()
                    ):  # We want to notify the user that they have registered.
                        email.successful_registration_notification(user.email)

        log(
            "registrations",
            format="[{date}] {ip} - {name} registered with {email}",
            name=user.name,
            email=user.email,
        )
        db.session.close()

        if is_teams_mode():
            return redirect(url_for("teams.private"))

        return redirect(url_for("challenges.listing"))
    else:
        return render_template("register.html", errors=errors)
コード例 #10
0
def register():
    errors = get_errors()
    if request.method == 'POST':
        name = request.form['name']
        email_address = request.form['email']
        password = request.form['password']

        name_len = len(name) == 0
        names = Users.query.add_columns('name',
                                        'id').filter_by(name=name).first()
        emails = Users.query.add_columns(
            'email', 'id').filter_by(email=email_address).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = validators.validate_email(request.form['email'])
        team_name_email_check = validators.validate_email(name)

        if not valid_email:
            errors.append("Please enter a valid email address")
        if email.check_email_is_whitelisted(email_address) is False:
            errors.append(
                "Only email addresses under {domains} may register".format(
                    domains=get_config('domain_whitelist')))
        if names:
            errors.append('That team name is already taken')
        if team_name_email_check is True:
            errors.append('Your team name cannot be an email address')
        if emails:
            errors.append('That email has already been used')
        if pass_short:
            errors.append('Pick a longer password')
        if pass_long:
            errors.append('Pick a shorter password')
        if name_len:
            errors.append('Pick a longer team name')
        if ' ' in name:
            errors.append('Your User name should not contain space')
        if len(errors) > 0:
            return render_template('register.html',
                                   errors=errors,
                                   name=request.form['name'],
                                   email=request.form['email'],
                                   password=request.form['password'])
        else:
            with app.app_context():
                user = Users(name=name.strip(),
                             email=email_address.lower(),
                             password=password.strip())
                db.session.add(user)
                db.session.commit()
                db.session.flush()

                login_user(user)
                # system("docker exec server-skr useradd -m %s -s /bin/bash" % name.strip())
                # system('''docker exec server-skr bash -c 'echo "%s:%s" | chpasswd' ''' % (name.strip(),password.strip()))
                # system("docker exec server-skr chmod 700 /home/%s" % name.strip())
                # system("docker exec server-skr cp -r /home/user/. /home/%s/" % name.strip())
                # system("docker exec server-skr chmod 4755 /home/%s/challenges/binary1/overflow" % name.strip())
                # system("docker exec server-skr chmod 4755 /home/%s/challenges/binary2/overflow2" % name.strip())
                # system("docker exec server-skr chmod 4755 /home/%s/challenges/format-string/format-string" % name.strip())
                if config.can_send_mail() and get_config(
                        'verify_emails'
                ):  # Confirming users is enabled and we can send email.
                    log('registrations',
                        format=
                        "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}"
                        )
                    email.verify_email_address(user.email)
                    db.session.close()
                    return redirect(url_for('auth.confirm'))
                else:  # Don't care about confirming users
                    if config.can_send_mail(
                    ):  # We want to notify the user that they have registered.
                        email.sendmail(
                            request.form['email'],
                            "You've successfully registered for {}".format(
                                get_config('ctf_name')))

        log('registrations', "[{date}] {ip} - {name} registered with {email}")
        db.session.close()
        return redirect(url_for('challenges.listing'))
    else:
        return render_template('register.html', errors=errors)
コード例 #11
0
ファイル: __init__.py プロジェクト: leexuan/RSA-2020-CTF
def register():
    errors = get_errors()
    if request.method != "POST":
        return render_template("register.html", errors=errors)
    else:
        name = request.form['name']
        email_address = request.form['email']
        password = request.form['password']
        fname = request.form['fname']
        lname = request.form['lname']
        name_len = len(name) == 0
        fname_len = len(fname) == 0
        lname_len = len(lname) == 0
        names = Users.query.add_columns('name',
                                        'id').filter_by(name=name).first()
        emails = Users.query.add_columns(
            'email', 'id').filter_by(email=email_address).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = validators.validate_email(request.form['email'])
        team_name_email_check = validators.validate_email(name)
        if email.check_email_is_whitelisted(email_address) is False:
            errors.append(
                "Only email addresses under {domains} may register".format(
                    domains=get_config('domain_whitelist')))
        if names:
            errors.append('That user name is already taken')
        if team_name_email_check is True:
            errors.append('Your user name cannot be an email address')
        if emails:
            errors.append('That email has already been used')
        if pass_short:
            errors.append('Pick a longer password')
        if pass_long:
            errors.append('Pick a shorter password')
        if name_len:
            errors.append('Pick a longer user name')
        if fname_len:
            errors.append('Pick a longer user first name')
        if lname_len:
            errors.append('Pick a longer last name')
        if len(errors) > 0:
            return render_template('register.html',
                                   errors=errors,
                                   fname=request.form['fname'],
                                   lname=request.form['lname'],
                                   name=request.form['name'],
                                   email=request.form['email'],
                                   password=request.form['password'])
        else:
            with app.app_context():
                user = Users(name=name.strip(),
                             email=email_address.lower(),
                             password=password.strip())
                db.session.add(user)
                db.session.commit()
                db.session.flush()
                login_user(user)
                # do custom registration work here
                fname = fname.strip()
                lname = lname.strip()
                user_email = email_address.lower()
                # end custom registration work
                if config.can_send_mail() and get_config(
                        'verify_emails'
                ):  # Confirming users is enabled and we can send email.
                    log('registrations',
                        format=
                        "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}"
                        )
                    email.verify_email_address(user.email)
                    db.session.close()
                    return redirect(url_for('auth.confirm'))
                else:  # Don't care about confirming users
                    if config.can_send_mail(
                    ):  # We want to notify the user that they have registered.
                        email.sendmail(
                            request.form['email'],
                            "You've successfully registered for {}".format(
                                get_config('ctf_name')))
        log('registrations', "[{date}] {ip} - {name} registered with {email}")
        db.session.close()
        return redirect(request.url_root + "getStarted" + "?result=" +
                        urllib.parse.quote_plus(web_request.text))
コード例 #12
0
def register():
    errors = get_errors()
    if request.method == 'POST':
        name = request.form['name']
        email_address = request.form['email']
        password = request.form['password']

        name_len = len(name) == 0
        names = Users.query.add_columns('name', 'id').filter_by(name=name).first()
        emails = Users.query.add_columns('email', 'id').filter_by(email=email_address).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = validators.validate_email(request.form['email'])
        team_name_email_check = validators.validate_email(name)

        local_id, _, domain = email_address.partition('@')

        domain_whitelist = get_config('domain_whitelist')

        if not valid_email:
            errors.append("Пожалуйста, введите действующий адрес электронной почты")
        if domain_whitelist:
            domain_whitelist = [d.strip() for d in domain_whitelist.split(',')]
            if domain not in domain_whitelist:
                errors.append(
                    "Only email addresses under {domains} may register".format(
                        domains=', '.join(domain_whitelist))
                )
        if names:
            errors.append('Это название команды уже занято')
        if team_name_email_check is True:
            errors.append('Название команды не может быть адресом электронной почты')
        if emails:
            errors.append('Эта почта уже используется')
        if pass_short:
            errors.append('Выберите пароль подлиннее')
        if pass_long:
            errors.append('Выберите пароль покороче')
        if name_len:
            errors.append('Выберите более длинное название команды')

        if len(errors) > 0:
            return render_template(
                'register.html',
                errors=errors,
                name=request.form['name'],
                email=request.form['email'],
                password=request.form['password']
            )
        else:
            with app.app_context():
                user = Users(
                    name=name.strip(),
                    email=email_address.lower(),
                    password=password.strip()
                )
                db.session.add(user)
                db.session.commit()
                db.session.flush()

                login_user(user)

                if config.can_send_mail() and get_config('verify_emails'):  # Confirming users is enabled and we can send email.
                    log('registrations', format="[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}")
                    email.verify_email_address(user.email)
                    db.session.close()
                    return redirect(url_for('auth.confirm'))
                else:  # Don't care about confirming users
                    if config.can_send_mail():  # We want to notify the user that they have registered.
                        email.sendmail(
                            request.form['email'],
                            "You've successfully registered for {}".format(get_config('ctf_name'))
                        )

        log('registrations', "[{date}] {ip} - {name} registered with {email}")
        db.session.close()
        return redirect(url_for('challenges.listing'))
    else:
        return render_template('register.html', errors=errors)
コード例 #13
0
ファイル: auth.py プロジェクト: itsTurnip/CTFd
def register():
    errors = get_errors()
    if request.method == "POST":
        name = request.form.get("name", "").strip()
        email_address = request.form.get("email", "").strip().lower()
        password = request.form.get("password", "").strip()

        website = request.form.get("website")
        affiliation = request.form.get("affiliation")
        country = request.form.get("country")

        name_len = len(name) == 0
        names = Users.query.add_columns("name",
                                        "id").filter_by(name=name).first()
        emails = (Users.query.add_columns(
            "email", "id").filter_by(email=email_address).first())
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = validators.validate_email(email_address)
        team_name_email_check = validators.validate_email(name)

        # Process additional user fields
        fields = {}
        for field in UserFields.query.all():
            fields[field.id] = field

        entries = {}
        for field_id, field in fields.items():
            value = request.form.get(f"fields[{field_id}]", "").strip()
            if field.required is True and (value is None or value == ""):
                errors.append("Please provide all required fields")
                break

            # Handle special casing of existing profile fields
            if field.name.lower() == "affiliation":
                affiliation = value
                break
            elif field.name.lower() == "website":
                website = value
                break

            if field.field_type == "boolean":
                entries[field_id] = bool(value)
            else:
                entries[field_id] = value

        if country:
            try:
                validators.validate_country_code(country)
                valid_country = True
            except ValidationError:
                valid_country = False
        else:
            valid_country = True

        if website:
            valid_website = validators.validate_url(website)
        else:
            valid_website = True

        if affiliation:
            valid_affiliation = len(affiliation) < 128
        else:
            valid_affiliation = True

        if not valid_email:
            errors.append(
                "Пожалуйста, введите действительный адрес электронной почты")
        if email.check_email_is_whitelisted(email_address) is False:
            errors.append(
                "Только адреса электронной почты ниже {domains} могут быть зарегистрированы"
                .format(domains=get_config("domain_whitelist")))
        if names:
            errors.append("Этот никнейм уже используется")
        if team_name_email_check is True:
            errors.append(
                "Ваше имя пользователя не может быть адресом электронной почты"
            )
        if emails:
            errors.append("Этот адрес электронной почты уже был использован")
        if pass_short:
            errors.append("Введите более длинный пароль")
        if pass_long:
            errors.append("Введите более короткий пароль")
        if name_len:
            errors.append("Введите более длинное имя пользователя")
        if valid_website is False:
            errors.append(
                "Сайт должен иметь правильный URL, начинающийся с http или https."
            )
        if valid_country is False:
            errors.append("Введите существующую страна")
        if valid_affiliation is False:
            errors.append("Укажите более короткое название учреждения")

        if len(errors) > 0:
            return render_template(
                "register.html",
                errors=errors,
                name=request.form["name"],
                email=request.form["email"],
                password=request.form["password"],
            )
        else:
            with app.app_context():
                user = Users(name=name, email=email_address, password=password)

                if website:
                    user.website = website
                if affiliation:
                    user.affiliation = affiliation
                if country:
                    user.country = country

                db.session.add(user)
                db.session.commit()
                db.session.flush()

                for field_id, value in entries.items():
                    entry = UserFieldEntries(field_id=field_id,
                                             value=value,
                                             user_id=user.id)
                    db.session.add(entry)
                db.session.commit()

                login_user(user)

                if config.can_send_mail() and get_config(
                        "verify_emails"
                ):  # Confirming users is enabled and we can send email.
                    log(
                        "registrations",
                        format=
                        "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}",
                    )
                    email.verify_email_address(user.email)
                    db.session.close()
                    return redirect(url_for("auth.confirm"))
                else:  # Don't care about confirming users
                    if (
                            config.can_send_mail()
                    ):  # We want to notify the user that they have registered.
                        email.successful_registration_notification(user.email)

        log("registrations", "[{date}] {ip} - {name} registered with {email}")
        db.session.close()

        if is_teams_mode():
            return redirect(url_for("teams.private"))

        return redirect(url_for("challenges.listing"))
    else:
        return render_template("register.html", errors=errors)
コード例 #14
0
def register():
    errors = get_errors()
    if request.method == "POST":
        name = request.form.get("name", "").strip()
        email_address = request.form.get("email", "").strip().lower()
        password = request.form.get("password", "").strip()

        website = request.form.get("website")
        affiliation = request.form.get("affiliation")
        country = request.form.get("country")

        name_len = len(name) == 0
        names = Users.query.add_columns("name",
                                        "id").filter_by(name=name).first()
        emails = (Users.query.add_columns(
            "email", "id").filter_by(email=email_address).first())
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = validators.validate_email(email_address)
        team_name_email_check = validators.validate_email(name)

        if country:
            try:
                validators.validate_country_code(country)
                valid_country = True
            except ValidationError:
                valid_country = False
        else:
            valid_country = True

        if website:
            valid_website = validators.validate_url(website)
        else:
            valid_website = True

        if affiliation:
            valid_affiliation = len(affiliation) < 128
        else:
            valid_affiliation = True

        if not valid_email:
            errors.append("Please enter a valid email address")
        if email.check_email_is_whitelisted(email_address) is False:
            errors.append(
                "Only email addresses under {domains} may register".format(
                    domains=get_config("domain_whitelist")))
        if names:
            errors.append("That user name is already taken")
        if team_name_email_check is True:
            errors.append("Your user name cannot be an email address")
        if emails:
            errors.append("That email has already been used")
        if pass_short:
            errors.append("Pick a longer password")
        if pass_long:
            errors.append("Pick a shorter password")
        if name_len:
            errors.append("Pick a longer user name")
        if valid_website is False:
            errors.append(
                "Websites must be a proper URL starting with http or https")
        if valid_country is False:
            errors.append("Invalid country")
        if valid_affiliation is False:
            errors.append("Please provide a shorter affiliation")

        if len(errors) > 0:
            return render_template(
                "register.html",
                errors=errors,
                name=request.form["name"],
                email=request.form["email"],
                password=request.form["password"],
            )
        else:
            with app.app_context():
                user = Users(name=name, email=email_address, password=password)

                if website:
                    user.website = website
                if affiliation:
                    user.affiliation = affiliation
                if country:
                    user.country = country

                db.session.add(user)
                db.session.commit()
                db.session.flush()

                login_user(user)

                if config.can_send_mail() and get_config(
                        "verify_emails"
                ):  # Confirming users is enabled and we can send email.
                    log(
                        "registrations",
                        format=
                        "[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}",
                    )
                    email.verify_email_address(user.email)
                    db.session.close()
                    return redirect(url_for("auth.confirm"))
                else:  # Don't care about confirming users
                    if (
                            config.can_send_mail()
                    ):  # We want to notify the user that they have registered.
                        email.successful_registration_notification(user.email)

        log("registrations", "[{date}] {ip} - {name} registered with {email}")
        db.session.close()

        if is_teams_mode():
            return redirect(url_for("teams.private"))

        return redirect(url_for("challenges.listing"))
    else:
        return render_template("register.html", errors=errors)
コード例 #15
0
def register():
    errors = get_errors()
    if request.method == 'POST':
        name = request.form['name']
        email_address = request.form['email']
        password = request.form['password']

        name_len = len(name) == 0
        names = Users.query.add_columns('name', 'id').filter_by(name=name).first()
        emails = Users.query.add_columns('email', 'id').filter_by(email=email_address).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = validators.validate_email(request.form['email'])
        team_name_email_check = validators.validate_email(name)
        #accepted_rules = request.form.get("accept")

        local_id, _, domain = email_address.partition('@')

        domain_whitelist = get_config('domain_whitelist')

        if not valid_email:
            errors.append("Veuillez entrer un courriel valide")
        if domain_whitelist:
            domain_whitelist = [d.strip() for d in domain_whitelist.split(',')]
            if domain not in domain_whitelist:
                errors.append(
                    "Seuls les addresses sous {domains} peuvent s'enregistrer".format(
                        domains=', '.join(domain_whitelist))
                )
        if names:
            errors.append('Ce nom d\'équipe est pris')
        if team_name_email_check is True:
            errors.append('Votre nom d\'équipe ne peut être une addresse courriel')
        if emails:
            errors.append('Cette addresse courriel est déjà utilisée')
        if pass_short:
            errors.append('Votre mot de passe est trop petit')
        if pass_long:
            errors.append('Votre mot de passe est trop long')
        if name_len:
            errors.append('Votre nom d\'équipe est trop petit')
        #if not accepted_rules:
        #    errors.append("Vous devez lire et accepter le règlement & code de conduite")
            
        if len(errors) > 0:
            return render_template(
                'register.html',
                errors=errors,
                name=request.form['name'],
                email=request.form['email'],
                password=request.form['password']
            )
        else:
            with app.app_context():
                user = Users(
                    name=name.strip(),
                    email=email_address.lower(),
                    password=password.strip()
                )
                db.session.add(user)
                db.session.commit()
                db.session.flush()

                login_user(user)

                if config.can_send_mail() and get_config('verify_emails'):  # Confirming users is enabled and we can send email.
                    log('registrations', format="[{date}] {ip} - {name} registered (UNCONFIRMED) with {email}")
                    email.verify_email_address(user.email)
                    db.session.close()
                    return redirect(url_for('auth.confirm'))
                else:  # Don't care about confirming users
                    if config.can_send_mail():  # We want to notify the user that they have registered.
                        email.sendmail(
                            request.form['email'],
                            "You've successfully registered for {}".format(get_config('ctf_name'))
                        )

        log('registrations', "[{date}] {ip} - {name} registered with {email}")
        db.session.close()
        return redirect(url_for('challenges.listing'))
    else:
        return render_template('register.html', errors=errors)