Ejemplo n.º 1
0
def confirm_user(data=None):
    if not utils.get_config('verify_emails'):
        # If the CTF doesn't care about confirming email addresses then redierct to challenges
        return redirect(url_for('challenges.challenges_view'))

    logger = logging.getLogger('regs')
    # User is confirming email account
    if data and request.method == "GET":
        try:
            s = TimedSerializer(app.config['SECRET_KEY'])
            email = s.loads(utils.base64decode(data, urldecode=True),
                            max_age=1800)
        except BadTimeSignature:
            return render_template('confirm.html',
                                   errors=[get_tip('LINK_EXPIRED')])
        except (BadSignature, TypeError, base64.binascii.Error):
            return render_template('confirm.html',
                                   errors=[get_tip('INVIDE_RESET_TOKEN')])
        team = Teams.query.filter_by(email=email).first_or_404()
        team.verified = True
        db.session.commit()
        logger.warn(
            get_tip('USER_HAVE_CM').format(date=time.strftime("%m/%d/%Y %X"),
                                           ip=utils.get_ip(),
                                           username=team.name.encode('utf-8'),
                                           email=team.email.encode('utf-8')))
        db.session.close()
        if utils.authed():
            return redirect(url_for('challenges.challenges_view'))
        return redirect(url_for('auth.login'))

    # User is trying to start or restart the confirmation flow
    if not utils.authed():
        return redirect(url_for('auth.login'))

    team = Teams.query.filter_by(id=session['id']).first_or_404()

    if data is None:
        if request.method == "POST":
            # User wants to resend their confirmation email
            if team.verified:
                return redirect(url_for('views.profile'))
            else:
                utils.verify_email(team.email)
                logger.warn(
                    get_tip('EMAIL_CF_RESENT').format(
                        date=time.strftime("%m/%d/%Y %X"),
                        ip=utils.get_ip(),
                        username=team.name.encode('utf-8'),
                        email=team.email.encode('utf-8')))
            return render_template('confirm.html',
                                   team=team,
                                   infos=[get_tip('EMAIL_CF_SENT')])
        elif request.method == "GET":
            # User has been directed to the confirm page
            team = Teams.query.filter_by(id=session['id']).first_or_404()
            if team.verified:
                # If user is already verified, redirect to their profile
                return redirect(url_for('views.profile'))
            return render_template('confirm.html', team=team)
Ejemplo n.º 2
0
def test_verify_email(mock_smtp):
    """Does verify_email send emails"""
    app = create_ctfd()
    with app.app_context():
        set_config('mail_server', 'localhost')
        set_config('mail_port', 25)
        set_config('mail_username', 'username')
        set_config('mail_password', 'password')
        set_config('verify_emails', True)

        from_addr = get_config('mailfrom_addr') or app.config.get('MAILFROM_ADDR')
        to_addr = '*****@*****.**'

        verify_email(to_addr)

        # This is currently not actually validated
        msg = ("Please click the following link to confirm"
               " your email address for CTFd:"
               " http://localhost/confirm/InVzZXJAdXNlci5jb20iLkFmS0dQZy5kLUJnVkgwaUhadzFHaXVENHczWTJCVVJwdWc")

        ctf_name = get_config('ctf_name')
        email_msg = MIMEText(msg)
        email_msg['Subject'] = "Message from {0}".format(ctf_name)
        email_msg['From'] = from_addr
        email_msg['To'] = to_addr

        # Need to freeze time to predict the value of the itsdangerous token.
        # For now just assert that sendmail was called.
        mock_smtp.return_value.sendmail.assert_called_with(from_addr, [to_addr], email_msg.as_string())
    destroy_ctfd(app)
Ejemplo n.º 3
0
def test_verify_email(mock_smtp):
    """Does verify_email send emails"""
    from email.mime.text import MIMEText
    app = create_ctfd()
    with app.app_context():
        set_config('mail_server', 'localhost')
        set_config('mail_port', 25)
        set_config('mail_username', 'username')
        set_config('mail_password', 'password')
        set_config('verify_emails', True)

        from_addr = get_config('mailfrom_addr') or app.config.get('MAILFROM_ADDR')
        to_addr = '*****@*****.**'

        verify_email(to_addr)

        # This is currently not actually validated
        msg = ("Please click the following link to confirm"
               " your email address for CTFd:"
               " http://localhost/confirm/InVzZXJAdXNlci5jb20iLkRHbGFZUS5XUURfQzBub3pGZkFMRlIyeGxDS1BCMjZETlk%3D")

        ctf_name = get_config('ctf_name')
        email_msg = MIMEText(msg)
        email_msg['Subject'] = "Message from {0}".format(ctf_name)
        email_msg['From'] = from_addr
        email_msg['To'] = to_addr

        # Need to freeze time to predict the value of the itsdangerous token.
        # For now just assert that sendmail was called.
        mock_smtp.return_value.sendmail.assert_called()
    destroy_ctfd(app)
Ejemplo n.º 4
0
def confirm_user(data=None):
    if not get_config('verify_emails'):
        return redirect(url_for('challenges.challenges_view'))
    if data and request.method == "GET":  # User is confirming email account
        try:
            s = Signer(app.config['SECRET_KEY'])
            email = s.unsign(urllib.unquote_plus(data.decode('base64')))
        except BadSignature:
            return render_template(
                'confirm.html', errors=['Your confirmation link seems wrong'])
        except:
            return render_template(
                'confirm.html',
                errors=['Your link appears broken, please try again.'])
        team = Teams.query.filter_by(email=email).first_or_404()
        team.verified = True
        db.session.commit()
        db.session.close()
        logger = logging.getLogger('regs')
        logger.warn("[{0}] {1} confirmed {2}".format(
            time.strftime("%m/%d/%Y %X"), team.name.encode('utf-8'),
            team.email.encode('utf-8')))
        if authed():
            return redirect(url_for('challenges.challenges_view'))
        return redirect(url_for('auth.login'))
    if not data and request.method == "GET":  # User has been directed to the confirm page because his account is not verified
        if not authed():
            return redirect(url_for('auth.login'))
        team = Teams.query.filter_by(id=session['id']).first_or_404()
        if team.verified:
            return redirect(url_for('views.profile'))
        else:
            verify_email(team.email)
        return render_template('confirm.html', team=team)
Ejemplo n.º 5
0
def register():
    if not can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        email = request.form['email']
        schoolCode = request.form['schoolCode']
        password = request.form['password']

        name_len = len(name) == 0
        names = Teams.query.add_columns('name', 'id').filter_by(name=name).first()
        emails = Teams.query.add_columns('email', 'id').filter_by(email=email).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = re.match("[^@]+@[^@]+\.[^@]+", request.form['email'])

        if not valid_email:
            errors.append("That email doesn't look right")
        if names:
            errors.append('That team name is already taken')
        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'], schoolCode=request.form['schoolCode'], password=request.form['password'])
        else:
            with app.app_context():
                team = Teams(name, email.lower(), schoolCode, password)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = sha512(os.urandom(10))

                if mailserver() and get_config('verify_emails'):
                    verify_email(team.email)
                else:
                    if mailserver():
                        sendmail(request.form['email'], "You've successfully registered for {}".format(get_config('ctf_name')))

        db.session.close()

        logger = logging.getLogger('regs')
        logger.warn("[{0}] {1} registered with {2}".format(time.strftime("%m/%d/%Y %X"), request.form['name'].encode('utf-8'), request.form['email'].encode('utf-8')))
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Ejemplo n.º 6
0
def confirm_user(data=None):
    if not utils.get_config('verify_emails'):
        # If the CTF doesn't care about confirming email addresses then redierct to challenges
        return redirect(url_for('challenges.challenges_view'))

    logger = logging.getLogger('regs')
    # User is confirming email account
    if data and request.method == "GET":
        try:
            s = TimedSerializer(app.config['SECRET_KEY'])
            email = s.loads(utils.base64decode(data, urldecode=True), max_age=1800)
        except BadTimeSignature:
            return render_template('confirm.html', errors=['Your confirmation link has expired'])
        except BadSignature:
            return render_template('confirm.html', errors=['Your confirmation link seems wrong'])
        team = Teams.query.filter_by(email=email).first_or_404()
        team.verified = True
        db.session.commit()
        logger.warn("[{date}] {ip} - {username} confirmed their account".format(
            date=time.strftime("%m/%d/%Y %X"),
            ip=utils.get_ip(),
            username=team.name.encode('utf-8'),
            email=team.email.encode('utf-8')
        ))
        db.session.close()
        if utils.authed():
            return redirect(url_for('challenges.challenges_view'))
        return redirect(url_for('auth.login'))

    # User is trying to start or restart the confirmation flow
    if not utils.authed():
        return redirect(url_for('auth.login'))

    team = Teams.query.filter_by(id=session['id']).first_or_404()

    if data is None:
        if request.method == "POST":
            # User wants to resend their confirmation email
            if team.verified:
                return redirect(url_for('views.profile'))
            else:
                utils.verify_email(team.email)
                logger.warn("[{date}] {ip} - {username} initiated a confirmation email resend".format(
                    date=time.strftime("%m/%d/%Y %X"),
                    ip=utils.get_ip(),
                    username=team.name.encode('utf-8'),
                    email=team.email.encode('utf-8')
                ))
            return render_template('confirm.html', team=team, infos=['Your confirmation email has been resent!'])
        elif request.method == "GET":
            # User has been directed to the confirm page
            team = Teams.query.filter_by(id=session['id']).first_or_404()
            if team.verified:
                # If user is already verified, redirect to their profile
                return redirect(url_for('views.profile'))
            return render_template('confirm.html', team=team)
Ejemplo n.º 7
0
def register():
    if not can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']

        name_len = len(name) == 0
        names = Teams.query.add_columns('name', 'id').filter_by(name=name).first()
        emails = Teams.query.add_columns('email', 'id').filter_by(email=email).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = re.match("[^@]+@[^@]+\.[^@]+", request.form['email'])

        if not valid_email:
            errors.append("That email doesn't look right")
        if names:
            errors.append('That team name is already taken')
        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():
                team = Teams(name, email.lower(), password)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = sha512(os.urandom(10))

                if can_send_mail() and get_config('verify_emails'):
                    verify_email(team.email)
                else:
                    if can_send_mail():
                        sendmail(request.form['email'], "You've successfully registered for {}".format(get_config('ctf_name')))

        db.session.close()

        logger = logging.getLogger('regs')
        logger.warn("[{0}] {1} registered with {2}".format(time.strftime("%m/%d/%Y %X"), request.form['name'].encode('utf-8'), request.form['email'].encode('utf-8')))
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Ejemplo n.º 8
0
def confirm_user(data=None):
    if not utils.get_config('verify_emails'):
        # If the CTF doesn't care about confirming email addresses then redierct to challenges
        return redirect(url_for('challenges.challenges_view'))

    # User is confirming email account
    if data and request.method == "GET":
        try:
            s = Signer(app.config['SECRET_KEY'])
            email = s.unsign(urllib.unquote_plus(data.decode('base64')))
        except BadSignature:
            return render_template(
                'confirm.html', errors=['Your confirmation link seems wrong'])
        except:
            return render_template(
                'confirm.html',
                errors=['Your link appears broken, please try again.'])
        team = Teams.query.filter_by(email=email).first_or_404()
        team.verified = True
        db.session.commit()
        logger = logging.getLogger('regs')
        logger.warn("[{0}] {1} confirmed {2}".format(
            time.strftime("%m/%d/%Y %X"), team.name.encode('utf-8'),
            team.email.encode('utf-8')))
        db.session.close()
        if utils.authed():
            return redirect(url_for('challenges.challenges_view'))
        return redirect(url_for('auth.login'))

    # User is trying to start or restart the confirmation flow
    if not utils.authed():
        return redirect(url_for('auth.login'))

    team = Teams.query.filter_by(id=session['id']).first_or_404()

    if data is None:
        if request.method == "POST":
            # User wants to resend their confirmation email
            if team.verified:
                return redirect(url_for('views.profile'))
            else:
                utils.verify_email(team.email)
            return render_template(
                'confirm.html',
                team=team,
                infos=['Your confirmation email has been resent!'])
        elif request.method == "GET":
            # User has been directed to the confirm page
            team = Teams.query.filter_by(id=session['id']).first_or_404()
            if team.verified:
                # If user is already verified, redirect to their profile
                return redirect(url_for('views.profile'))
            return render_template('confirm.html', team=team)
Ejemplo n.º 9
0
def confirm_user(data=None):
    if not utils.get_config('verify_emails'):
        # If the CTF doesn't care about confirming email addresses then redierct to challenges
        return redirect(url_for('challenges.challenges_view'))

    # User is confirming email account
    if data and request.method == "GET":
        try:
            s = Signer(app.config['SECRET_KEY'])
            email = s.unsign(urllib.unquote_plus(data.decode('base64')))
        except BadSignature:
            return render_template('confirm.html', errors=['Your confirmation link seems wrong'])
        except:
            return render_template('confirm.html', errors=['Your link appears broken, please try again.'])
        team = Teams.query.filter_by(email=email).first_or_404()
        team.verified = True
        db.session.commit()
        logger = logging.getLogger('regs')
        logger.warn("[{0}] {1} confirmed {2}".format(time.strftime("%m/%d/%Y %X"), team.name.encode('utf-8'), team.email.encode('utf-8')))
        db.session.close()
        if utils.authed():
            return redirect(url_for('challenges.challenges_view'))
        return redirect(url_for('auth.login'))

    # User is trying to start or restart the confirmation flow
    if not utils.authed():
        return redirect(url_for('auth.login'))

    team = Teams.query.filter_by(id=session['id']).first_or_404()

    if data is None:
        if request.method == "POST":
            # User wants to resend their confirmation email
            if team.verified:
                return redirect(url_for('views.profile'))
            else:
                utils.verify_email(team.email)
            return render_template('confirm.html', team=team, infos=['Your confirmation email has been resent!'])
        elif request.method == "GET":
            # User has been directed to the confirm page
            team = Teams.query.filter_by(id=session['id']).first_or_404()
            if team.verified:
                # If user is already verified, redirect to their profile
                return redirect(url_for('views.profile'))
            return render_template('confirm.html', team=team)
Ejemplo n.º 10
0
def register():
    logger = logging.getLogger('regs')
    if not utils.can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        sno = request.form['sno']
        email = request.form['email']
        password = request.form['password']

        name_len = len(name) == 0
        names = Teams.query.add_columns('name',
                                        'id').filter_by(name=name).first()
        valid_sno = utils.check_sno_format(request.form['sno'])
        snos = Teams.query.add_columns('sno', 'id').filter_by(sno=sno).first()
        emails = Teams.query.add_columns('email',
                                         'id').filter_by(email=email).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = utils.check_email_format(request.form['email'])
        team_name_email_check = utils.check_email_format(name)

        if not valid_sno:
            errors.append("Please enter a valid student ID")
        if not valid_email:
            errors.append("Please enter a valid email address")
        if names or snos:
            errors.append('That nick/user 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():
                team = Teams(name, sno, email.lower(), password)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['sno'] = team.sno
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = utils.sha512(os.urandom(10))

                if utils.can_send_mail() and utils.get_config(
                        'verify_emails'
                ):  # Confirming users is enabled and we can send email.
                    logger = logging.getLogger('regs')
                    logger.warn(
                        "[{date}] {ip} - {username}/{sno} registered (UNCONFIRMED) with {email}"
                        .format(date=time.strftime("%m/%d/%Y %X"),
                                ip=utils.get_ip(),
                                username=request.form['name'].encode('utf-8'),
                                sno=request.form['sno'].encode('utf-8'),
                                email=request.form['email'].encode('utf-8')))
                    utils.verify_email(team.email)
                    db.session.close()
                    return redirect(url_for('auth.confirm_user'))
                else:  # Don't care about confirming users
                    if utils.can_send_mail(
                    ):  # We want to notify the user that they have registered.
                        utils.sendmail(
                            request.form['email'],
                            "You've successfully registered for {}".format(
                                utils.get_config('ctf_name')))

        logger.warn(
            "[{date}] {ip} - {username}/{sno} registered with {email}".format(
                date=time.strftime("%m/%d/%Y %X"),
                ip=utils.get_ip(),
                username=request.form['name'].encode('utf-8'),
                sno=request.form['sno'].encode('utf-8'),
                email=request.form['email'].encode('utf-8')))
        db.session.close()
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Ejemplo n.º 11
0
def register():
    logger = logging.getLogger('regs')
    if not utils.can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']

        name_len = len(name) == 0
        names = Teams.query.add_columns('name', 'id').filter_by(name=name).first()
        emails = Teams.query.add_columns('email', 'id').filter_by(email=email).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", request.form['email'])

        if not valid_email:
            errors.append("That email doesn't look right")
        if names:
            errors.append('That team name is already taken')
        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():
                team = Teams(name, email.lower(), password)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = utils.sha512(os.urandom(10))

                if utils.can_send_mail() and utils.get_config('verify_emails'):  # Confirming users is enabled and we can send email.
                    logger = logging.getLogger('regs')
                    logger.warn("[{date}] {ip} - {username} registered (UNCONFIRMED) with {email}".format(
                        date=time.strftime("%m/%d/%Y %X"),
                        ip=utils.get_ip(),
                        username=request.form['name'].encode('utf-8'),
                        email=request.form['email'].encode('utf-8')
                    ))
                    utils.verify_email(team.email)
                    db.session.close()
                    return redirect(url_for('auth.confirm_user'))
                else:  # Don't care about confirming users
                    if utils.can_send_mail():  # We want to notify the user that they have registered.
                        utils.sendmail(request.form['email'], "You've successfully registered for {}".format(utils.get_config('ctf_name')))

        logger.warn("[{date}] {ip} - {username} registered with {email}".format(
            date=time.strftime("%m/%d/%Y %X"),
            ip=utils.get_ip(),
            username=request.form['name'].encode('utf-8'),
            email=request.form['email'].encode('utf-8')
        ))
        db.session.close()
        return redirect(url_for('contests.contests_view'))
    else:
        return render_template('register.html')
Ejemplo n.º 12
0
def register():
    if not utils.can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']

        name_len = len(name) == 0
        names = Teams.query.add_columns('name', 'id').filter_by(name=name).first()
        emails = Teams.query.add_columns('email', 'id').filter_by(email=email).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = re.match(r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)", request.form['email'])

        if not valid_email:
            errors.append("That email doesn't look right")
        if names:
            errors.append('That team name is already taken')
        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():
                team = Teams(name, email.lower(), password)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = utils.sha512(os.urandom(10))

                if utils.can_send_mail() and utils.get_config('verify_emails'):  # Confirming users is enabled and we can send email.
                    db.session.close()
                    logger = logging.getLogger('regs')
                    logger.warn("[{0}] {1} registered (UNCONFIRMED) with {2}".format(time.strftime("%m/%d/%Y %X"),
                                                                                     request.form['name'].encode('utf-8'),
                                                                                     request.form['email'].encode('utf-8')))

                    utils.verify_email(team.email)

                    return redirect(url_for('auth.confirm_user'))
                else:  # Don't care about confirming users
                    if utils.can_send_mail():  # We want to notify the user that they have registered.
                        utils.sendmail(request.form['email'], "You've successfully registered for {}".format(utils.get_config('ctf_name')))

        db.session.close()

        logger = logging.getLogger('regs')
        logger.warn("[{0}] {1} registered with {2}".format(time.strftime("%m/%d/%Y %X"), request.form['name'].encode('utf-8'), request.form['email'].encode('utf-8')))
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Ejemplo n.º 13
0
def register():
    logger = logging.getLogger('regs')
    if not utils.can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']

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

        if not valid_email:
            errors.append(get_tip('INVIDE_EMAIL'))
        if names:
            errors.append(get_tip('TEAM_EXIST'))
        if team_name_email_check is True:
            errors.append(get_tip('EMAIL_NOT_TEAM'))
        if emails:
            errors.append(get_tip('EMAIL_HAVE_USE'))
        if pass_short:
            errors.append(get_tip('TOO_SHORT_PASS'))
        if pass_long:
            errors.append(get_tip('TOO_LONG_PASS'))
        if name_len:
            errors.append(get_tip('TOO_SHORT_TEAM'))

        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():
                token = os.urandom(16).encode('hex')
                team = Teams(name, email.lower(), password, token.lower())
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = utils.sha512(os.urandom(10))

                if utils.can_send_mail() and utils.get_config(
                        'verify_emails'
                ):  # Confirming users is enabled and we can send email.
                    logger = logging.getLogger('regs')
                    logger.warn(
                        get_tip('USER_REG_WARN').format(
                            date=time.strftime("%m/%d/%Y %X"),
                            ip=utils.get_ip(),
                            username=request.form['name'].encode('utf-8'),
                            email=request.form['email'].encode('utf-8')))
                    utils.verify_email(team.email)
                    db.session.close()
                    return redirect(url_for('auth.confirm_user'))
                else:  # Don't care about confirming users
                    if utils.can_send_mail(
                    ):  # We want to notify the user that they have registered.
                        utils.sendmail(
                            request.form['email'],
                            get_tip('USER_REG_SUCCESS').format(
                                utils.get_config('ctf_name')))

        logger.warn(
            get_tip('USER_REGISTRED').format(
                date=time.strftime("%m/%d/%Y %X"),
                ip=utils.get_ip(),
                username=request.form['name'].encode('utf-8'),
                email=request.form['email'].encode('utf-8')))
        db.session.close()
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Ejemplo n.º 14
0
def register():
    logger = logging.getLogger('regs')
    if not utils.can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']

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

        if not valid_email:
            errors.append("邮箱格式不正确")
        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():
                team = Teams(name, email.lower(), password)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = utils.sha512(os.urandom(10))

                if utils.can_send_mail() and utils.get_config(
                        'verify_emails'
                ):  # Confirming users is enabled and we can send email.
                    logger = logging.getLogger('regs')
                    logger.warn(
                        "[{date}] {ip} - {username} registered (UNCONFIRMED) with {email}"
                        .format(date=time.strftime("%m/%d/%Y %X"),
                                ip=utils.get_ip(),
                                username=request.form['name'].encode('utf-8'),
                                email=request.form['email'].encode('utf-8')))
                    utils.verify_email(team.email)
                    db.session.close()
                    return redirect(url_for('auth.confirm_user'))
                else:  # Don't care about confirming users
                    if utils.can_send_mail(
                    ):  # We want to notify the user that they have registered.
                        utils.sendmail(
                            request.form['email'], "您已经成功过注册了 {}".format(
                                utils.get_config('ctf_name')))

        logger.warn(
            "[{date}] {ip} - {username} registered with {email}".format(
                date=time.strftime("%m/%d/%Y %X"),
                ip=utils.get_ip(),
                username=request.form['name'].encode('utf-8'),
                email=request.form['email'].encode('utf-8')))
        db.session.close()
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Ejemplo n.º 15
0
def register():
    if not can_register():
        return redirect(url_for("auth.login"))
    if request.method == "POST":
        errors = []
        name = request.form["name"]
        email = request.form["email"]
        password = request.form["password"]
        bracket = request.form["bracket"]
        country = request.form["country"]
        affiliation = request.form["affiliation"]

        name_len = len(name) == 0
        names = Teams.query.add_columns("name", "id").filter_by(name=name).first()
        emails = Teams.query.add_columns("email", "id").filter_by(email=email).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = re.match("[^@]+@[^@]+\.[^@]+", request.form["email"])
        bracket_exists = bracket in brackets
        country_exists = country in countries
        print country_exists
        print country

        if not valid_email:
            errors.append("That email doesn't look right")
        if names:
            errors.append("That team name is already taken")
        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 not bracket_exists:
            errors.append("Please select a valid bracket")
        if not country_exists:
            errors.append("Please select a valid country")

        if len(errors) > 0:
            return render_template(
                "register.html",
                errors=errors,
                name=request.form["name"],
                email=request.form["email"],
                password=request.form["password"],
                brackets=brackets,
                countries=countries,
            )
        else:
            with app.app_context():
                team = Teams(name, email.lower(), password, bracket, country, affiliation)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session["username"] = team.name
                session["id"] = team.id
                session["admin"] = team.admin
                session["nonce"] = sha512(os.urandom(10))

                if mailserver() and get_config("verify_emails"):
                    verify_email(team.email)
                else:
                    if mailserver():
                        sendmail(
                            request.form["email"],
                            "You've successfully registered for {}".format(get_config("ctf_name")),
                        )

        db.session.close()

        logger = logging.getLogger("regs")
        logger.warn(
            "[{0}] {1} registered with {2}".format(
                time.strftime("%m/%d/%Y %X"),
                request.form["name"].encode("utf-8"),
                request.form["email"].encode("utf-8"),
            )
        )
        return redirect(url_for("challenges.challenges_view"))
    else:
        return render_template("register.html", brackets=brackets, countries=countries)
Ejemplo n.º 16
0
def private_register():
    if not utils.can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        selected_option = utils.get_config('private_registration_option')

        errors = []

        if selected_option == 'token':
            token = request.form['token']
            invited_team = InvitedTeams.query.add_columns(
                'name', 'email').filter_by(token=token).first()
            if not invited_team:
                errors.append('Invalid token')
        elif selected_option == 'email':
            email = request.form['email']
            invited_team = InvitedTeams.query.add_columns(
                'name', 'email').filter_by(email=email).first()
            if not invited_team:
                errors.append('Your email is not invited')
        else:
            errors.append('Something strange happened')

        if len(errors) == 0:
            team = Teams.query.add_columns('id').filter_by(
                name=invited_team.name).first()
            if team:
                errors.append('Already registered')

        password = request.form['password']

        pass_short = len(password) == 0
        pass_long = len(password) > 128

        if pass_short:
            errors.append('Pick a longer password')
        if pass_long:
            errors.append('Pick a shorter password')

        if len(errors) > 0:
            if selected_option == 'token':
                return render_template('register.html',
                                       errors=errors,
                                       token=request.form['token'],
                                       password=request.form['password'])
            elif selected_option == 'email':
                return render_template('register.html',
                                       errors=errors,
                                       email=request.form['email'],
                                       password=request.form['password'])
            else:
                return render_template('register.html')
        else:
            with app.app_context():
                name = invited_team.name
                email = invited_team.email
                team = Teams(name, email.lower(), password)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = utils.sha512(urandom(10))

                if (utils.can_send_mail()
                        and utils.get_config('verify_emails')):
                    db.session.close()
                    logger = logging.getLogger('regs')
                    logger.warn('[{0}] {1} registered (UNCONFIRMED) ' \
                                'with {2}'.format(
                                    time.strftime('%m/%d/%Y %X'),
                                    name.encode('utf-8'),
                                    email.encode('utf-8')))

                    utils.verify_email(team.email)

                    return redirect(url_for('auth.confirm_user'))
                else:
                    if utils.can_send_mail():
                        utils.sendmail(email, "You've successfully " \
                                       "registered for {}".format(
                                           utils.get_config('ctf_name')))

        db.session.close()

        logger = logging.getLogger('regs')
        logger.warn('[{0}] {1} registered with {2}'.format(
            time.strftime('%m/%d/%Y %X'), name.encode('utf-8'),
            email.encode('utf-8')))
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Ejemplo n.º 17
0
def register_smart():
    logger = logging.getLogger('regs')
    if not utils.can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']
        color = request.form['color']
        school = request.form['school']
        image = request.form['image']
        #school = request.form['school']
        if not color in teamColors:
            color = "RED"
        if not image in teamImages:
            image = "HULK"
        name_len = len(name) == 0
        names = Teams.query.add_columns('name',
                                        'id').filter_by(name=name).first()
        emails = Teams.query.add_columns('email',
                                         'id').filter_by(email=email).first()
        smart_color = SmartCityTeam.query.filter_by(color=color).first()
        smart_image = SmartCityTeam.query.filter_by(image=image).first()
        #challenge = SmartCityChallenge.query.filter_by(id=challenge.id).first()
        pass_short = len(password) == 0
        pass_long = len(password) > 128
        valid_email = utils.check_email_format(request.form['email'])
        team_name_email_check = utils.check_email_format(name)

        if not valid_email:
            errors.append("Please enter a valid email address")
        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 smart_color:
            if not Teams.query.filter_by(id=smart_color.teamId).first().admin:
                errors.append(
                    'Color unavailable. The following colors are available:  \n'
                    + getAvailableColors())
        if smart_image:
            if not Teams.query.filter_by(id=smart_image.teamId).first().admin:
                errors.append('That image 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'])
        else:
            with app.app_context():
                team = Teams(name, email.lower(), password)
                db.session.add(team)
                db.session.commit()
                db.session.flush()

                smart_team = SmartCityTeam(team.id, team.name, color, image,
                                           school)
                db.session.add(smart_team)
                db.session.commit()
                db.session.flush()

                session['username'] = team.name
                session['id'] = team.id
                session['admin'] = team.admin
                session['nonce'] = utils.sha512(os.urandom(10))

                if utils.can_send_mail() and utils.get_config(
                        'verify_emails'
                ):  # Confirming users is enabled and we can send email.
                    logger = logging.getLogger('regs')
                    logger.warn(
                        "[{date}] {ip} - {username} registered (UNCONFIRMED) with {email}"
                        .format(date=time.strftime("%m/%d/%Y %X"),
                                ip=utils.get_ip(),
                                username=request.form['name'].encode('utf-8'),
                                email=request.form['email'].encode('utf-8')))
                    utils.verify_email(team.email)
                    db.session.close()
                    return redirect(url_for('auth.confirm_user'))
                else:  # Don't care about confirming users
                    if utils.can_send_mail(
                    ):  # We want to notify the user that they have registered.
                        utils.sendmail(
                            request.form['email'],
                            "You've successfully registered for {}".format(
                                utils.get_config('ctf_name')))

        logger.warn(
            "[{date}] {ip} - {username} registered with {email}".format(
                date=time.strftime("%m/%d/%Y %X"),
                ip=utils.get_ip(),
                username=request.form['name'].encode('utf-8'),
                email=request.form['email'].encode('utf-8')))
        db.session.close()
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')