id
int64
0
190k
prompt
stringlengths
21
13.4M
docstring
stringlengths
1
12k
158,349
from alembic import op from sqlalchemy.sql import column, table from CTFd.models import db configs_table = table( "config", column("id", db.Integer), column("key", db.Text), column("value", db.Text) ) def upgrade(): connection = op.get_bind() css = connection.execute( configs_table.select().where(configs_table.c.key == "css").limit(1) ).fetchone() if css and css.value: new_css = "<style>\n" + css.value + "\n</style>" config = connection.execute( configs_table.select().where(configs_table.c.key == "theme_header").limit(1) ).fetchone() if config: # Do not overwrite existing theme_header value pass else: connection.execute( configs_table.insert().values(key="theme_header", value=new_css) )
null
158,350
from alembic import op from sqlalchemy.sql import column, table from CTFd.models import db def downgrade(): pass
null
158,351
from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "comments", sa.Column("id", sa.Integer(), nullable=False), sa.Column("type", sa.String(length=80), nullable=True), sa.Column("content", sa.Text(), nullable=True), sa.Column("date", sa.DateTime(), nullable=True), sa.Column("author_id", sa.Integer(), nullable=True), sa.Column("challenge_id", sa.Integer(), nullable=True), sa.Column("user_id", sa.Integer(), nullable=True), sa.Column("team_id", sa.Integer(), nullable=True), sa.Column("page_id", sa.Integer(), nullable=True), sa.ForeignKeyConstraint(["author_id"], ["users.id"], ondelete="CASCADE"), sa.ForeignKeyConstraint( ["challenge_id"], ["challenges.id"], ondelete="CASCADE" ), sa.ForeignKeyConstraint(["page_id"], ["pages.id"], ondelete="CASCADE"), sa.ForeignKeyConstraint(["team_id"], ["teams.id"], ondelete="CASCADE"), sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"), sa.PrimaryKeyConstraint("id"), ) # ### end Alembic commands ###
null
158,352
from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table("comments") # ### end Alembic commands ###
null
158,353
from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column("pages", sa.Column("format", sa.String(length=80), nullable=True)) # ### end Alembic commands ###
null
158,354
from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column("pages", "format") # ### end Alembic commands ###
null
158,355
import sqlalchemy as sa from alembic import op def upgrade(): op.create_table( "tokens", sa.Column("id", sa.Integer(), nullable=False), sa.Column("type", sa.String(length=32), nullable=True), sa.Column("user_id", sa.Integer(), nullable=True), sa.Column("created", sa.DateTime(), nullable=True), sa.Column("expiration", sa.DateTime(), nullable=True), sa.Column("value", sa.String(length=128), nullable=True), sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("value"), )
null
158,356
import sqlalchemy as sa from alembic import op def downgrade(): op.drop_table("tokens")
null
158,357
import sqlalchemy as sa from alembic import op from sqlalchemy.sql import column, table from CTFd.models import db teams_table = table("teams", column("id", db.Integer), column("captain_id", db.Integer)) users_table = table("users", column("id", db.Integer), column("team_id", db.Integer)) def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column("teams", sa.Column("captain_id", sa.Integer(), nullable=True)) bind = op.get_bind() url = str(bind.engine.url) if url.startswith("sqlite") is False: op.create_foreign_key( "team_captain_id", "teams", "users", ["captain_id"], ["id"] ) connection = op.get_bind() for team in connection.execute(teams_table.select()): users = connection.execute( users_table.select() .where(users_table.c.team_id == team.id) .order_by(users_table.c.id) .limit(1) ) for user in users: connection.execute( teams_table.update() .where(teams_table.c.id == team.id) .values(captain_id=user.id) ) # ### end Alembic commands ###
null
158,358
import sqlalchemy as sa from alembic import op from sqlalchemy.sql import column, table from CTFd.models import db def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_constraint("team_captain_id", "teams", type_="foreignkey") op.drop_column("teams", "captain_id") # ### end Alembic commands ###
null
158,359
import sqlalchemy as sa from alembic import op def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "challenges", sa.Column("id", sa.Integer(), nullable=False), sa.Column("name", sa.String(length=80), nullable=True), sa.Column("description", sa.Text(), nullable=True), sa.Column("max_attempts", sa.Integer(), nullable=True), sa.Column("value", sa.Integer(), nullable=True), sa.Column("category", sa.String(length=80), nullable=True), sa.Column("type", sa.String(length=80), nullable=True), sa.Column("state", sa.String(length=80), nullable=False), sa.Column("requirements", sa.JSON(), nullable=True), sa.PrimaryKeyConstraint("id"), ) op.create_table( "config", sa.Column("id", sa.Integer(), nullable=False), sa.Column("key", sa.Text(), nullable=True), sa.Column("value", sa.Text(), nullable=True), sa.PrimaryKeyConstraint("id"), ) op.create_table( "pages", sa.Column("id", sa.Integer(), nullable=False), sa.Column("title", sa.String(length=80), nullable=True), sa.Column("route", sa.String(length=128), nullable=True), sa.Column("content", sa.Text(), nullable=True), sa.Column("draft", sa.Boolean(), nullable=True), sa.Column("hidden", sa.Boolean(), nullable=True), sa.Column("auth_required", sa.Boolean(), nullable=True), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("route"), ) op.create_table( "teams", sa.Column("id", sa.Integer(), nullable=False), sa.Column("oauth_id", sa.Integer(), nullable=True), sa.Column("name", sa.String(length=128), nullable=True), sa.Column("email", sa.String(length=128), nullable=True), sa.Column("password", sa.String(length=128), nullable=True), sa.Column("secret", sa.String(length=128), nullable=True), sa.Column("website", sa.String(length=128), nullable=True), sa.Column("affiliation", sa.String(length=128), nullable=True), sa.Column("country", sa.String(length=32), nullable=True), sa.Column("bracket", sa.String(length=32), nullable=True), sa.Column("hidden", sa.Boolean(), nullable=True), sa.Column("banned", sa.Boolean(), nullable=True), sa.Column("created", sa.DateTime(), nullable=True), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("email"), sa.UniqueConstraint("id", "oauth_id"), sa.UniqueConstraint("oauth_id"), ) op.create_table( "dynamic_challenge", sa.Column("id", sa.Integer(), nullable=False), sa.Column("initial", sa.Integer(), nullable=True), sa.Column("minimum", sa.Integer(), nullable=True), sa.Column("decay", sa.Integer(), nullable=True), sa.ForeignKeyConstraint(["id"], ["challenges.id"]), sa.PrimaryKeyConstraint("id"), ) op.create_table( "files", sa.Column("id", sa.Integer(), nullable=False), sa.Column("type", sa.String(length=80), nullable=True), sa.Column("location", sa.Text(), nullable=True), sa.Column("challenge_id", sa.Integer(), nullable=True), sa.Column("page_id", sa.Integer(), nullable=True), sa.ForeignKeyConstraint(["challenge_id"], ["challenges.id"]), sa.ForeignKeyConstraint(["page_id"], ["pages.id"]), sa.PrimaryKeyConstraint("id"), ) op.create_table( "flags", sa.Column("id", sa.Integer(), nullable=False), sa.Column("challenge_id", sa.Integer(), nullable=True), sa.Column("type", sa.String(length=80), nullable=True), sa.Column("content", sa.Text(), nullable=True), sa.Column("data", sa.Text(), nullable=True), sa.ForeignKeyConstraint(["challenge_id"], ["challenges.id"]), sa.PrimaryKeyConstraint("id"), ) op.create_table( "hints", sa.Column("id", sa.Integer(), nullable=False), sa.Column("type", sa.String(length=80), nullable=True), sa.Column("challenge_id", sa.Integer(), nullable=True), sa.Column("content", sa.Text(), nullable=True), sa.Column("cost", sa.Integer(), nullable=True), sa.Column("requirements", sa.JSON(), nullable=True), sa.ForeignKeyConstraint(["challenge_id"], ["challenges.id"]), sa.PrimaryKeyConstraint("id"), ) op.create_table( "tags", sa.Column("id", sa.Integer(), nullable=False), sa.Column("challenge_id", sa.Integer(), nullable=True), sa.Column("value", sa.String(length=80), nullable=True), sa.ForeignKeyConstraint(["challenge_id"], ["challenges.id"]), sa.PrimaryKeyConstraint("id"), ) op.create_table( "users", sa.Column("id", sa.Integer(), nullable=False), sa.Column("oauth_id", sa.Integer(), nullable=True), sa.Column("name", sa.String(length=128), nullable=True), sa.Column("password", sa.String(length=128), nullable=True), sa.Column("email", sa.String(length=128), nullable=True), sa.Column("type", sa.String(length=80), nullable=True), sa.Column("secret", sa.String(length=128), nullable=True), sa.Column("website", sa.String(length=128), nullable=True), sa.Column("affiliation", sa.String(length=128), nullable=True), sa.Column("country", sa.String(length=32), nullable=True), sa.Column("bracket", sa.String(length=32), nullable=True), sa.Column("hidden", sa.Boolean(), nullable=True), sa.Column("banned", sa.Boolean(), nullable=True), sa.Column("verified", sa.Boolean(), nullable=True), sa.Column("team_id", sa.Integer(), nullable=True), sa.Column("created", sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(["team_id"], ["teams.id"]), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("email"), sa.UniqueConstraint("id", "oauth_id"), sa.UniqueConstraint("oauth_id"), ) op.create_table( "awards", sa.Column("id", sa.Integer(), nullable=False), sa.Column("user_id", sa.Integer(), nullable=True), sa.Column("team_id", sa.Integer(), nullable=True), sa.Column("name", sa.String(length=80), nullable=True), sa.Column("description", sa.Text(), nullable=True), sa.Column("date", sa.DateTime(), nullable=True), sa.Column("value", sa.Integer(), nullable=True), sa.Column("category", sa.String(length=80), nullable=True), sa.Column("icon", sa.Text(), nullable=True), sa.Column("requirements", sa.JSON(), nullable=True), sa.ForeignKeyConstraint(["team_id"], ["teams.id"]), sa.ForeignKeyConstraint(["user_id"], ["users.id"]), sa.PrimaryKeyConstraint("id"), ) op.create_table( "notifications", sa.Column("id", sa.Integer(), nullable=False), sa.Column("title", sa.Text(), nullable=True), sa.Column("content", sa.Text(), nullable=True), sa.Column("date", sa.DateTime(), nullable=True), sa.Column("user_id", sa.Integer(), nullable=True), sa.Column("team_id", sa.Integer(), nullable=True), sa.ForeignKeyConstraint(["team_id"], ["teams.id"]), sa.ForeignKeyConstraint(["user_id"], ["users.id"]), sa.PrimaryKeyConstraint("id"), ) op.create_table( "submissions", sa.Column("id", sa.Integer(), nullable=False), sa.Column("challenge_id", sa.Integer(), nullable=True), sa.Column("user_id", sa.Integer(), nullable=True), sa.Column("team_id", sa.Integer(), nullable=True), sa.Column("ip", sa.String(length=46), nullable=True), sa.Column("provided", sa.Text(), nullable=True), sa.Column("type", sa.String(length=32), nullable=True), sa.Column("date", sa.DateTime(), nullable=True), sa.ForeignKeyConstraint( ["challenge_id"], ["challenges.id"], ondelete="CASCADE" ), sa.ForeignKeyConstraint(["team_id"], ["teams.id"], ondelete="CASCADE"), sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"), sa.PrimaryKeyConstraint("id"), ) op.create_table( "tracking", sa.Column("id", sa.Integer(), nullable=False), sa.Column("type", sa.String(length=32), nullable=True), sa.Column("ip", sa.String(length=46), nullable=True), sa.Column("user_id", sa.Integer(), nullable=True), sa.Column("date", sa.DateTime(), nullable=True), sa.ForeignKeyConstraint(["user_id"], ["users.id"]), sa.PrimaryKeyConstraint("id"), ) op.create_table( "unlocks", sa.Column("id", sa.Integer(), nullable=False), sa.Column("user_id", sa.Integer(), nullable=True), sa.Column("team_id", sa.Integer(), nullable=True), sa.Column("target", sa.Integer(), nullable=True), sa.Column("date", sa.DateTime(), nullable=True), sa.Column("type", sa.String(length=32), nullable=True), sa.ForeignKeyConstraint(["team_id"], ["teams.id"]), sa.ForeignKeyConstraint(["user_id"], ["users.id"]), sa.PrimaryKeyConstraint("id"), ) op.create_table( "solves", sa.Column("id", sa.Integer(), nullable=False), sa.Column("challenge_id", sa.Integer(), nullable=True), sa.Column("user_id", sa.Integer(), nullable=True), sa.Column("team_id", sa.Integer(), nullable=True), sa.ForeignKeyConstraint( ["challenge_id"], ["challenges.id"], ondelete="CASCADE" ), sa.ForeignKeyConstraint(["id"], ["submissions.id"], ondelete="CASCADE"), sa.ForeignKeyConstraint(["team_id"], ["teams.id"], ondelete="CASCADE"), sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"), sa.PrimaryKeyConstraint("id"), sa.UniqueConstraint("challenge_id", "team_id"), sa.UniqueConstraint("challenge_id", "user_id"), ) # ### end Alembic commands ###
null
158,360
import sqlalchemy as sa from alembic import op def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table("solves") op.drop_table("unlocks") op.drop_table("tracking") op.drop_table("submissions") op.drop_table("notifications") op.drop_table("awards") op.drop_table("users") op.drop_table("tags") op.drop_table("hints") op.drop_table("flags") op.drop_table("files") op.drop_table("dynamic_challenge") op.drop_table("teams") op.drop_table("pages") op.drop_table("config") op.drop_table("challenges") # ### end Alembic commands ###
null
158,361
import sqlalchemy as sa from alembic import op def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.add_column( "awards", sa.Column( "type", sa.String(length=80), nullable=True, server_default="standard" ), ) # ### end Alembic commands ###
null
158,362
import sqlalchemy as sa from alembic import op def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_column("awards", "type") # ### end Alembic commands ###
null
158,363
from alembic import op from sqlalchemy.sql import column, table from CTFd.models import db from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) def get_config(key): def set_config(key, value): DEFAULT_VERIFICATION_EMAIL_SUBJECT = "Confirm your account for {ctf_name}" DEFAULT_VERIFICATION_EMAIL_BODY = ( "Welcome to {ctf_name}!\n\n" "Click the following link to confirm and activate your account:\n" "{url}" "\n\n" "If the link is not clickable, try copying and pasting it into your browser." ) DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT = "Successfully registered for {ctf_name}" DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY = ( "You've successfully registered for {ctf_name}!" ) DEFAULT_USER_CREATION_EMAIL_SUBJECT = "Message from {ctf_name}" DEFAULT_USER_CREATION_EMAIL_BODY = ( "A new account has been created for you for {ctf_name} at {url}. \n\n" "Username: {name}\n" "Password: {password}" ) DEFAULT_PASSWORD_RESET_SUBJECT = "Password Reset Request from {ctf_name}" DEFAULT_PASSWORD_RESET_BODY = ( "Did you initiate a password reset on {ctf_name}? " "If you didn't initiate this request you can ignore this email. \n\n" "Click the following link to reset your password:\n{url}\n\n" "If the link is not clickable, try copying and pasting it into your browser." ) def upgrade(): # Only run if this instance already been setup before if bool(get_config("setup")) is True: for k, v in [ ("password_reset_body", DEFAULT_PASSWORD_RESET_BODY), ("password_reset_subject", DEFAULT_PASSWORD_RESET_SUBJECT), ( "successful_registration_email_body", DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, ), ( "successful_registration_email_subject", DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, ), ("user_creation_email_body", DEFAULT_USER_CREATION_EMAIL_BODY), ("user_creation_email_subject", DEFAULT_USER_CREATION_EMAIL_SUBJECT), ("verification_email_body", DEFAULT_VERIFICATION_EMAIL_BODY), ("verification_email_subject", DEFAULT_VERIFICATION_EMAIL_SUBJECT), ]: if get_config(k) is None: set_config(k, v)
null
158,364
from alembic import op from sqlalchemy.sql import column, table from CTFd.models import db from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) def downgrade(): pass
null
158,365
from alembic import op import sqlalchemy as sa def upgrade(): # ### commands auto generated by Alembic - please adjust! ### op.create_table( "fields", sa.Column("id", sa.Integer(), nullable=False), sa.Column("name", sa.Text(), nullable=True), sa.Column("type", sa.String(length=80), nullable=True), sa.Column("field_type", sa.String(length=80), nullable=True), sa.Column("description", sa.Text(), nullable=True), sa.Column("required", sa.Boolean(), nullable=True), sa.Column("public", sa.Boolean(), nullable=True), sa.Column("editable", sa.Boolean(), nullable=True), sa.PrimaryKeyConstraint("id"), ) op.create_table( "field_entries", sa.Column("id", sa.Integer(), nullable=False), sa.Column("type", sa.String(length=80), nullable=True), sa.Column("value", sa.JSON(), nullable=True), sa.Column("field_id", sa.Integer(), nullable=True), sa.Column("user_id", sa.Integer(), nullable=True), sa.Column("team_id", sa.Integer(), nullable=True), sa.ForeignKeyConstraint(["field_id"], ["fields.id"], ondelete="CASCADE"), sa.ForeignKeyConstraint(["team_id"], ["teams.id"], ondelete="CASCADE"), sa.ForeignKeyConstraint(["user_id"], ["users.id"], ondelete="CASCADE"), sa.PrimaryKeyConstraint("id"), ) # ### end Alembic commands ###
null
158,366
from alembic import op import sqlalchemy as sa def downgrade(): # ### commands auto generated by Alembic - please adjust! ### op.drop_table("field_entries") op.drop_table("fields") # ### end Alembic commands ###
null
158,367
from __future__ import with_statement import logging from logging.config import fileConfig from sqlalchemy import engine_from_config from sqlalchemy import pool from alembic import context config = context.config from flask import current_app config.set_main_option( "sqlalchemy.url", str(current_app.extensions["migrate"].db.engine.url).replace("%", "%%"), ) target_metadata = current_app.extensions["migrate"].db.metadata if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online() The provided code snippet includes necessary dependencies for implementing the `run_migrations_offline` function. Write a Python function `def run_migrations_offline()` to solve the following problem: Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. Here is the function: def run_migrations_offline(): """Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output. """ url = config.get_main_option("sqlalchemy.url") context.configure(url=url, target_metadata=target_metadata, literal_binds=True) with context.begin_transaction(): context.run_migrations()
Run migrations in 'offline' mode. This configures the context with just a URL and not an Engine, though an Engine is acceptable here as well. By skipping the Engine creation we don't even need a DBAPI to be available. Calls to context.execute() here emit the given string to the script output.
158,368
from __future__ import with_statement import logging from logging.config import fileConfig from sqlalchemy import engine_from_config from sqlalchemy import pool from alembic import context config = context.config logger = logging.getLogger("alembic.env") from flask import current_app config.set_main_option( "sqlalchemy.url", str(current_app.extensions["migrate"].db.engine.url).replace("%", "%%"), ) target_metadata = current_app.extensions["migrate"].db.metadata if context.is_offline_mode(): run_migrations_offline() else: run_migrations_online() The provided code snippet includes necessary dependencies for implementing the `run_migrations_online` function. Write a Python function `def run_migrations_online()` to solve the following problem: Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. Here is the function: def run_migrations_online(): """Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context. """ # this callback is used to prevent an auto-migration from being generated # when there are no changes to the schema # reference: http://alembic.zzzcomputing.com/en/latest/cookbook.html def process_revision_directives(context, revision, directives): if getattr(config.cmd_opts, "autogenerate", False): script = directives[0] if script.upgrade_ops.is_empty(): directives[:] = [] logger.info("No changes in schema detected.") connectable = engine_from_config( config.get_section(config.config_ini_section), prefix="sqlalchemy.", poolclass=pool.NullPool, ) with connectable.connect() as connection: context.configure( connection=connection, target_metadata=target_metadata, process_revision_directives=process_revision_directives, **current_app.extensions["migrate"].configure_args ) with context.begin_transaction(): context.run_migrations()
Run migrations in 'online' mode. In this scenario we need to create an Engine and associate a connection with the context.
158,369
from flask import Blueprint, render_template, request, url_for from CTFd.models import Users from CTFd.utils import config from CTFd.utils.decorators import authed_only from CTFd.utils.decorators.visibility import ( check_account_visibility, check_score_visibility, ) from CTFd.utils.helpers import get_errors, get_infos from CTFd.utils.user import get_current_user users = Blueprint("users", __name__) class Users(db.Model): __tablename__ = "users" __table_args__ = (db.UniqueConstraint("id", "oauth_id"), {}) # Core attributes id = db.Column(db.Integer, primary_key=True) oauth_id = db.Column(db.Integer, unique=True) # User names are not constrained to be unique to allow for official/unofficial teams. name = db.Column(db.String(128)) password = db.Column(db.String(128)) email = db.Column(db.String(128), unique=True) type = db.Column(db.String(80)) secret = db.Column(db.String(128)) # Supplementary attributes website = db.Column(db.String(128)) affiliation = db.Column(db.String(128)) country = db.Column(db.String(32)) bracket = db.Column(db.String(32)) hidden = db.Column(db.Boolean, default=False) banned = db.Column(db.Boolean, default=False) verified = db.Column(db.Boolean, default=False) # Relationship for Teams team_id = db.Column(db.Integer, db.ForeignKey("teams.id")) field_entries = db.relationship( "UserFieldEntries", foreign_keys="UserFieldEntries.user_id", lazy="joined" ) created = db.Column(db.DateTime, default=datetime.datetime.utcnow) __mapper_args__ = {"polymorphic_identity": "user", "polymorphic_on": type} def __init__(self, **kwargs): super(Users, self).__init__(**kwargs) def validate_password(self, key, plaintext): from CTFd.utils.crypto import hash_password return hash_password(str(plaintext)) def account_id(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team_id elif user_mode == "users": return self.id def account(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team elif user_mode == "users": return self def fields(self): return self.get_fields(admin=False) def solves(self): return self.get_solves(admin=False) def fails(self): return self.get_fails(admin=False) def awards(self): return self.get_awards(admin=False) def score(self): return self.get_score(admin=False) def place(self): from CTFd.utils.config.visibility import scores_visible if scores_visible(): return self.get_place(admin=False) else: return None def get_fields(self, admin=False): if admin: return self.field_entries return [ entry for entry in self.field_entries if entry.field.public and entry.value ] def get_solves(self, admin=False): from CTFd.utils import get_config solves = Solves.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) solves = solves.filter(Solves.date < dt) return solves.all() def get_fails(self, admin=False): from CTFd.utils import get_config fails = Fails.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) fails = fails.filter(Fails.date < dt) return fails.all() def get_awards(self, admin=False): from CTFd.utils import get_config awards = Awards.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) awards = awards.filter(Awards.date < dt) return awards.all() def get_score(self, admin=False): score = db.func.sum(Challenges.value).label("score") user = ( db.session.query(Solves.user_id, score) .join(Users, Solves.user_id == Users.id) .join(Challenges, Solves.challenge_id == Challenges.id) .filter(Users.id == self.id) ) award_score = db.func.sum(Awards.value).label("award_score") award = db.session.query(award_score).filter_by(user_id=self.id) if not admin: freeze = Configs.query.filter_by(key="freeze").first() if freeze and freeze.value: freeze = int(freeze.value) freeze = datetime.datetime.utcfromtimestamp(freeze) user = user.filter(Solves.date < freeze) award = award.filter(Awards.date < freeze) user = user.group_by(Solves.user_id).first() award = award.first() if user and award: return int(user.score or 0) + int(award.award_score or 0) elif user: return int(user.score or 0) elif award: return int(award.award_score or 0) else: return 0 def get_place(self, admin=False, numeric=False): """ This method is generally a clone of CTFd.scoreboard.get_standings. The point being that models.py must be self-reliant and have little to no imports within the CTFd application as importing from the application itself will result in a circular import. """ from CTFd.utils.scores import get_user_standings from CTFd.utils.humanize.numbers import ordinalize standings = get_user_standings(admin=admin) for i, user in enumerate(standings): if user.user_id == self.id: n = i + 1 if numeric: return n return ordinalize(n) else: return None def listing(): q = request.args.get("q") field = request.args.get("field", "name") if field not in ("name", "affiliation", "website"): field = "name" filters = [] if q: filters.append(getattr(Users, field).like("%{}%".format(q))) users = ( Users.query.filter_by(banned=False, hidden=False) .filter(*filters) .order_by(Users.id.asc()) .paginate(per_page=50) ) args = dict(request.args) args.pop("page", 1) return render_template( "users/users.html", users=users, prev_page=url_for(request.endpoint, page=users.prev_num, **args), next_page=url_for(request.endpoint, page=users.next_num, **args), q=q, field=field, )
null
158,370
from flask import Blueprint, render_template, request, url_for from CTFd.models import Users from CTFd.utils import config from CTFd.utils.decorators import authed_only from CTFd.utils.decorators.visibility import ( check_account_visibility, check_score_visibility, ) from CTFd.utils.helpers import get_errors, get_infos from CTFd.utils.user import get_current_user def get_infos(): return get_flashed_messages(category_filter=request.endpoint + ".infos") def get_errors(): return get_flashed_messages(category_filter=request.endpoint + ".errors") def get_current_user(): if authed(): user = Users.query.filter_by(id=session["id"]).first() # Check if the session is still valid session_hash = session.get("hash") if session_hash: if session_hash != hmac(user.password): logout_user() if request.content_type == "application/json": error = 401 else: error = redirect(url_for("auth.login", next=request.full_path)) abort(error) return user else: return None def private(): infos = get_infos() errors = get_errors() user = get_current_user() if config.is_scoreboard_frozen(): infos.append("Scoreboard has been frozen") return render_template( "users/private.html", user=user, account=user.account, infos=infos, errors=errors, )
null
158,371
from flask import Blueprint, render_template, request, url_for from CTFd.models import Users from CTFd.utils import config from CTFd.utils.decorators import authed_only from CTFd.utils.decorators.visibility import ( check_account_visibility, check_score_visibility, ) from CTFd.utils.helpers import get_errors, get_infos from CTFd.utils.user import get_current_user class Users(db.Model): __tablename__ = "users" __table_args__ = (db.UniqueConstraint("id", "oauth_id"), {}) # Core attributes id = db.Column(db.Integer, primary_key=True) oauth_id = db.Column(db.Integer, unique=True) # User names are not constrained to be unique to allow for official/unofficial teams. name = db.Column(db.String(128)) password = db.Column(db.String(128)) email = db.Column(db.String(128), unique=True) type = db.Column(db.String(80)) secret = db.Column(db.String(128)) # Supplementary attributes website = db.Column(db.String(128)) affiliation = db.Column(db.String(128)) country = db.Column(db.String(32)) bracket = db.Column(db.String(32)) hidden = db.Column(db.Boolean, default=False) banned = db.Column(db.Boolean, default=False) verified = db.Column(db.Boolean, default=False) # Relationship for Teams team_id = db.Column(db.Integer, db.ForeignKey("teams.id")) field_entries = db.relationship( "UserFieldEntries", foreign_keys="UserFieldEntries.user_id", lazy="joined" ) created = db.Column(db.DateTime, default=datetime.datetime.utcnow) __mapper_args__ = {"polymorphic_identity": "user", "polymorphic_on": type} def __init__(self, **kwargs): super(Users, self).__init__(**kwargs) def validate_password(self, key, plaintext): from CTFd.utils.crypto import hash_password return hash_password(str(plaintext)) def account_id(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team_id elif user_mode == "users": return self.id def account(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team elif user_mode == "users": return self def fields(self): return self.get_fields(admin=False) def solves(self): return self.get_solves(admin=False) def fails(self): return self.get_fails(admin=False) def awards(self): return self.get_awards(admin=False) def score(self): return self.get_score(admin=False) def place(self): from CTFd.utils.config.visibility import scores_visible if scores_visible(): return self.get_place(admin=False) else: return None def get_fields(self, admin=False): if admin: return self.field_entries return [ entry for entry in self.field_entries if entry.field.public and entry.value ] def get_solves(self, admin=False): from CTFd.utils import get_config solves = Solves.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) solves = solves.filter(Solves.date < dt) return solves.all() def get_fails(self, admin=False): from CTFd.utils import get_config fails = Fails.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) fails = fails.filter(Fails.date < dt) return fails.all() def get_awards(self, admin=False): from CTFd.utils import get_config awards = Awards.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) awards = awards.filter(Awards.date < dt) return awards.all() def get_score(self, admin=False): score = db.func.sum(Challenges.value).label("score") user = ( db.session.query(Solves.user_id, score) .join(Users, Solves.user_id == Users.id) .join(Challenges, Solves.challenge_id == Challenges.id) .filter(Users.id == self.id) ) award_score = db.func.sum(Awards.value).label("award_score") award = db.session.query(award_score).filter_by(user_id=self.id) if not admin: freeze = Configs.query.filter_by(key="freeze").first() if freeze and freeze.value: freeze = int(freeze.value) freeze = datetime.datetime.utcfromtimestamp(freeze) user = user.filter(Solves.date < freeze) award = award.filter(Awards.date < freeze) user = user.group_by(Solves.user_id).first() award = award.first() if user and award: return int(user.score or 0) + int(award.award_score or 0) elif user: return int(user.score or 0) elif award: return int(award.award_score or 0) else: return 0 def get_place(self, admin=False, numeric=False): """ This method is generally a clone of CTFd.scoreboard.get_standings. The point being that models.py must be self-reliant and have little to no imports within the CTFd application as importing from the application itself will result in a circular import. """ from CTFd.utils.scores import get_user_standings from CTFd.utils.humanize.numbers import ordinalize standings = get_user_standings(admin=admin) for i, user in enumerate(standings): if user.user_id == self.id: n = i + 1 if numeric: return n return ordinalize(n) else: return None def get_infos(): return get_flashed_messages(category_filter=request.endpoint + ".infos") def get_errors(): return get_flashed_messages(category_filter=request.endpoint + ".errors") def public(user_id): infos = get_infos() errors = get_errors() user = Users.query.filter_by(id=user_id, banned=False, hidden=False).first_or_404() if config.is_scoreboard_frozen(): infos.append("Scoreboard has been frozen") return render_template( "users/public.html", user=user, account=user.account, infos=infos, errors=errors )
null
158,372
import configparser import os from distutils.util import strtobool def process_string_var(value): if value == "": return None if value.isdigit(): return int(value) elif value.replace(".", "", 1).isdigit(): return float(value) try: return bool(strtobool(value)) except ValueError: return value
null
158,373
import configparser import os from distutils.util import strtobool def process_boolean_str(value): if type(value) is bool: return value if value is None: return False if value == "": return None return bool(strtobool(value))
null
158,374
import configparser import os from distutils.util import strtobool def empty_str_cast(value, default=None): if value == "": return default return value
null
158,375
import configparser import os from distutils.util import strtobool def gen_secret_key(): # Attempt to read the secret from the secret file # This will fail if the secret has not been written try: with open(".ctfd_secret_key", "rb") as secret: key = secret.read() except OSError: key = None if not key: key = os.urandom(64) # Attempt to write the secret file # This will fail if the filesystem is read-only try: with open(".ctfd_secret_key", "wb") as secret: secret.write(key) secret.flush() except OSError: pass return key
null
158,376
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker fake = Faker() def gen_sentence(): return fake.text()
null
158,377
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker fake = Faker() def gen_name(): return fake.first_name()
null
158,378
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker fake = Faker() def gen_team_name(): return fake.word().capitalize() + str(random.randint(1, 1000))
null
158,379
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker fake = Faker() def gen_email(): return fake.email()
null
158,380
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker categories = [ "Exploitation", "Reversing", "Web", "Forensics", "Scripting", "Cryptography", "Networking", ] def gen_category(): return random.choice(categories)
null
158,381
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker fake = Faker() companies = ["Corp", "Inc.", "Squad", "Team"] def gen_affiliation(): return (fake.word() + " " + random.choice(companies)).title()
null
158,382
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker def gen_value(): return random.choice(range(100, 500, 50))
null
158,383
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker fake = Faker() def gen_word(): return fake.word()
null
158,384
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker icons = [ None, "shield", "bug", "crown", "crosshairs", "ban", "lightning", "code", "cowboy", "angry", ] def gen_icon(): return random.choice(icons)
null
158,385
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker fake = Faker() def gen_file(): return fake.file_name()
null
158,386
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker fake = Faker() def gen_ip(): return fake.ipv4()
null
158,387
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker def random_date(start, end): return start + datetime.timedelta( seconds=random.randint(0, int((end - start).total_seconds())) )
null
158,388
import datetime import hashlib import random import argparse from CTFd import create_app from CTFd.cache import clear_config, clear_standings, clear_pages from CTFd.models import ( Users, Teams, Challenges, Flags, Awards, ChallengeFiles, Fails, Solves, Tracking, ) from faker import Faker def random_chance(): return random.random() > 0.5
null
158,389
from flask import Blueprint, render_template from CTFd.utils import config from CTFd.utils.config.visibility import scores_visible from CTFd.utils.decorators.visibility import check_score_visibility from CTFd.utils.helpers import get_infos from CTFd.utils.scores import get_standings from CTFd.utils.user import is_admin def scores_visible(): v = get_config(ConfigTypes.SCORE_VISIBILITY) if v == ScoreVisibilityTypes.PUBLIC: return True elif v == ScoreVisibilityTypes.PRIVATE: return authed() elif v == ScoreVisibilityTypes.HIDDEN: return False elif v == ScoreVisibilityTypes.ADMINS: return is_admin() def get_infos(): return get_flashed_messages(category_filter=request.endpoint + ".infos") def get_standings(count=None, admin=False, fields=None): """ Get standings as a list of tuples containing account_id, name, and score e.g. [(account_id, team_name, score)]. Ties are broken by who reached a given score first based on the solve ID. Two users can have the same score but one user will have a solve ID that is before the others. That user will be considered the tie-winner. Challenges & Awards with a value of zero are filtered out of the calculations to avoid incorrect tie breaks. """ if fields is None: fields = [] Model = get_model() scores = ( db.session.query( Solves.account_id.label("account_id"), db.func.sum(Challenges.value).label("score"), db.func.max(Solves.id).label("id"), db.func.max(Solves.date).label("date"), ) .join(Challenges) .filter(Challenges.value != 0) .group_by(Solves.account_id) ) awards = ( db.session.query( Awards.account_id.label("account_id"), db.func.sum(Awards.value).label("score"), db.func.max(Awards.id).label("id"), db.func.max(Awards.date).label("date"), ) .filter(Awards.value != 0) .group_by(Awards.account_id) ) """ Filter out solves and awards that are before a specific time point. """ freeze = get_config("freeze") if not admin and freeze: scores = scores.filter(Solves.date < unix_time_to_utc(freeze)) awards = awards.filter(Awards.date < unix_time_to_utc(freeze)) """ Combine awards and solves with a union. They should have the same amount of columns """ results = union_all(scores, awards).alias("results") """ Sum each of the results by the team id to get their score. """ sumscores = ( db.session.query( results.columns.account_id, db.func.sum(results.columns.score).label("score"), db.func.max(results.columns.id).label("id"), db.func.max(results.columns.date).label("date"), ) .group_by(results.columns.account_id) .subquery() ) """ Admins can see scores for all users but the public cannot see banned users. Filters out banned users. Properly resolves value ties by ID. Different databases treat time precision differently so resolve by the row ID instead. """ if admin: standings_query = ( db.session.query( Model.id.label("account_id"), Model.oauth_id.label("oauth_id"), Model.name.label("name"), Model.hidden, Model.banned, sumscores.columns.score, *fields, ) .join(sumscores, Model.id == sumscores.columns.account_id) .order_by(sumscores.columns.score.desc(), sumscores.columns.id) ) else: standings_query = ( db.session.query( Model.id.label("account_id"), Model.oauth_id.label("oauth_id"), Model.name.label("name"), sumscores.columns.score, *fields, ) .join(sumscores, Model.id == sumscores.columns.account_id) .filter(Model.banned == False, Model.hidden == False) .order_by(sumscores.columns.score.desc(), sumscores.columns.id) ) """ Only select a certain amount of users if asked. """ if count is None: standings = standings_query.all() else: standings = standings_query.limit(count).all() return standings def is_admin(): if authed(): user = get_current_user_attrs() return user.type == "admin" else: return False def listing(): infos = get_infos() if config.is_scoreboard_frozen(): infos.append("Scoreboard has been frozen") if is_admin() is True and scores_visible() is False: infos.append("Scores are not currently visible to users") standings = get_standings() return render_template("scoreboard.html", standings=standings, infos=infos)
null
158,390
from wtforms import BooleanField, PasswordField, SelectField, StringField from wtforms.fields.html5 import EmailField, URLField from wtforms.validators import InputRequired from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.models import TeamFieldEntries, TeamFields from CTFd.utils.countries import SELECT_COUNTRIES_LIST def build_custom_team_fields( form_cls, include_entries=False, fields_kwargs=None, field_entries_kwargs=None, blacklisted_items=("affiliation", "website"), ): if fields_kwargs is None: fields_kwargs = {} if field_entries_kwargs is None: field_entries_kwargs = {} fields = [] new_fields = TeamFields.query.filter_by(**fields_kwargs).all() user_fields = {} # Only include preexisting values if asked if include_entries is True: for f in TeamFieldEntries.query.filter_by(**field_entries_kwargs).all(): user_fields[f.field_id] = f.value for field in new_fields: if field.name.lower() in blacklisted_items: continue form_field = getattr(form_cls, f"fields[{field.id}]") # Add the field_type to the field so we know how to render it form_field.field_type = field.field_type # Only include preexisting values if asked if include_entries is True: initial = user_fields.get(field.id, "") form_field.data = initial if form_field.render_kw: form_field.render_kw["data-initial"] = initial else: form_field.render_kw = {"data-initial": initial} fields.append(form_field) return fields def attach_custom_team_fields(form_cls, **kwargs): new_fields = TeamFields.query.filter_by(**kwargs).all() for field in new_fields: validators = [] if field.required: validators.append(InputRequired()) if field.field_type == "text": input_field = StringField( field.name, description=field.description, validators=validators ) elif field.field_type == "boolean": input_field = BooleanField( field.name, description=field.description, validators=validators ) setattr(form_cls, f"fields[{field.id}]", input_field) class BaseForm(Form): class Meta: csrf = True csrf_class = CTFdCSRF csrf_field_name = "nonce" class SubmitField(_SubmitField): """ This custom SubmitField exists because wtforms is dumb. See https://github.com/wtforms/wtforms/issues/205, https://github.com/wtforms/wtforms/issues/36 The .submit() handler in JS will break if the form has an input with the name or id of "submit" so submit fields need to be changed. """ def __init__(self, *args, **kwargs): name = kwargs.pop("name", "_submit") super().__init__(*args, **kwargs) if self.name == "submit" or name: self.id = name self.name = name def TeamRegisterForm(*args, **kwargs): class _TeamRegisterForm(BaseForm): name = StringField("Team Name", validators=[InputRequired()]) password = PasswordField("Team Password", validators=[InputRequired()]) submit = SubmitField("Create") @property def extra(self): return build_custom_team_fields( self, include_entries=False, blacklisted_items=() ) attach_custom_team_fields(_TeamRegisterForm) return _TeamRegisterForm(*args, **kwargs)
null
158,391
from wtforms import BooleanField, PasswordField, SelectField, StringField from wtforms.fields.html5 import EmailField, URLField from wtforms.validators import InputRequired from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.models import TeamFieldEntries, TeamFields from CTFd.utils.countries import SELECT_COUNTRIES_LIST def build_custom_team_fields( form_cls, include_entries=False, fields_kwargs=None, field_entries_kwargs=None, blacklisted_items=("affiliation", "website"), ): if fields_kwargs is None: fields_kwargs = {} if field_entries_kwargs is None: field_entries_kwargs = {} fields = [] new_fields = TeamFields.query.filter_by(**fields_kwargs).all() user_fields = {} # Only include preexisting values if asked if include_entries is True: for f in TeamFieldEntries.query.filter_by(**field_entries_kwargs).all(): user_fields[f.field_id] = f.value for field in new_fields: if field.name.lower() in blacklisted_items: continue form_field = getattr(form_cls, f"fields[{field.id}]") # Add the field_type to the field so we know how to render it form_field.field_type = field.field_type # Only include preexisting values if asked if include_entries is True: initial = user_fields.get(field.id, "") form_field.data = initial if form_field.render_kw: form_field.render_kw["data-initial"] = initial else: form_field.render_kw = {"data-initial": initial} fields.append(form_field) return fields def attach_custom_team_fields(form_cls, **kwargs): new_fields = TeamFields.query.filter_by(**kwargs).all() for field in new_fields: validators = [] if field.required: validators.append(InputRequired()) if field.field_type == "text": input_field = StringField( field.name, description=field.description, validators=validators ) elif field.field_type == "boolean": input_field = BooleanField( field.name, description=field.description, validators=validators ) setattr(form_cls, f"fields[{field.id}]", input_field) class BaseForm(Form): class Meta: csrf = True csrf_class = CTFdCSRF csrf_field_name = "nonce" class SubmitField(_SubmitField): """ This custom SubmitField exists because wtforms is dumb. See https://github.com/wtforms/wtforms/issues/205, https://github.com/wtforms/wtforms/issues/36 The .submit() handler in JS will break if the form has an input with the name or id of "submit" so submit fields need to be changed. """ def __init__(self, *args, **kwargs): name = kwargs.pop("name", "_submit") super().__init__(*args, **kwargs) if self.name == "submit" or name: self.id = name self.name = name SELECT_COUNTRIES_LIST = [("", "")] + COUNTRIES_LIST def TeamSettingsForm(*args, **kwargs): class _TeamSettingsForm(BaseForm): name = StringField( "Team Name", description="Your team's public name shown to other competitors", ) password = PasswordField( "New Team Password", description="Set a new team join password" ) confirm = PasswordField( "Confirm Password", description="Provide your current team password (or your password) to update your team's password", ) affiliation = StringField( "Affiliation", description="Your team's affiliation publicly shown to other competitors", ) website = URLField( "Website", description="Your team's website publicly shown to other competitors", ) country = SelectField( "Country", choices=SELECT_COUNTRIES_LIST, description="Your team's country publicly shown to other competitors", ) submit = SubmitField("Submit") @property def extra(self): return build_custom_team_fields( self, include_entries=True, fields_kwargs={"editable": True}, field_entries_kwargs={"team_id": self.obj.id}, ) def __init__(self, *args, **kwargs): """ Custom init to persist the obj parameter to the rest of the form """ super().__init__(*args, **kwargs) obj = kwargs.get("obj") if obj: self.obj = obj attach_custom_team_fields(_TeamSettingsForm) return _TeamSettingsForm(*args, **kwargs)
null
158,392
from wtforms import BooleanField, PasswordField, SelectField, StringField from wtforms.fields.html5 import EmailField, URLField from wtforms.validators import InputRequired from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.models import TeamFieldEntries, TeamFields from CTFd.utils.countries import SELECT_COUNTRIES_LIST def build_custom_team_fields( form_cls, include_entries=False, fields_kwargs=None, field_entries_kwargs=None, blacklisted_items=("affiliation", "website"), ): if fields_kwargs is None: fields_kwargs = {} if field_entries_kwargs is None: field_entries_kwargs = {} fields = [] new_fields = TeamFields.query.filter_by(**fields_kwargs).all() user_fields = {} # Only include preexisting values if asked if include_entries is True: for f in TeamFieldEntries.query.filter_by(**field_entries_kwargs).all(): user_fields[f.field_id] = f.value for field in new_fields: if field.name.lower() in blacklisted_items: continue form_field = getattr(form_cls, f"fields[{field.id}]") # Add the field_type to the field so we know how to render it form_field.field_type = field.field_type # Only include preexisting values if asked if include_entries is True: initial = user_fields.get(field.id, "") form_field.data = initial if form_field.render_kw: form_field.render_kw["data-initial"] = initial else: form_field.render_kw = {"data-initial": initial} fields.append(form_field) return fields def attach_custom_team_fields(form_cls, **kwargs): new_fields = TeamFields.query.filter_by(**kwargs).all() for field in new_fields: validators = [] if field.required: validators.append(InputRequired()) if field.field_type == "text": input_field = StringField( field.name, description=field.description, validators=validators ) elif field.field_type == "boolean": input_field = BooleanField( field.name, description=field.description, validators=validators ) setattr(form_cls, f"fields[{field.id}]", input_field) class TeamBaseForm(BaseForm): name = StringField("Team Name", validators=[InputRequired()]) email = EmailField("Email") password = PasswordField("Password") website = URLField("Website") affiliation = StringField("Affiliation") country = SelectField("Country", choices=SELECT_COUNTRIES_LIST) hidden = BooleanField("Hidden") banned = BooleanField("Banned") submit = SubmitField("Submit") def TeamCreateForm(*args, **kwargs): class _TeamCreateForm(TeamBaseForm): pass @property def extra(self): return build_custom_team_fields(self, include_entries=False) attach_custom_team_fields(_TeamCreateForm) return _TeamCreateForm(*args, **kwargs)
null
158,393
from wtforms import BooleanField, PasswordField, SelectField, StringField from wtforms.fields.html5 import EmailField, URLField from wtforms.validators import InputRequired from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.models import TeamFieldEntries, TeamFields from CTFd.utils.countries import SELECT_COUNTRIES_LIST def build_custom_team_fields( form_cls, include_entries=False, fields_kwargs=None, field_entries_kwargs=None, blacklisted_items=("affiliation", "website"), ): if fields_kwargs is None: fields_kwargs = {} if field_entries_kwargs is None: field_entries_kwargs = {} fields = [] new_fields = TeamFields.query.filter_by(**fields_kwargs).all() user_fields = {} # Only include preexisting values if asked if include_entries is True: for f in TeamFieldEntries.query.filter_by(**field_entries_kwargs).all(): user_fields[f.field_id] = f.value for field in new_fields: if field.name.lower() in blacklisted_items: continue form_field = getattr(form_cls, f"fields[{field.id}]") # Add the field_type to the field so we know how to render it form_field.field_type = field.field_type # Only include preexisting values if asked if include_entries is True: initial = user_fields.get(field.id, "") form_field.data = initial if form_field.render_kw: form_field.render_kw["data-initial"] = initial else: form_field.render_kw = {"data-initial": initial} fields.append(form_field) return fields def attach_custom_team_fields(form_cls, **kwargs): new_fields = TeamFields.query.filter_by(**kwargs).all() for field in new_fields: validators = [] if field.required: validators.append(InputRequired()) if field.field_type == "text": input_field = StringField( field.name, description=field.description, validators=validators ) elif field.field_type == "boolean": input_field = BooleanField( field.name, description=field.description, validators=validators ) setattr(form_cls, f"fields[{field.id}]", input_field) class TeamBaseForm(BaseForm): name = StringField("Team Name", validators=[InputRequired()]) email = EmailField("Email") password = PasswordField("Password") website = URLField("Website") affiliation = StringField("Affiliation") country = SelectField("Country", choices=SELECT_COUNTRIES_LIST) hidden = BooleanField("Hidden") banned = BooleanField("Banned") submit = SubmitField("Submit") def TeamEditForm(*args, **kwargs): class _TeamEditForm(TeamBaseForm): pass @property def extra(self): return build_custom_team_fields( self, include_entries=True, fields_kwargs=None, field_entries_kwargs={"team_id": self.obj.id}, ) def __init__(self, *args, **kwargs): """ Custom init to persist the obj parameter to the rest of the form """ super().__init__(*args, **kwargs) obj = kwargs.get("obj") if obj: self.obj = obj attach_custom_team_fields(_TeamEditForm) return _TeamEditForm(*args, **kwargs)
null
158,394
from wtforms import BooleanField, PasswordField, SelectField, StringField from wtforms.fields.html5 import EmailField from wtforms.validators import InputRequired from CTFd.constants.config import Configs from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.models import UserFieldEntries, UserFields from CTFd.utils.countries import SELECT_COUNTRIES_LIST def build_custom_user_fields( form_cls, include_entries=False, fields_kwargs=None, field_entries_kwargs=None, blacklisted_items=("affiliation", "website"), ): """ Function used to reinject values back into forms for accessing by themes """ if fields_kwargs is None: fields_kwargs = {} if field_entries_kwargs is None: field_entries_kwargs = {} fields = [] new_fields = UserFields.query.filter_by(**fields_kwargs).all() user_fields = {} # Only include preexisting values if asked if include_entries is True: for f in UserFieldEntries.query.filter_by(**field_entries_kwargs).all(): user_fields[f.field_id] = f.value for field in new_fields: if field.name.lower() in blacklisted_items: continue form_field = getattr(form_cls, f"fields[{field.id}]") # Add the field_type to the field so we know how to render it form_field.field_type = field.field_type # Only include preexisting values if asked if include_entries is True: initial = user_fields.get(field.id, "") form_field.data = initial if form_field.render_kw: form_field.render_kw["data-initial"] = initial else: form_field.render_kw = {"data-initial": initial} fields.append(form_field) return fields def attach_custom_user_fields(form_cls, **kwargs): """ Function used to attach form fields to wtforms. Not really a great solution but is approved by wtforms. https://wtforms.readthedocs.io/en/2.3.x/specific_problems/#dynamic-form-composition """ new_fields = UserFields.query.filter_by(**kwargs).all() for field in new_fields: validators = [] if field.required: validators.append(InputRequired()) if field.field_type == "text": input_field = StringField( field.name, description=field.description, validators=validators ) elif field.field_type == "boolean": input_field = BooleanField( field.name, description=field.description, validators=validators ) setattr(form_cls, f"fields[{field.id}]", input_field) class UserBaseForm(BaseForm): name = StringField("User Name", validators=[InputRequired()]) email = EmailField("Email", validators=[InputRequired()]) password = PasswordField("Password") website = StringField("Website") affiliation = StringField("Affiliation") country = SelectField("Country", choices=SELECT_COUNTRIES_LIST) type = SelectField("Type", choices=[("user", "User"), ("admin", "Admin")]) verified = BooleanField("Verified") hidden = BooleanField("Hidden") banned = BooleanField("Banned") submit = SubmitField("Submit") def UserEditForm(*args, **kwargs): class _UserEditForm(UserBaseForm): pass @property def extra(self): return build_custom_user_fields( self, include_entries=True, fields_kwargs=None, field_entries_kwargs={"user_id": self.obj.id}, ) def __init__(self, *args, **kwargs): """ Custom init to persist the obj parameter to the rest of the form """ super().__init__(*args, **kwargs) obj = kwargs.get("obj") if obj: self.obj = obj attach_custom_user_fields(_UserEditForm) return _UserEditForm(*args, **kwargs)
null
158,395
from wtforms import BooleanField, PasswordField, SelectField, StringField from wtforms.fields.html5 import EmailField from wtforms.validators import InputRequired from CTFd.constants.config import Configs from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.models import UserFieldEntries, UserFields from CTFd.utils.countries import SELECT_COUNTRIES_LIST def build_custom_user_fields( form_cls, include_entries=False, fields_kwargs=None, field_entries_kwargs=None, blacklisted_items=("affiliation", "website"), ): def attach_custom_user_fields(form_cls, **kwargs): class UserBaseForm(BaseForm): def UserCreateForm(*args, **kwargs): class _UserCreateForm(UserBaseForm): notify = BooleanField("Email account credentials to user", default=True) @property def extra(self): return build_custom_user_fields(self, include_entries=False) attach_custom_user_fields(_UserCreateForm) return _UserCreateForm(*args, **kwargs)
null
158,396
from flask import session from wtforms import PasswordField, SelectField, StringField from wtforms.fields.html5 import DateField, URLField from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.forms.users import attach_custom_user_fields, build_custom_user_fields from CTFd.utils.countries import SELECT_COUNTRIES_LIST class BaseForm(Form): class Meta: csrf = True csrf_class = CTFdCSRF csrf_field_name = "nonce" class SubmitField(_SubmitField): """ This custom SubmitField exists because wtforms is dumb. See https://github.com/wtforms/wtforms/issues/205, https://github.com/wtforms/wtforms/issues/36 The .submit() handler in JS will break if the form has an input with the name or id of "submit" so submit fields need to be changed. """ def __init__(self, *args, **kwargs): name = kwargs.pop("name", "_submit") super().__init__(*args, **kwargs) if self.name == "submit" or name: self.id = name self.name = name def build_custom_user_fields( form_cls, include_entries=False, fields_kwargs=None, field_entries_kwargs=None, blacklisted_items=("affiliation", "website"), ): """ Function used to reinject values back into forms for accessing by themes """ if fields_kwargs is None: fields_kwargs = {} if field_entries_kwargs is None: field_entries_kwargs = {} fields = [] new_fields = UserFields.query.filter_by(**fields_kwargs).all() user_fields = {} # Only include preexisting values if asked if include_entries is True: for f in UserFieldEntries.query.filter_by(**field_entries_kwargs).all(): user_fields[f.field_id] = f.value for field in new_fields: if field.name.lower() in blacklisted_items: continue form_field = getattr(form_cls, f"fields[{field.id}]") # Add the field_type to the field so we know how to render it form_field.field_type = field.field_type # Only include preexisting values if asked if include_entries is True: initial = user_fields.get(field.id, "") form_field.data = initial if form_field.render_kw: form_field.render_kw["data-initial"] = initial else: form_field.render_kw = {"data-initial": initial} fields.append(form_field) return fields def attach_custom_user_fields(form_cls, **kwargs): """ Function used to attach form fields to wtforms. Not really a great solution but is approved by wtforms. https://wtforms.readthedocs.io/en/2.3.x/specific_problems/#dynamic-form-composition """ new_fields = UserFields.query.filter_by(**kwargs).all() for field in new_fields: validators = [] if field.required: validators.append(InputRequired()) if field.field_type == "text": input_field = StringField( field.name, description=field.description, validators=validators ) elif field.field_type == "boolean": input_field = BooleanField( field.name, description=field.description, validators=validators ) setattr(form_cls, f"fields[{field.id}]", input_field) SELECT_COUNTRIES_LIST = [("", "")] + COUNTRIES_LIST def SettingsForm(*args, **kwargs): class _SettingsForm(BaseForm): name = StringField("User Name") email = StringField("Email") password = PasswordField("Password") confirm = PasswordField("Current Password") affiliation = StringField("Affiliation") website = URLField("Website") country = SelectField("Country", choices=SELECT_COUNTRIES_LIST) submit = SubmitField("Submit") @property def extra(self): return build_custom_user_fields( self, include_entries=True, fields_kwargs={"editable": True}, field_entries_kwargs={"user_id": session["id"]}, ) attach_custom_user_fields(_SettingsForm, editable=True) return _SettingsForm(*args, **kwargs)
null
158,397
from wtforms import PasswordField, StringField from wtforms.fields.html5 import EmailField from wtforms.validators import InputRequired from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.forms.users import ( attach_custom_user_fields, attach_registration_code_field, build_custom_user_fields, build_registration_code_field, ) class BaseForm(Form): class SubmitField(_SubmitField): def __init__(self, *args, **kwargs): def build_custom_user_fields( form_cls, include_entries=False, fields_kwargs=None, field_entries_kwargs=None, blacklisted_items=("affiliation", "website"), ): def attach_custom_user_fields(form_cls, **kwargs): def build_registration_code_field(form_cls): def attach_registration_code_field(form_cls): def RegistrationForm(*args, **kwargs): class _RegistrationForm(BaseForm): name = StringField("User Name", validators=[InputRequired()]) email = EmailField("Email", validators=[InputRequired()]) password = PasswordField("Password", validators=[InputRequired()]) submit = SubmitField("Submit") @property def extra(self): return build_custom_user_fields( self, include_entries=False, blacklisted_items=() ) + build_registration_code_field(self) attach_custom_user_fields(_RegistrationForm) attach_registration_code_field(_RegistrationForm) return _RegistrationForm(*args, **kwargs)
null
158,398
from flask import Blueprint, redirect, render_template, request, url_for from CTFd.constants.config import ChallengeVisibilityTypes, Configs from CTFd.utils.config import is_teams_mode from CTFd.utils.dates import ctf_ended, ctf_paused, ctf_started from CTFd.utils.decorators import during_ctf_time_only, require_verified_emails from CTFd.utils.decorators.visibility import check_challenge_visibility from CTFd.utils.helpers import get_errors, get_infos from CTFd.utils.user import authed, get_current_team class ChallengeVisibilityTypes(str, RawEnum): PUBLIC = "public" PRIVATE = "private" ADMINS = "admins" Configs = _ConfigsWrapper() def is_teams_mode(): return user_mode() == TEAMS_MODE def ctf_paused(): return bool(get_config("paused")) def ctf_started(): return time.time() > int(get_config("start") or 0) def ctf_ended(): if int(get_config("end") or 0): return time.time() > int(get_config("end") or 0) return False def get_infos(): return get_flashed_messages(category_filter=request.endpoint + ".infos") def get_errors(): return get_flashed_messages(category_filter=request.endpoint + ".errors") def get_current_team(): if authed(): user = get_current_user() return user.team else: return None def authed(): return bool(session.get("id", False)) def listing(): if ( Configs.challenge_visibility == ChallengeVisibilityTypes.PUBLIC and authed() is False ): pass else: if is_teams_mode() and get_current_team() is None: return redirect(url_for("teams.private", next=request.full_path)) infos = get_infos() errors = get_errors() if ctf_started() is False: errors.append(f"{Configs.ctf_name} has not started yet") if ctf_paused() is True: infos.append(f"{Configs.ctf_name} is paused") if ctf_ended() is True: infos.append(f"{Configs.ctf_name} has ended") return render_template("challenges.html", infos=infos, errors=errors)
null
158,403
from typing import List from flask import request, session from flask_restx import Namespace, Resource from CTFd.api.v1.helpers.request import validate_args from CTFd.api.v1.helpers.schemas import sqlalchemy_to_pydantic from CTFd.api.v1.schemas import APIDetailedSuccessResponse, APIListSuccessResponse from CTFd.constants import RawEnum from CTFd.models import ( ChallengeComments, Comments, PageComments, TeamComments, UserComments, db, ) from CTFd.schemas.comments import CommentSchema from CTFd.utils.decorators import admins_only from CTFd.utils.helpers.models import build_model_filters class Comments(db.Model): __tablename__ = "comments" id = db.Column(db.Integer, primary_key=True) type = db.Column(db.String(80), default="standard") content = db.Column(db.Text) date = db.Column(db.DateTime, default=datetime.datetime.utcnow) author_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE")) author = db.relationship("Users", foreign_keys="Comments.author_id", lazy="select") def html(self): from CTFd.utils.config.pages import build_markdown from CTFd.utils.helpers import markup return markup(build_markdown(self.content, sanitize=True)) __mapper_args__ = {"polymorphic_identity": "standard", "polymorphic_on": type} class ChallengeComments(Comments): __mapper_args__ = {"polymorphic_identity": "challenge"} challenge_id = db.Column( db.Integer, db.ForeignKey("challenges.id", ondelete="CASCADE") ) class UserComments(Comments): __mapper_args__ = {"polymorphic_identity": "user"} user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE")) class TeamComments(Comments): __mapper_args__ = {"polymorphic_identity": "team"} team_id = db.Column(db.Integer, db.ForeignKey("teams.id", ondelete="CASCADE")) class PageComments(Comments): __mapper_args__ = {"polymorphic_identity": "page"} page_id = db.Column(db.Integer, db.ForeignKey("pages.id", ondelete="CASCADE")) def get_comment_model(data): model = Comments if "challenge_id" in data: model = ChallengeComments elif "user_id" in data: model = UserComments elif "team_id" in data: model = TeamComments elif "page_id" in data: model = PageComments else: model = Comments return model
null
158,407
from flask import Blueprint, abort, redirect, render_template, request, url_for from CTFd.cache import clear_team_session, clear_user_session from CTFd.exceptions import TeamTokenExpiredException, TeamTokenInvalidException from CTFd.models import TeamFieldEntries, TeamFields, Teams, db from CTFd.utils import config, get_config, validators from CTFd.utils.crypto import verify_password from CTFd.utils.decorators import authed_only, ratelimit, registered_only from CTFd.utils.decorators.modes import require_team_mode from CTFd.utils.decorators.visibility import ( check_account_visibility, check_score_visibility, ) from CTFd.utils.helpers import get_errors, get_infos from CTFd.utils.humanize.words import pluralize from CTFd.utils.user import get_current_user, get_current_user_attrs def clear_user_session(user_id): def clear_team_session(team_id): db = SQLAlchemy() class Teams(db.Model): def __init__(self, **kwargs): def validate_password(self, key, plaintext): def fields(self): def solves(self): def fails(self): def awards(self): def score(self): def place(self): def get_fields(self, admin=False): def get_invite_code(self): def load_invite_code(cls, code): def get_solves(self, admin=False): def get_fails(self, admin=False): def get_awards(self, admin=False): def get_score(self, admin=False): def get_place(self, admin=False, numeric=False): def get_config(key, default=None): def verify_password(plaintext, ciphertext): def get_infos(): def get_errors(): def get_current_user(): def get_current_user_attrs(): def join(): infos = get_infos() errors = get_errors() user = get_current_user_attrs() if user.team_id: errors.append("You are already in a team. You cannot join another.") if request.method == "GET": team_size_limit = get_config("team_size", default=0) if team_size_limit: plural = "" if team_size_limit == 1 else "s" infos.append( "Teams are limited to {limit} member{plural}".format( limit=team_size_limit, plural=plural ) ) return render_template("teams/join_team.html", infos=infos, errors=errors) if request.method == "POST": teamname = request.form.get("name") passphrase = request.form.get("password", "").strip() team = Teams.query.filter_by(name=teamname).first() if errors: return ( render_template("teams/join_team.html", infos=infos, errors=errors), 403, ) if team and verify_password(passphrase, team.password): team_size_limit = get_config("team_size", default=0) if team_size_limit and len(team.members) >= team_size_limit: errors.append( "{name} has already reached the team size limit of {limit}".format( name=team.name, limit=team_size_limit ) ) return render_template( "teams/join_team.html", infos=infos, errors=errors ) user = get_current_user() user.team_id = team.id db.session.commit() if len(team.members) == 1: team.captain_id = user.id db.session.commit() clear_user_session(user_id=user.id) clear_team_session(team_id=team.id) return redirect(url_for("challenges.listing")) else: errors.append("That information is incorrect") return render_template("teams/join_team.html", infos=infos, errors=errors)
null
158,416
from flask import render_template, request, url_for from sqlalchemy.sql import not_ from CTFd.admin import admin from CTFd.models import Challenges, Tracking, Users from CTFd.utils import get_config from CTFd.utils.decorators import admins_only from CTFd.utils.modes import TEAMS_MODE class Users(db.Model): def __init__(self, **kwargs): def validate_password(self, key, plaintext): def account_id(self): def account(self): def fields(self): def solves(self): def fails(self): def awards(self): def score(self): def place(self): def get_fields(self, admin=False): def get_solves(self, admin=False): def get_fails(self, admin=False): def get_awards(self, admin=False): def get_score(self, admin=False): def get_place(self, admin=False, numeric=False): class Tracking(db.Model): def __init__(self, *args, **kwargs): def __repr__(self): def users_listing(): q = request.args.get("q") field = request.args.get("field") page = abs(request.args.get("page", 1, type=int)) filters = [] users = [] if q: # The field exists as an exposed column if Users.__mapper__.has_property(field): filters.append(getattr(Users, field).like("%{}%".format(q))) if q and field == "ip": users = ( Users.query.join(Tracking, Users.id == Tracking.user_id) .filter(Tracking.ip.like("%{}%".format(q))) .order_by(Users.id.asc()) .paginate(page=page, per_page=50) ) else: users = ( Users.query.filter(*filters) .order_by(Users.id.asc()) .paginate(page=page, per_page=50) ) args = dict(request.args) args.pop("page", 1) return render_template( "admin/users/users.html", users=users, prev_page=url_for(request.endpoint, page=users.prev_num, **args), next_page=url_for(request.endpoint, page=users.next_num, **args), q=q, field=field, )
null
158,424
from flask import abort, render_template, request, url_for from CTFd.admin import admin from CTFd.models import Challenges, Flags, Solves from CTFd.plugins.challenges import CHALLENGE_CLASSES, get_chal_class from CTFd.utils.decorators import admins_only class Challenges(db.Model): def __missing__(self, key): def html(self): def plugin_class(self): def __init__(self, *args, **kwargs): def __repr__(self): def challenges_listing(): q = request.args.get("q") field = request.args.get("field") filters = [] if q: # The field exists as an exposed column if Challenges.__mapper__.has_property(field): filters.append(getattr(Challenges, field).like("%{}%".format(q))) query = Challenges.query.filter(*filters).order_by(Challenges.id.asc()) challenges = query.all() total = query.count() return render_template( "admin/challenges/challenges.html", challenges=challenges, total=total, q=q, field=field, )
null
158,429
from flask import Blueprint, render_template, request, url_for from CTFd.models import Users from CTFd.utils import config from CTFd.utils.decorators import authed_only from CTFd.utils.decorators.visibility import ( check_account_visibility, check_score_visibility, ) from CTFd.utils.helpers import get_errors, get_infos from CTFd.utils.user import get_current_user def get_infos(): def get_errors(): def get_current_user(): def private(): infos = get_infos() errors = get_errors() user = get_current_user() if config.is_scoreboard_frozen(): infos.append("Scoreboard has been frozen") return render_template( "users/private.html", user=user, account=user.account, infos=infos, errors=errors, )
null
158,440
from wtforms import BooleanField, PasswordField, SelectField, StringField from wtforms.fields.html5 import EmailField from wtforms.validators import InputRequired from CTFd.constants.config import Configs from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.models import UserFieldEntries, UserFields from CTFd.utils.countries import SELECT_COUNTRIES_LIST Configs = _ConfigsWrapper() The provided code snippet includes necessary dependencies for implementing the `build_registration_code_field` function. Write a Python function `def build_registration_code_field(form_cls)` to solve the following problem: Build the appropriate field so we can render it via the extra property. Add field_type so Jinja knows how to render it. Here is the function: def build_registration_code_field(form_cls): """ Build the appropriate field so we can render it via the extra property. Add field_type so Jinja knows how to render it. """ if Configs.registration_code: field = getattr(form_cls, "registration_code") # noqa B009 field.field_type = "text" return [field] else: return []
Build the appropriate field so we can render it via the extra property. Add field_type so Jinja knows how to render it.
158,441
from wtforms import BooleanField, PasswordField, SelectField, StringField from wtforms.fields.html5 import EmailField from wtforms.validators import InputRequired from CTFd.constants.config import Configs from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.models import UserFieldEntries, UserFields from CTFd.utils.countries import SELECT_COUNTRIES_LIST Configs = _ConfigsWrapper() The provided code snippet includes necessary dependencies for implementing the `attach_registration_code_field` function. Write a Python function `def attach_registration_code_field(form_cls)` to solve the following problem: If we have a registration code required, we attach it to the form similar to attach_custom_user_fields Here is the function: def attach_registration_code_field(form_cls): """ If we have a registration code required, we attach it to the form similar to attach_custom_user_fields """ if Configs.registration_code: setattr( # noqa B010 form_cls, "registration_code", StringField( "Registration Code", description="Registration code required to create account", validators=[InputRequired()], ), )
If we have a registration code required, we attach it to the form similar to attach_custom_user_fields
158,443
from wtforms import BooleanField, PasswordField, SelectField, StringField from wtforms.fields.html5 import EmailField from wtforms.validators import InputRequired from CTFd.constants.config import Configs from CTFd.forms import BaseForm from CTFd.forms.fields import SubmitField from CTFd.models import UserFieldEntries, UserFields from CTFd.utils.countries import SELECT_COUNTRIES_LIST def build_custom_user_fields( form_cls, include_entries=False, fields_kwargs=None, field_entries_kwargs=None, blacklisted_items=("affiliation", "website"), ): """ Function used to reinject values back into forms for accessing by themes """ if fields_kwargs is None: fields_kwargs = {} if field_entries_kwargs is None: field_entries_kwargs = {} fields = [] new_fields = UserFields.query.filter_by(**fields_kwargs).all() user_fields = {} # Only include preexisting values if asked if include_entries is True: for f in UserFieldEntries.query.filter_by(**field_entries_kwargs).all(): user_fields[f.field_id] = f.value for field in new_fields: if field.name.lower() in blacklisted_items: continue form_field = getattr(form_cls, f"fields[{field.id}]") # Add the field_type to the field so we know how to render it form_field.field_type = field.field_type # Only include preexisting values if asked if include_entries is True: initial = user_fields.get(field.id, "") form_field.data = initial if form_field.render_kw: form_field.render_kw["data-initial"] = initial else: form_field.render_kw = {"data-initial": initial} fields.append(form_field) return fields def attach_custom_user_fields(form_cls, **kwargs): """ Function used to attach form fields to wtforms. Not really a great solution but is approved by wtforms. https://wtforms.readthedocs.io/en/2.3.x/specific_problems/#dynamic-form-composition """ new_fields = UserFields.query.filter_by(**kwargs).all() for field in new_fields: validators = [] if field.required: validators.append(InputRequired()) if field.field_type == "text": input_field = StringField( field.name, description=field.description, validators=validators ) elif field.field_type == "boolean": input_field = BooleanField( field.name, description=field.description, validators=validators ) setattr(form_cls, f"fields[{field.id}]", input_field) class UserBaseForm(BaseForm): name = StringField("User Name", validators=[InputRequired()]) email = EmailField("Email", validators=[InputRequired()]) password = PasswordField("Password") website = StringField("Website") affiliation = StringField("Affiliation") country = SelectField("Country", choices=SELECT_COUNTRIES_LIST) type = SelectField("Type", choices=[("user", "User"), ("admin", "Admin")]) verified = BooleanField("Verified") hidden = BooleanField("Hidden") banned = BooleanField("Banned") submit = SubmitField("Submit") def UserCreateForm(*args, **kwargs): class _UserCreateForm(UserBaseForm): notify = BooleanField("Email account credentials to user", default=True) @property def extra(self): return build_custom_user_fields(self, include_entries=False) attach_custom_user_fields(_UserCreateForm) return _UserCreateForm(*args, **kwargs)
null
158,447
import base64 import requests from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, session, url_for from itsdangerous.exc import BadSignature, BadTimeSignature, SignatureExpired from CTFd.cache import clear_team_session, clear_user_session from CTFd.models import Teams, UserFieldEntries, UserFields, Users, db from CTFd.utils import config, email, get_app_config, get_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_teams_mode from CTFd.utils.config.integrations import mlc_registration from CTFd.utils.config.visibility import registration_visible from CTFd.utils.crypto import verify_password from CTFd.utils.decorators import ratelimit from CTFd.utils.decorators.visibility import check_registration_visibility from CTFd.utils.helpers import error_for, get_errors, markup from CTFd.utils.logging import log from CTFd.utils.modes import TEAMS_MODE from CTFd.utils.security.auth import login_user, logout_user from CTFd.utils.security.signing import unserialize from CTFd.utils.validators import ValidationError def clear_user_session(user_id): from CTFd.utils.user import get_user_attrs cache.delete_memoized(get_user_attrs, user_id=user_id) db = SQLAlchemy() class Users(db.Model): __tablename__ = "users" __table_args__ = (db.UniqueConstraint("id", "oauth_id"), {}) # Core attributes id = db.Column(db.Integer, primary_key=True) oauth_id = db.Column(db.Integer, unique=True) # User names are not constrained to be unique to allow for official/unofficial teams. name = db.Column(db.String(128)) password = db.Column(db.String(128)) email = db.Column(db.String(128), unique=True) type = db.Column(db.String(80)) secret = db.Column(db.String(128)) # Supplementary attributes website = db.Column(db.String(128)) affiliation = db.Column(db.String(128)) country = db.Column(db.String(32)) bracket = db.Column(db.String(32)) hidden = db.Column(db.Boolean, default=False) banned = db.Column(db.Boolean, default=False) verified = db.Column(db.Boolean, default=False) # Relationship for Teams team_id = db.Column(db.Integer, db.ForeignKey("teams.id")) field_entries = db.relationship( "UserFieldEntries", foreign_keys="UserFieldEntries.user_id", lazy="joined" ) created = db.Column(db.DateTime, default=datetime.datetime.utcnow) __mapper_args__ = {"polymorphic_identity": "user", "polymorphic_on": type} def __init__(self, **kwargs): super(Users, self).__init__(**kwargs) def validate_password(self, key, plaintext): from CTFd.utils.crypto import hash_password return hash_password(str(plaintext)) def account_id(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team_id elif user_mode == "users": return self.id def account(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team elif user_mode == "users": return self def fields(self): return self.get_fields(admin=False) def solves(self): return self.get_solves(admin=False) def fails(self): return self.get_fails(admin=False) def awards(self): return self.get_awards(admin=False) def score(self): return self.get_score(admin=False) def place(self): from CTFd.utils.config.visibility import scores_visible if scores_visible(): return self.get_place(admin=False) else: return None def get_fields(self, admin=False): if admin: return self.field_entries return [ entry for entry in self.field_entries if entry.field.public and entry.value ] def get_solves(self, admin=False): from CTFd.utils import get_config solves = Solves.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) solves = solves.filter(Solves.date < dt) return solves.all() def get_fails(self, admin=False): from CTFd.utils import get_config fails = Fails.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) fails = fails.filter(Fails.date < dt) return fails.all() def get_awards(self, admin=False): from CTFd.utils import get_config awards = Awards.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) awards = awards.filter(Awards.date < dt) return awards.all() def get_score(self, admin=False): score = db.func.sum(Challenges.value).label("score") user = ( db.session.query(Solves.user_id, score) .join(Users, Solves.user_id == Users.id) .join(Challenges, Solves.challenge_id == Challenges.id) .filter(Users.id == self.id) ) award_score = db.func.sum(Awards.value).label("award_score") award = db.session.query(award_score).filter_by(user_id=self.id) if not admin: freeze = Configs.query.filter_by(key="freeze").first() if freeze and freeze.value: freeze = int(freeze.value) freeze = datetime.datetime.utcfromtimestamp(freeze) user = user.filter(Solves.date < freeze) award = award.filter(Awards.date < freeze) user = user.group_by(Solves.user_id).first() award = award.first() if user and award: return int(user.score or 0) + int(award.award_score or 0) elif user: return int(user.score or 0) elif award: return int(award.award_score or 0) else: return 0 def get_place(self, admin=False, numeric=False): """ This method is generally a clone of CTFd.scoreboard.get_standings. The point being that models.py must be self-reliant and have little to no imports within the CTFd application as importing from the application itself will result in a circular import. """ from CTFd.utils.scores import get_user_standings from CTFd.utils.humanize.numbers import ordinalize standings = get_user_standings(admin=admin) for i, user in enumerate(standings): if user.user_id == self.id: n = i + 1 if numeric: return n return ordinalize(n) else: return None def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def log(logger, format, **kwargs): logger = logging.getLogger(logger) props = { "id": session.get("id"), "date": time.strftime("%m/%d/%Y %X"), "ip": get_ip(), } props.update(kwargs) msg = format.format(**props) print(msg) logger.info(msg) def unserialize(data, secret=None, max_age=432000): if secret is None: secret = current_app.config["SECRET_KEY"] s = URLSafeTimedSerializer(secret) return s.loads(data, max_age=max_age) def confirm(data=None): if not get_config("verify_emails"): # If the CTF doesn't care about confirming email addresses then redierct to challenges return redirect(url_for("challenges.listing")) # User is confirming email account if data and request.method == "GET": try: user_email = unserialize(data, max_age=1800) except (BadTimeSignature, SignatureExpired): return render_template( "confirm.html", errors=["Your confirmation link has expired"] ) except (BadSignature, TypeError, base64.binascii.Error): return render_template( "confirm.html", errors=["Your confirmation token is invalid"] ) user = Users.query.filter_by(email=user_email).first_or_404() if user.verified: return redirect(url_for("views.settings")) user.verified = True log( "registrations", format="[{date}] {ip} - successful confirmation for {name}", name=user.name, ) db.session.commit() clear_user_session(user_id=user.id) email.successful_registration_notification(user.email) db.session.close() if current_user.authed(): return redirect(url_for("challenges.listing")) return redirect(url_for("auth.login")) # User is trying to start or restart the confirmation flow if current_user.authed() is False: return redirect(url_for("auth.login")) user = Users.query.filter_by(id=session["id"]).first_or_404() if user.verified: return redirect(url_for("views.settings")) if data is None: if request.method == "POST": # User wants to resend their confirmation email email.verify_email_address(user.email) log( "registrations", format="[{date}] {ip} - {name} initiated a confirmation email resend", name=user.name, ) return render_template( "confirm.html", infos=[f"Confirmation email sent to {user.email}!"] ) elif request.method == "GET": # User has been directed to the confirm page return render_template("confirm.html")
null
158,448
import base64 import requests from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, session, url_for from itsdangerous.exc import BadSignature, BadTimeSignature, SignatureExpired from CTFd.cache import clear_team_session, clear_user_session from CTFd.models import Teams, UserFieldEntries, UserFields, Users, db from CTFd.utils import config, email, get_app_config, get_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_teams_mode from CTFd.utils.config.integrations import mlc_registration from CTFd.utils.config.visibility import registration_visible from CTFd.utils.crypto import verify_password from CTFd.utils.decorators import ratelimit from CTFd.utils.decorators.visibility import check_registration_visibility from CTFd.utils.helpers import error_for, get_errors, markup from CTFd.utils.logging import log from CTFd.utils.modes import TEAMS_MODE from CTFd.utils.security.auth import login_user, logout_user from CTFd.utils.security.signing import unserialize from CTFd.utils.validators import ValidationError def clear_user_session(user_id): from CTFd.utils.user import get_user_attrs cache.delete_memoized(get_user_attrs, user_id=user_id) db = SQLAlchemy() class Users(db.Model): __tablename__ = "users" __table_args__ = (db.UniqueConstraint("id", "oauth_id"), {}) # Core attributes id = db.Column(db.Integer, primary_key=True) oauth_id = db.Column(db.Integer, unique=True) # User names are not constrained to be unique to allow for official/unofficial teams. name = db.Column(db.String(128)) password = db.Column(db.String(128)) email = db.Column(db.String(128), unique=True) type = db.Column(db.String(80)) secret = db.Column(db.String(128)) # Supplementary attributes website = db.Column(db.String(128)) affiliation = db.Column(db.String(128)) country = db.Column(db.String(32)) bracket = db.Column(db.String(32)) hidden = db.Column(db.Boolean, default=False) banned = db.Column(db.Boolean, default=False) verified = db.Column(db.Boolean, default=False) # Relationship for Teams team_id = db.Column(db.Integer, db.ForeignKey("teams.id")) field_entries = db.relationship( "UserFieldEntries", foreign_keys="UserFieldEntries.user_id", lazy="joined" ) created = db.Column(db.DateTime, default=datetime.datetime.utcnow) __mapper_args__ = {"polymorphic_identity": "user", "polymorphic_on": type} def __init__(self, **kwargs): super(Users, self).__init__(**kwargs) def validate_password(self, key, plaintext): from CTFd.utils.crypto import hash_password return hash_password(str(plaintext)) def account_id(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team_id elif user_mode == "users": return self.id def account(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team elif user_mode == "users": return self def fields(self): return self.get_fields(admin=False) def solves(self): return self.get_solves(admin=False) def fails(self): return self.get_fails(admin=False) def awards(self): return self.get_awards(admin=False) def score(self): return self.get_score(admin=False) def place(self): from CTFd.utils.config.visibility import scores_visible if scores_visible(): return self.get_place(admin=False) else: return None def get_fields(self, admin=False): if admin: return self.field_entries return [ entry for entry in self.field_entries if entry.field.public and entry.value ] def get_solves(self, admin=False): from CTFd.utils import get_config solves = Solves.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) solves = solves.filter(Solves.date < dt) return solves.all() def get_fails(self, admin=False): from CTFd.utils import get_config fails = Fails.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) fails = fails.filter(Fails.date < dt) return fails.all() def get_awards(self, admin=False): from CTFd.utils import get_config awards = Awards.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) awards = awards.filter(Awards.date < dt) return awards.all() def get_score(self, admin=False): score = db.func.sum(Challenges.value).label("score") user = ( db.session.query(Solves.user_id, score) .join(Users, Solves.user_id == Users.id) .join(Challenges, Solves.challenge_id == Challenges.id) .filter(Users.id == self.id) ) award_score = db.func.sum(Awards.value).label("award_score") award = db.session.query(award_score).filter_by(user_id=self.id) if not admin: freeze = Configs.query.filter_by(key="freeze").first() if freeze and freeze.value: freeze = int(freeze.value) freeze = datetime.datetime.utcfromtimestamp(freeze) user = user.filter(Solves.date < freeze) award = award.filter(Awards.date < freeze) user = user.group_by(Solves.user_id).first() award = award.first() if user and award: return int(user.score or 0) + int(award.award_score or 0) elif user: return int(user.score or 0) elif award: return int(award.award_score or 0) else: return 0 def get_place(self, admin=False, numeric=False): """ This method is generally a clone of CTFd.scoreboard.get_standings. The point being that models.py must be self-reliant and have little to no imports within the CTFd application as importing from the application itself will result in a circular import. """ from CTFd.utils.scores import get_user_standings from CTFd.utils.humanize.numbers import ordinalize standings = get_user_standings(admin=admin) for i, user in enumerate(standings): if user.user_id == self.id: n = i + 1 if numeric: return n return ordinalize(n) else: return None def markup(text): """ Mark text as safe to inject as HTML into templates """ return Markup(text) def get_errors(): return get_flashed_messages(category_filter=request.endpoint + ".errors") def log(logger, format, **kwargs): logger = logging.getLogger(logger) props = { "id": session.get("id"), "date": time.strftime("%m/%d/%Y %X"), "ip": get_ip(), } props.update(kwargs) msg = format.format(**props) print(msg) logger.info(msg) def unserialize(data, secret=None, max_age=432000): if secret is None: secret = current_app.config["SECRET_KEY"] s = URLSafeTimedSerializer(secret) return s.loads(data, max_age=max_age) def reset_password(data=None): if config.can_send_mail() is False: return render_template( "reset_password.html", errors=[ markup( "This CTF is not configured to send email.<br> Please contact an organizer to have your password reset." ) ], ) 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", infos=[ "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 not user: return render_template( "reset_password.html", infos=[ "If that account exists you will receive an email, please check your inbox" ], ) if user.oauth_id: return render_template( "reset_password.html", infos=[ "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", infos=[ "If that account exists you will receive an email, please check your inbox" ], ) return render_template("reset_password.html")
null
158,449
import base64 import requests from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, session, url_for from itsdangerous.exc import BadSignature, BadTimeSignature, SignatureExpired from CTFd.cache import clear_team_session, clear_user_session from CTFd.models import Teams, UserFieldEntries, UserFields, Users, db from CTFd.utils import config, email, get_app_config, get_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_teams_mode from CTFd.utils.config.integrations import mlc_registration from CTFd.utils.config.visibility import registration_visible from CTFd.utils.crypto import verify_password from CTFd.utils.decorators import ratelimit from CTFd.utils.decorators.visibility import check_registration_visibility from CTFd.utils.helpers import error_for, get_errors, markup from CTFd.utils.logging import log from CTFd.utils.modes import TEAMS_MODE from CTFd.utils.security.auth import login_user, logout_user from CTFd.utils.security.signing import unserialize from CTFd.utils.validators import ValidationError db = SQLAlchemy() class Users(db.Model): __tablename__ = "users" __table_args__ = (db.UniqueConstraint("id", "oauth_id"), {}) # Core attributes id = db.Column(db.Integer, primary_key=True) oauth_id = db.Column(db.Integer, unique=True) # User names are not constrained to be unique to allow for official/unofficial teams. name = db.Column(db.String(128)) password = db.Column(db.String(128)) email = db.Column(db.String(128), unique=True) type = db.Column(db.String(80)) secret = db.Column(db.String(128)) # Supplementary attributes website = db.Column(db.String(128)) affiliation = db.Column(db.String(128)) country = db.Column(db.String(32)) bracket = db.Column(db.String(32)) hidden = db.Column(db.Boolean, default=False) banned = db.Column(db.Boolean, default=False) verified = db.Column(db.Boolean, default=False) # Relationship for Teams team_id = db.Column(db.Integer, db.ForeignKey("teams.id")) field_entries = db.relationship( "UserFieldEntries", foreign_keys="UserFieldEntries.user_id", lazy="joined" ) created = db.Column(db.DateTime, default=datetime.datetime.utcnow) __mapper_args__ = {"polymorphic_identity": "user", "polymorphic_on": type} def __init__(self, **kwargs): super(Users, self).__init__(**kwargs) def validate_password(self, key, plaintext): from CTFd.utils.crypto import hash_password return hash_password(str(plaintext)) def account_id(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team_id elif user_mode == "users": return self.id def account(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team elif user_mode == "users": return self def fields(self): return self.get_fields(admin=False) def solves(self): return self.get_solves(admin=False) def fails(self): return self.get_fails(admin=False) def awards(self): return self.get_awards(admin=False) def score(self): return self.get_score(admin=False) def place(self): from CTFd.utils.config.visibility import scores_visible if scores_visible(): return self.get_place(admin=False) else: return None def get_fields(self, admin=False): if admin: return self.field_entries return [ entry for entry in self.field_entries if entry.field.public and entry.value ] def get_solves(self, admin=False): from CTFd.utils import get_config solves = Solves.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) solves = solves.filter(Solves.date < dt) return solves.all() def get_fails(self, admin=False): from CTFd.utils import get_config fails = Fails.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) fails = fails.filter(Fails.date < dt) return fails.all() def get_awards(self, admin=False): from CTFd.utils import get_config awards = Awards.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) awards = awards.filter(Awards.date < dt) return awards.all() def get_score(self, admin=False): score = db.func.sum(Challenges.value).label("score") user = ( db.session.query(Solves.user_id, score) .join(Users, Solves.user_id == Users.id) .join(Challenges, Solves.challenge_id == Challenges.id) .filter(Users.id == self.id) ) award_score = db.func.sum(Awards.value).label("award_score") award = db.session.query(award_score).filter_by(user_id=self.id) if not admin: freeze = Configs.query.filter_by(key="freeze").first() if freeze and freeze.value: freeze = int(freeze.value) freeze = datetime.datetime.utcfromtimestamp(freeze) user = user.filter(Solves.date < freeze) award = award.filter(Awards.date < freeze) user = user.group_by(Solves.user_id).first() award = award.first() if user and award: return int(user.score or 0) + int(award.award_score or 0) elif user: return int(user.score or 0) elif award: return int(award.award_score or 0) else: return 0 def get_place(self, admin=False, numeric=False): """ This method is generally a clone of CTFd.scoreboard.get_standings. The point being that models.py must be self-reliant and have little to no imports within the CTFd application as importing from the application itself will result in a circular import. """ from CTFd.utils.scores import get_user_standings from CTFd.utils.humanize.numbers import ordinalize standings = get_user_standings(admin=admin) for i, user in enumerate(standings): if user.user_id == self.id: n = i + 1 if numeric: return n return ordinalize(n) else: return None class UserFields(Fields): __mapper_args__ = {"polymorphic_identity": "user"} class UserFieldEntries(FieldEntries): __mapper_args__ = {"polymorphic_identity": "user"} user_id = db.Column(db.Integer, db.ForeignKey("users.id", ondelete="CASCADE")) user = db.relationship("Users", foreign_keys="UserFieldEntries.user_id") def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def is_teams_mode(): return user_mode() == TEAMS_MODE def get_errors(): return get_flashed_messages(category_filter=request.endpoint + ".errors") def log(logger, format, **kwargs): logger = logging.getLogger(logger) props = { "id": session.get("id"), "date": time.strftime("%m/%d/%Y %X"), "ip": get_ip(), } props.update(kwargs) msg = format.format(**props) print(msg) logger.info(msg) def login_user(user): session["id"] = user.id session["nonce"] = generate_nonce() session["hash"] = hmac(user.password) # Clear out any currently cached user attributes clear_user_session(user_id=user.id) 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("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() 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)
null
158,450
import base64 import requests from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, session, url_for from itsdangerous.exc import BadSignature, BadTimeSignature, SignatureExpired from CTFd.cache import clear_team_session, clear_user_session from CTFd.models import Teams, UserFieldEntries, UserFields, Users, db from CTFd.utils import config, email, get_app_config, get_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_teams_mode from CTFd.utils.config.integrations import mlc_registration from CTFd.utils.config.visibility import registration_visible from CTFd.utils.crypto import verify_password from CTFd.utils.decorators import ratelimit from CTFd.utils.decorators.visibility import check_registration_visibility from CTFd.utils.helpers import error_for, get_errors, markup from CTFd.utils.logging import log from CTFd.utils.modes import TEAMS_MODE from CTFd.utils.security.auth import login_user, logout_user from CTFd.utils.security.signing import unserialize from CTFd.utils.validators import ValidationError db = SQLAlchemy() class Users(db.Model): def __init__(self, **kwargs): def validate_password(self, key, plaintext): def account_id(self): def account(self): def fields(self): def solves(self): def fails(self): def awards(self): def score(self): def place(self): def get_fields(self, admin=False): def get_solves(self, admin=False): def get_fails(self, admin=False): def get_awards(self, admin=False): def get_score(self, admin=False): def get_place(self, admin=False, numeric=False): def verify_password(plaintext, ciphertext): def get_errors(): def log(logger, format, **kwargs): def login_user(user): def login(): errors = get_errors() if request.method == "POST": name = request.form["name"] # Check if the user submitted an email address or a team name if validators.validate_email(name) is True: user = Users.query.filter_by(email=name).first() else: user = Users.query.filter_by(name=name).first() if user: if user.password is None: errors.append( "Your account was registered with a 3rd party authentication provider. " "Please try logging in with a configured authentication provider." ) return render_template("login.html", errors=errors) if user and verify_password(request.form["password"], user.password): session.regenerate() login_user(user) log("logins", "[{date}] {ip} - {name} logged in", name=user.name) db.session.close() if request.args.get("next") and validators.is_safe_url( request.args.get("next") ): return redirect(request.args.get("next")) return redirect(url_for("challenges.listing")) else: # This user exists but the password is wrong log( "logins", "[{date}] {ip} - submitted invalid password for {name}", name=user.name, ) errors.append("Your username or password is incorrect") db.session.close() return render_template("login.html", errors=errors) else: # This user just doesn't exist log("logins", "[{date}] {ip} - submitted invalid account information") errors.append("Your username or password is incorrect") db.session.close() return render_template("login.html", errors=errors) else: db.session.close() return render_template("login.html", errors=errors)
null
158,451
import base64 import requests from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, session, url_for from itsdangerous.exc import BadSignature, BadTimeSignature, SignatureExpired from CTFd.cache import clear_team_session, clear_user_session from CTFd.models import Teams, UserFieldEntries, UserFields, Users, db from CTFd.utils import config, email, get_app_config, get_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_teams_mode from CTFd.utils.config.integrations import mlc_registration from CTFd.utils.config.visibility import registration_visible from CTFd.utils.crypto import verify_password from CTFd.utils.decorators import ratelimit from CTFd.utils.decorators.visibility import check_registration_visibility from CTFd.utils.helpers import error_for, get_errors, markup from CTFd.utils.logging import log from CTFd.utils.modes import TEAMS_MODE from CTFd.utils.security.auth import login_user, logout_user from CTFd.utils.security.signing import unserialize from CTFd.utils.validators import ValidationError def get_app_config(key, default=None): value = app.config.get(key, default) return value def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def error_for(endpoint, message): flash(message=message, category=endpoint + ".errors") def oauth_login(): endpoint = ( get_app_config("OAUTH_AUTHORIZATION_ENDPOINT") or get_config("oauth_authorization_endpoint") or "https://auth.majorleaguecyber.org/oauth/authorize" ) if get_config("user_mode") == "teams": scope = "profile team" else: scope = "profile" client_id = get_app_config("OAUTH_CLIENT_ID") or get_config("oauth_client_id") if client_id is None: error_for( endpoint="auth.login", message="OAuth Settings not configured. " "Ask your CTF administrator to configure MajorLeagueCyber integration.", ) return redirect(url_for("auth.login")) redirect_url = "{endpoint}?response_type=code&client_id={client_id}&scope={scope}&state={state}".format( endpoint=endpoint, client_id=client_id, scope=scope, state=session["nonce"] ) return redirect(redirect_url)
null
158,452
import base64 import requests from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, session, url_for from itsdangerous.exc import BadSignature, BadTimeSignature, SignatureExpired from CTFd.cache import clear_team_session, clear_user_session from CTFd.models import Teams, UserFieldEntries, UserFields, Users, db from CTFd.utils import config, email, get_app_config, get_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_teams_mode from CTFd.utils.config.integrations import mlc_registration from CTFd.utils.config.visibility import registration_visible from CTFd.utils.crypto import verify_password from CTFd.utils.decorators import ratelimit from CTFd.utils.decorators.visibility import check_registration_visibility from CTFd.utils.helpers import error_for, get_errors, markup from CTFd.utils.logging import log from CTFd.utils.modes import TEAMS_MODE from CTFd.utils.security.auth import login_user, logout_user from CTFd.utils.security.signing import unserialize from CTFd.utils.validators import ValidationError def clear_user_session(user_id): def clear_team_session(team_id): db = SQLAlchemy() class Users(db.Model): def __init__(self, **kwargs): def validate_password(self, key, plaintext): def account_id(self): def account(self): def fields(self): def solves(self): def fails(self): def awards(self): def score(self): def place(self): def get_fields(self, admin=False): def get_solves(self, admin=False): def get_fails(self, admin=False): def get_awards(self, admin=False): def get_score(self, admin=False): def get_place(self, admin=False, numeric=False): class Teams(db.Model): def __init__(self, **kwargs): def validate_password(self, key, plaintext): def fields(self): def solves(self): def fails(self): def awards(self): def score(self): def place(self): def get_fields(self, admin=False): def get_invite_code(self): def load_invite_code(cls, code): def get_solves(self, admin=False): def get_fails(self, admin=False): def get_awards(self, admin=False): def get_score(self, admin=False): def get_place(self, admin=False, numeric=False): def get_app_config(key, default=None): def get_config(key, default=None): def mlc_registration(): def registration_visible(): def error_for(endpoint, message): def log(logger, format, **kwargs): TEAMS_MODE = "teams" def login_user(user): def oauth_redirect(): oauth_code = request.args.get("code") state = request.args.get("state") if session["nonce"] != state: log("logins", "[{date}] {ip} - OAuth State validation mismatch") error_for(endpoint="auth.login", message="OAuth State validation mismatch.") return redirect(url_for("auth.login")) if oauth_code: url = ( get_app_config("OAUTH_TOKEN_ENDPOINT") or get_config("oauth_token_endpoint") or "https://auth.majorleaguecyber.org/oauth/token" ) client_id = get_app_config("OAUTH_CLIENT_ID") or get_config("oauth_client_id") client_secret = get_app_config("OAUTH_CLIENT_SECRET") or get_config( "oauth_client_secret" ) headers = {"content-type": "application/x-www-form-urlencoded"} data = { "code": oauth_code, "client_id": client_id, "client_secret": client_secret, "grant_type": "authorization_code", } token_request = requests.post(url, data=data, headers=headers) if token_request.status_code == requests.codes.ok: token = token_request.json()["access_token"] user_url = ( get_app_config("OAUTH_API_ENDPOINT") or get_config("oauth_api_endpoint") or "https://api.majorleaguecyber.org/user" ) headers = { "Authorization": "Bearer " + str(token), "Content-type": "application/json", } api_data = requests.get(url=user_url, headers=headers).json() user_id = api_data["id"] user_name = api_data["name"] user_email = api_data["email"] user = Users.query.filter_by(email=user_email).first() if user is None: # Check if we are allowing registration before creating users if registration_visible() or mlc_registration(): user = Users( name=user_name, email=user_email, oauth_id=user_id, verified=True, ) db.session.add(user) db.session.commit() else: log("logins", "[{date}] {ip} - Public registration via MLC blocked") error_for( endpoint="auth.login", message="Public registration is disabled. Please try again later.", ) return redirect(url_for("auth.login")) if get_config("user_mode") == TEAMS_MODE: team_id = api_data["team"]["id"] team_name = api_data["team"]["name"] team = Teams.query.filter_by(oauth_id=team_id).first() if team is None: num_teams_limit = int(get_config("num_teams", default=0)) num_teams = Teams.query.filter_by( banned=False, hidden=False ).count() if num_teams_limit and num_teams >= num_teams_limit: abort( 403, description=f"Reached the maximum number of teams ({num_teams_limit}). Please join an existing team.", ) team = Teams(name=team_name, oauth_id=team_id, captain_id=user.id) db.session.add(team) db.session.commit() clear_team_session(team_id=team.id) team_size_limit = get_config("team_size", default=0) if team_size_limit and len(team.members) >= team_size_limit: plural = "" if team_size_limit == 1 else "s" size_error = "Teams are limited to {limit} member{plural}.".format( limit=team_size_limit, plural=plural ) error_for(endpoint="auth.login", message=size_error) return redirect(url_for("auth.login")) team.members.append(user) db.session.commit() if user.oauth_id is None: user.oauth_id = user_id user.verified = True db.session.commit() clear_user_session(user_id=user.id) login_user(user) return redirect(url_for("challenges.listing")) else: log("logins", "[{date}] {ip} - OAuth token retrieval failure") error_for(endpoint="auth.login", message="OAuth token retrieval failure.") return redirect(url_for("auth.login")) else: log("logins", "[{date}] {ip} - Received redirect without OAuth code") error_for( endpoint="auth.login", message="Received redirect without OAuth code." ) return redirect(url_for("auth.login"))
null
158,453
import base64 import requests from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, session, url_for from itsdangerous.exc import BadSignature, BadTimeSignature, SignatureExpired from CTFd.cache import clear_team_session, clear_user_session from CTFd.models import Teams, UserFieldEntries, UserFields, Users, db from CTFd.utils import config, email, get_app_config, get_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_teams_mode from CTFd.utils.config.integrations import mlc_registration from CTFd.utils.config.visibility import registration_visible from CTFd.utils.crypto import verify_password from CTFd.utils.decorators import ratelimit from CTFd.utils.decorators.visibility import check_registration_visibility from CTFd.utils.helpers import error_for, get_errors, markup from CTFd.utils.logging import log from CTFd.utils.modes import TEAMS_MODE from CTFd.utils.security.auth import login_user, logout_user from CTFd.utils.security.signing import unserialize from CTFd.utils.validators import ValidationError def logout_user(): session.clear() def logout(): if current_user.authed(): logout_user() return redirect(url_for("views.static_html"))
null
158,454
import os from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, send_file, session, url_for from flask.helpers import safe_join from jinja2.exceptions import TemplateNotFound from sqlalchemy.exc import IntegrityError from CTFd.cache import cache from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.constants.themes import DEFAULT_THEME from CTFd.models import ( Admins, Files, Notifications, Pages, Teams, Users, UserTokens, db, ) from CTFd.utils import config, get_config, set_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_setup from CTFd.utils.config.pages import build_markdown, get_page from CTFd.utils.config.visibility import challenges_visible from CTFd.utils.dates import ctf_ended, ctftime, view_after_ctf from CTFd.utils.decorators import authed_only from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) from CTFd.utils.helpers import get_errors, get_infos, markup from CTFd.utils.modes import USERS_MODE from CTFd.utils.security.auth import login_user from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import ( BadSignature, BadTimeSignature, SignatureExpired, serialize, unserialize, ) from CTFd.utils.uploads import get_uploader, upload_file from CTFd.utils.user import authed, get_current_user, is_admin def files(path): """ Route in charge of dealing with making sure that CTF challenges are only accessible during the competition. :param path: :return: """ f = Files.query.filter_by(location=path).first_or_404() if f.type == "challenge": if challenges_visible(): if current_user.is_admin() is False: if not ctftime(): if ctf_ended() and view_after_ctf(): pass else: abort(403) else: if not ctftime(): abort(403) # Allow downloads if a valid token is provided token = request.args.get("token", "") try: data = unserialize(token, max_age=3600) user_id = data.get("user_id") team_id = data.get("team_id") file_id = data.get("file_id") user = Users.query.filter_by(id=user_id).first() team = Teams.query.filter_by(id=team_id).first() # Check user is admin if challenge_visibility is admins only if ( get_config(ConfigTypes.CHALLENGE_VISIBILITY) == "admins" and user.type != "admin" ): abort(403) # Check that the user exists and isn't banned if user: if user.banned: abort(403) else: abort(403) # Check that the team isn't banned if team: if team.banned: abort(403) else: pass # Check that the token properly refers to the file if file_id != f.id: abort(403) # The token isn't expired or broken except (BadTimeSignature, SignatureExpired, BadSignature): abort(403) uploader = get_uploader() try: return uploader.download(f.location) except IOError: abort(404) cache = Cache() class ConfigTypes(str, RawEnum): CHALLENGE_VISIBILITY = "challenge_visibility" SCORE_VISIBILITY = "score_visibility" ACCOUNT_VISIBILITY = "account_visibility" REGISTRATION_VISIBILITY = "registration_visibility" class ChallengeVisibilityTypes(str, RawEnum): PUBLIC = "public" PRIVATE = "private" ADMINS = "admins" class ScoreVisibilityTypes(str, RawEnum): PUBLIC = "public" PRIVATE = "private" HIDDEN = "hidden" ADMINS = "admins" class AccountVisibilityTypes(str, RawEnum): PUBLIC = "public" PRIVATE = "private" ADMINS = "admins" class RegistrationVisibilityTypes(str, RawEnum): PUBLIC = "public" PRIVATE = "private" DEFAULT_THEME = "core" db = SQLAlchemy() class Pages(db.Model): __tablename__ = "pages" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.String(80)) route = db.Column(db.String(128), unique=True) content = db.Column(db.Text) draft = db.Column(db.Boolean) hidden = db.Column(db.Boolean) auth_required = db.Column(db.Boolean) format = db.Column(db.String(80), default="markdown") # TODO: Use hidden attribute files = db.relationship("PageFiles", backref="page") def html(self): from CTFd.utils.config.pages import build_html, build_markdown if self.format == "markdown": return build_markdown(self.content) elif self.format == "html": return build_html(self.content) else: return build_markdown(self.content) def __init__(self, *args, **kwargs): super(Pages, self).__init__(**kwargs) def __repr__(self): return "<Pages {0}>".format(self.route) class Users(db.Model): __tablename__ = "users" __table_args__ = (db.UniqueConstraint("id", "oauth_id"), {}) # Core attributes id = db.Column(db.Integer, primary_key=True) oauth_id = db.Column(db.Integer, unique=True) # User names are not constrained to be unique to allow for official/unofficial teams. name = db.Column(db.String(128)) password = db.Column(db.String(128)) email = db.Column(db.String(128), unique=True) type = db.Column(db.String(80)) secret = db.Column(db.String(128)) # Supplementary attributes website = db.Column(db.String(128)) affiliation = db.Column(db.String(128)) country = db.Column(db.String(32)) bracket = db.Column(db.String(32)) hidden = db.Column(db.Boolean, default=False) banned = db.Column(db.Boolean, default=False) verified = db.Column(db.Boolean, default=False) # Relationship for Teams team_id = db.Column(db.Integer, db.ForeignKey("teams.id")) field_entries = db.relationship( "UserFieldEntries", foreign_keys="UserFieldEntries.user_id", lazy="joined" ) created = db.Column(db.DateTime, default=datetime.datetime.utcnow) __mapper_args__ = {"polymorphic_identity": "user", "polymorphic_on": type} def __init__(self, **kwargs): super(Users, self).__init__(**kwargs) def validate_password(self, key, plaintext): from CTFd.utils.crypto import hash_password return hash_password(str(plaintext)) def account_id(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team_id elif user_mode == "users": return self.id def account(self): from CTFd.utils import get_config user_mode = get_config("user_mode") if user_mode == "teams": return self.team elif user_mode == "users": return self def fields(self): return self.get_fields(admin=False) def solves(self): return self.get_solves(admin=False) def fails(self): return self.get_fails(admin=False) def awards(self): return self.get_awards(admin=False) def score(self): return self.get_score(admin=False) def place(self): from CTFd.utils.config.visibility import scores_visible if scores_visible(): return self.get_place(admin=False) else: return None def get_fields(self, admin=False): if admin: return self.field_entries return [ entry for entry in self.field_entries if entry.field.public and entry.value ] def get_solves(self, admin=False): from CTFd.utils import get_config solves = Solves.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) solves = solves.filter(Solves.date < dt) return solves.all() def get_fails(self, admin=False): from CTFd.utils import get_config fails = Fails.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) fails = fails.filter(Fails.date < dt) return fails.all() def get_awards(self, admin=False): from CTFd.utils import get_config awards = Awards.query.filter_by(user_id=self.id) freeze = get_config("freeze") if freeze and admin is False: dt = datetime.datetime.utcfromtimestamp(freeze) awards = awards.filter(Awards.date < dt) return awards.all() def get_score(self, admin=False): score = db.func.sum(Challenges.value).label("score") user = ( db.session.query(Solves.user_id, score) .join(Users, Solves.user_id == Users.id) .join(Challenges, Solves.challenge_id == Challenges.id) .filter(Users.id == self.id) ) award_score = db.func.sum(Awards.value).label("award_score") award = db.session.query(award_score).filter_by(user_id=self.id) if not admin: freeze = Configs.query.filter_by(key="freeze").first() if freeze and freeze.value: freeze = int(freeze.value) freeze = datetime.datetime.utcfromtimestamp(freeze) user = user.filter(Solves.date < freeze) award = award.filter(Awards.date < freeze) user = user.group_by(Solves.user_id).first() award = award.first() if user and award: return int(user.score or 0) + int(award.award_score or 0) elif user: return int(user.score or 0) elif award: return int(award.award_score or 0) else: return 0 def get_place(self, admin=False, numeric=False): """ This method is generally a clone of CTFd.scoreboard.get_standings. The point being that models.py must be self-reliant and have little to no imports within the CTFd application as importing from the application itself will result in a circular import. """ from CTFd.utils.scores import get_user_standings from CTFd.utils.humanize.numbers import ordinalize standings = get_user_standings(admin=admin) for i, user in enumerate(standings): if user.user_id == self.id: n = i + 1 if numeric: return n return ordinalize(n) else: return None class Admins(Users): __tablename__ = "admins" __mapper_args__ = {"polymorphic_identity": "admin"} def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def set_config(key, value): config = Configs.query.filter_by(key=key).first() if config: config.value = value else: config = Configs(key=key, value=value) db.session.add(config) db.session.commit() # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) cache.delete_memoized(_get_config, key) return config def is_setup(): return bool(get_config("setup")) is True DEFAULT_VERIFICATION_EMAIL_SUBJECT = "Confirm your account for {ctf_name}" DEFAULT_VERIFICATION_EMAIL_BODY = ( "Welcome to {ctf_name}!\n\n" "Click the following link to confirm and activate your account:\n" "{url}" "\n\n" "If the link is not clickable, try copying and pasting it into your browser." ) DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT = "Successfully registered for {ctf_name}" DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY = ( "You've successfully registered for {ctf_name}!" ) DEFAULT_USER_CREATION_EMAIL_SUBJECT = "Message from {ctf_name}" DEFAULT_USER_CREATION_EMAIL_BODY = ( "A new account has been created for you for {ctf_name} at {url}. \n\n" "Username: {name}\n" "Password: {password}" ) DEFAULT_PASSWORD_RESET_SUBJECT = "Password Reset Request from {ctf_name}" DEFAULT_PASSWORD_RESET_BODY = ( "Did you initiate a password reset on {ctf_name}? " "If you didn't initiate this request you can ignore this email. \n\n" "Click the following link to reset your password:\n{url}\n\n" "If the link is not clickable, try copying and pasting it into your browser." ) def get_errors(): return get_flashed_messages(category_filter=request.endpoint + ".errors") USERS_MODE = "users" def login_user(user): session["id"] = user.id session["nonce"] = generate_nonce() session["hash"] = hmac(user.password) # Clear out any currently cached user attributes clear_user_session(user_id=user.id) def generate_nonce(): return hexencode(os.urandom(32)) def serialize(data, secret=None): if secret is None: secret = current_app.config["SECRET_KEY"] s = URLSafeTimedSerializer(secret) return s.dumps(data) def upload_file(*args, **kwargs): file_obj = kwargs.get("file") challenge_id = kwargs.get("challenge_id") or kwargs.get("challenge") page_id = kwargs.get("page_id") or kwargs.get("page") file_type = kwargs.get("type", "standard") model_args = {"type": file_type, "location": None} model = Files if file_type == "challenge": model = ChallengeFiles model_args["challenge_id"] = challenge_id if file_type == "page": model = PageFiles model_args["page_id"] = page_id uploader = get_uploader() location = uploader.upload(file_obj=file_obj, filename=file_obj.filename) model_args["location"] = location file_row = model(**model_args) db.session.add(file_row) db.session.commit() return file_row def setup(): errors = get_errors() if not config.is_setup(): if not session.get("nonce"): session["nonce"] = generate_nonce() if request.method == "POST": # General ctf_name = request.form.get("ctf_name") ctf_description = request.form.get("ctf_description") user_mode = request.form.get("user_mode", USERS_MODE) set_config("ctf_name", ctf_name) set_config("ctf_description", ctf_description) set_config("user_mode", user_mode) # Style ctf_logo = request.files.get("ctf_logo") if ctf_logo: f = upload_file(file=ctf_logo) set_config("ctf_logo", f.location) ctf_small_icon = request.files.get("ctf_small_icon") if ctf_small_icon: f = upload_file(file=ctf_small_icon) set_config("ctf_small_icon", f.location) theme = request.form.get("ctf_theme", DEFAULT_THEME) set_config("ctf_theme", theme) theme_color = request.form.get("theme_color") theme_header = get_config("theme_header") if theme_color and bool(theme_header) is False: # Uses {{ and }} to insert curly braces while using the format method css = ( '<style id="theme-color">\n' ":root {{--theme-color: {theme_color};}}\n" ".navbar{{background-color: var(--theme-color) !important;}}\n" ".jumbotron{{background-color: var(--theme-color) !important;}}\n" "</style>\n" ).format(theme_color=theme_color) set_config("theme_header", css) # DateTime start = request.form.get("start") end = request.form.get("end") set_config("start", start) set_config("end", end) set_config("freeze", None) # Administration name = request.form["name"] email = 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).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 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( "setup.html", errors=errors, name=name, email=email, password=password, state=serialize(generate_nonce()), ) admin = Admins( name=name, email=email, password=password, type="admin", hidden=True ) # Create an empty index page page = Pages(title=None, route="index", content="", draft=False) # Upload banner default_ctf_banner_location = url_for("views.themes", path="img/logo.png") ctf_banner = request.files.get("ctf_banner") if ctf_banner: f = upload_file(file=ctf_banner, page_id=page.id) default_ctf_banner_location = url_for("views.files", path=f.location) # Splice in our banner index = f"""<div class="row"> <div class="col-md-6 offset-md-3"> <img class="w-100 mx-auto d-block" style="max-width: 500px;padding: 50px;padding-top: 14vh;" src="{default_ctf_banner_location}" /> <h3 class="text-center"> <p>A cool CTF platform from <a href="https://ctfd.io">ctfd.io</a></p> <p>Follow us on social media:</p> <a href="https://twitter.com/ctfdio"><i class="fab fa-twitter fa-2x" aria-hidden="true"></i></a>&nbsp; <a href="https://facebook.com/ctfdio"><i class="fab fa-facebook fa-2x" aria-hidden="true"></i></a>&nbsp; <a href="https://github.com/ctfd"><i class="fab fa-github fa-2x" aria-hidden="true"></i></a> </h3> <br> <h4 class="text-center"> <a href="admin">Click here</a> to login and setup your CTF </h4> </div> </div>""" page.content = index # Visibility set_config( ConfigTypes.CHALLENGE_VISIBILITY, ChallengeVisibilityTypes.PRIVATE ) set_config( ConfigTypes.REGISTRATION_VISIBILITY, RegistrationVisibilityTypes.PUBLIC ) set_config(ConfigTypes.SCORE_VISIBILITY, ScoreVisibilityTypes.PUBLIC) set_config(ConfigTypes.ACCOUNT_VISIBILITY, AccountVisibilityTypes.PUBLIC) # Verify emails set_config("verify_emails", None) set_config("mail_server", None) set_config("mail_port", None) set_config("mail_tls", None) set_config("mail_ssl", None) set_config("mail_username", None) set_config("mail_password", None) set_config("mail_useauth", None) # Set up default emails set_config("verification_email_subject", DEFAULT_VERIFICATION_EMAIL_SUBJECT) set_config("verification_email_body", DEFAULT_VERIFICATION_EMAIL_BODY) set_config( "successful_registration_email_subject", DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, ) set_config( "successful_registration_email_body", DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, ) set_config( "user_creation_email_subject", DEFAULT_USER_CREATION_EMAIL_SUBJECT ) set_config("user_creation_email_body", DEFAULT_USER_CREATION_EMAIL_BODY) set_config("password_reset_subject", DEFAULT_PASSWORD_RESET_SUBJECT) set_config("password_reset_body", DEFAULT_PASSWORD_RESET_BODY) set_config( "password_change_alert_subject", "Password Change Confirmation for {ctf_name}", ) set_config( "password_change_alert_body", ( "Your password for {ctf_name} has been changed.\n\n" "If you didn't request a password change you can reset your password here: {url}" ), ) set_config("setup", True) try: db.session.add(admin) db.session.commit() except IntegrityError: db.session.rollback() try: db.session.add(page) db.session.commit() except IntegrityError: db.session.rollback() login_user(admin) db.session.close() with app.app_context(): cache.clear() return redirect(url_for("views.static_html")) try: return render_template("setup.html", state=serialize(generate_nonce())) except TemplateNotFound: # Set theme to default and try again set_config("ctf_theme", DEFAULT_THEME) return render_template("setup.html", state=serialize(generate_nonce())) return redirect(url_for("views.static_html"))
null
158,455
import os from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, send_file, session, url_for from flask.helpers import safe_join from jinja2.exceptions import TemplateNotFound from sqlalchemy.exc import IntegrityError from CTFd.cache import cache from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.constants.themes import DEFAULT_THEME from CTFd.models import ( Admins, Files, Notifications, Pages, Teams, Users, UserTokens, db, ) from CTFd.utils import config, get_config, set_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_setup from CTFd.utils.config.pages import build_markdown, get_page from CTFd.utils.config.visibility import challenges_visible from CTFd.utils.dates import ctf_ended, ctftime, view_after_ctf from CTFd.utils.decorators import authed_only from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) from CTFd.utils.helpers import get_errors, get_infos, markup from CTFd.utils.modes import USERS_MODE from CTFd.utils.security.auth import login_user from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import ( BadSignature, BadTimeSignature, SignatureExpired, serialize, unserialize, ) from CTFd.utils.uploads import get_uploader, upload_file from CTFd.utils.user import authed, get_current_user, is_admin def set_config(key, value): config = Configs.query.filter_by(key=key).first() if config: config.value = value else: config = Configs(key=key, value=value) db.session.add(config) db.session.commit() # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) cache.delete_memoized(_get_config, key) return config def is_setup(): return bool(get_config("setup")) is True def unserialize(data, secret=None, max_age=432000): if secret is None: secret = current_app.config["SECRET_KEY"] s = URLSafeTimedSerializer(secret) return s.loads(data, max_age=max_age) def is_admin(): if authed(): user = get_current_user_attrs() return user.type == "admin" else: return False def integrations(): if is_admin() or is_setup() is False: name = request.values.get("name") state = request.values.get("state") try: state = unserialize(state, max_age=3600) except (BadSignature, BadTimeSignature): state = False except Exception: state = False if state: if name == "mlc": mlc_client_id = request.values.get("mlc_client_id") mlc_client_secret = request.values.get("mlc_client_secret") set_config("oauth_client_id", mlc_client_id) set_config("oauth_client_secret", mlc_client_secret) return render_template("admin/integrations.html") else: abort(404) else: abort(403) else: abort(403)
null
158,456
import os from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, send_file, session, url_for from flask.helpers import safe_join from jinja2.exceptions import TemplateNotFound from sqlalchemy.exc import IntegrityError from CTFd.cache import cache from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.constants.themes import DEFAULT_THEME from CTFd.models import ( Admins, Files, Notifications, Pages, Teams, Users, UserTokens, db, ) from CTFd.utils import config, get_config, set_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_setup from CTFd.utils.config.pages import build_markdown, get_page from CTFd.utils.config.visibility import challenges_visible from CTFd.utils.dates import ctf_ended, ctftime, view_after_ctf from CTFd.utils.decorators import authed_only from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) from CTFd.utils.helpers import get_errors, get_infos, markup from CTFd.utils.modes import USERS_MODE from CTFd.utils.security.auth import login_user from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import ( BadSignature, BadTimeSignature, SignatureExpired, serialize, unserialize, ) from CTFd.utils.uploads import get_uploader, upload_file from CTFd.utils.user import authed, get_current_user, is_admin class Notifications(db.Model): __tablename__ = "notifications" id = db.Column(db.Integer, primary_key=True) title = db.Column(db.Text) content = db.Column(db.Text) date = db.Column(db.DateTime, default=datetime.datetime.utcnow) user_id = db.Column(db.Integer, db.ForeignKey("users.id")) team_id = db.Column(db.Integer, db.ForeignKey("teams.id")) user = db.relationship("Users", foreign_keys="Notifications.user_id", lazy="select") team = db.relationship("Teams", foreign_keys="Notifications.team_id", lazy="select") def html(self): from CTFd.utils.config.pages import build_markdown from CTFd.utils.helpers import markup return markup(build_markdown(self.content)) def __init__(self, *args, **kwargs): super(Notifications, self).__init__(**kwargs) def notifications(): notifications = Notifications.query.order_by(Notifications.id.desc()).all() return render_template("notifications.html", notifications=notifications)
null
158,457
import os from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, send_file, session, url_for from flask.helpers import safe_join from jinja2.exceptions import TemplateNotFound from sqlalchemy.exc import IntegrityError from CTFd.cache import cache from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.constants.themes import DEFAULT_THEME from CTFd.models import ( Admins, Files, Notifications, Pages, Teams, Users, UserTokens, db, ) from CTFd.utils import config, get_config, set_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_setup from CTFd.utils.config.pages import build_markdown, get_page from CTFd.utils.config.visibility import challenges_visible from CTFd.utils.dates import ctf_ended, ctftime, view_after_ctf from CTFd.utils.decorators import authed_only from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) from CTFd.utils.helpers import get_errors, get_infos, markup from CTFd.utils.modes import USERS_MODE from CTFd.utils.security.auth import login_user from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import ( BadSignature, BadTimeSignature, SignatureExpired, serialize, unserialize, ) from CTFd.utils.uploads import get_uploader, upload_file from CTFd.utils.user import authed, get_current_user, is_admin class UserTokens(Tokens): __mapper_args__ = {"polymorphic_identity": "user"} def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def markup(text): """ Mark text as safe to inject as HTML into templates """ return Markup(text) def get_infos(): return get_flashed_messages(category_filter=request.endpoint + ".infos") def get_current_user(): if authed(): user = Users.query.filter_by(id=session["id"]).first() # Check if the session is still valid session_hash = session.get("hash") if session_hash: if session_hash != hmac(user.password): logout_user() if request.content_type == "application/json": error = 401 else: error = redirect(url_for("auth.login", next=request.full_path)) abort(error) return user else: return None def settings(): infos = get_infos() user = get_current_user() name = user.name email = user.email website = user.website affiliation = user.affiliation country = user.country tokens = UserTokens.query.filter_by(user_id=user.id).all() prevent_name_change = get_config("prevent_name_change") if get_config("verify_emails") and not user.verified: confirm_url = markup(url_for("auth.confirm")) infos.append( markup( "Your email address isn't confirmed!<br>" "Please check your email to confirm your email address.<br><br>" f'To have the confirmation email resent please <a href="{confirm_url}">click here</a>.' ) ) return render_template( "settings.html", name=name, email=email, website=website, affiliation=affiliation, country=country, tokens=tokens, prevent_name_change=prevent_name_change, infos=infos, )
null
158,458
import os from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, send_file, session, url_for from flask.helpers import safe_join from jinja2.exceptions import TemplateNotFound from sqlalchemy.exc import IntegrityError from CTFd.cache import cache from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.constants.themes import DEFAULT_THEME from CTFd.models import ( Admins, Files, Notifications, Pages, Teams, Users, UserTokens, db, ) from CTFd.utils import config, get_config, set_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_setup from CTFd.utils.config.pages import build_markdown, get_page from CTFd.utils.config.visibility import challenges_visible from CTFd.utils.dates import ctf_ended, ctftime, view_after_ctf from CTFd.utils.decorators import authed_only from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) from CTFd.utils.helpers import get_errors, get_infos, markup from CTFd.utils.modes import USERS_MODE from CTFd.utils.security.auth import login_user from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import ( BadSignature, BadTimeSignature, SignatureExpired, serialize, unserialize, ) from CTFd.utils.uploads import get_uploader, upload_file from CTFd.utils.user import authed, get_current_user, is_admin def get_page(route): page = db.session.execute( Pages.__table__.select() .where(Pages.route == route) .where(Pages.draft.isnot(True)) ).fetchone() if page: # Convert the row into a transient ORM object so this change isn't commited accidentally p = Pages(**page) return p return None def authed(): return bool(session.get("id", False)) The provided code snippet includes necessary dependencies for implementing the `static_html` function. Write a Python function `def static_html(route)` to solve the following problem: Route in charge of routing users to Pages. :param route: :return: Here is the function: def static_html(route): """ Route in charge of routing users to Pages. :param route: :return: """ page = get_page(route) if page is None: abort(404) else: if page.auth_required and authed() is False: return redirect(url_for("auth.login", next=request.full_path)) return render_template("page.html", content=page.html, title=page.title)
Route in charge of routing users to Pages. :param route: :return:
158,459
import os from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, send_file, session, url_for from flask.helpers import safe_join from jinja2.exceptions import TemplateNotFound from sqlalchemy.exc import IntegrityError from CTFd.cache import cache from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.constants.themes import DEFAULT_THEME from CTFd.models import ( Admins, Files, Notifications, Pages, Teams, Users, UserTokens, db, ) from CTFd.utils import config, get_config, set_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_setup from CTFd.utils.config.pages import build_markdown, get_page from CTFd.utils.config.visibility import challenges_visible from CTFd.utils.dates import ctf_ended, ctftime, view_after_ctf from CTFd.utils.decorators import authed_only from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) from CTFd.utils.helpers import get_errors, get_infos, markup from CTFd.utils.modes import USERS_MODE from CTFd.utils.security.auth import login_user from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import ( BadSignature, BadTimeSignature, SignatureExpired, serialize, unserialize, ) from CTFd.utils.uploads import get_uploader, upload_file from CTFd.utils.user import authed, get_current_user, is_admin def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def build_markdown(md, sanitize=False): html = markdown(md) html = format_variables(html) if current_app.config["HTML_SANITIZATION"] is True or sanitize is True: html = sanitize_html(html) return html def tos(): tos_url = get_config("tos_url") tos_text = get_config("tos_text") if tos_url: return redirect(tos_url) elif tos_text: return render_template("page.html", content=build_markdown(tos_text)) else: abort(404)
null
158,460
import os from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, send_file, session, url_for from flask.helpers import safe_join from jinja2.exceptions import TemplateNotFound from sqlalchemy.exc import IntegrityError from CTFd.cache import cache from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.constants.themes import DEFAULT_THEME from CTFd.models import ( Admins, Files, Notifications, Pages, Teams, Users, UserTokens, db, ) from CTFd.utils import config, get_config, set_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_setup from CTFd.utils.config.pages import build_markdown, get_page from CTFd.utils.config.visibility import challenges_visible from CTFd.utils.dates import ctf_ended, ctftime, view_after_ctf from CTFd.utils.decorators import authed_only from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) from CTFd.utils.helpers import get_errors, get_infos, markup from CTFd.utils.modes import USERS_MODE from CTFd.utils.security.auth import login_user from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import ( BadSignature, BadTimeSignature, SignatureExpired, serialize, unserialize, ) from CTFd.utils.uploads import get_uploader, upload_file from CTFd.utils.user import authed, get_current_user, is_admin def get_config(key, default=None): def build_markdown(md, sanitize=False): def privacy(): privacy_url = get_config("privacy_url") privacy_text = get_config("privacy_text") if privacy_url: return redirect(privacy_url) elif privacy_text: return render_template("page.html", content=build_markdown(privacy_text)) else: abort(404)
null
158,461
import os from flask import Blueprint, abort from flask import current_app as app from flask import redirect, render_template, request, send_file, session, url_for from flask.helpers import safe_join from jinja2.exceptions import TemplateNotFound from sqlalchemy.exc import IntegrityError from CTFd.cache import cache from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.constants.themes import DEFAULT_THEME from CTFd.models import ( Admins, Files, Notifications, Pages, Teams, Users, UserTokens, db, ) from CTFd.utils import config, get_config, set_config from CTFd.utils import user as current_user from CTFd.utils import validators from CTFd.utils.config import is_setup from CTFd.utils.config.pages import build_markdown, get_page from CTFd.utils.config.visibility import challenges_visible from CTFd.utils.dates import ctf_ended, ctftime, view_after_ctf from CTFd.utils.decorators import authed_only from CTFd.utils.email import ( DEFAULT_PASSWORD_RESET_BODY, DEFAULT_PASSWORD_RESET_SUBJECT, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_BODY, DEFAULT_SUCCESSFUL_REGISTRATION_EMAIL_SUBJECT, DEFAULT_USER_CREATION_EMAIL_BODY, DEFAULT_USER_CREATION_EMAIL_SUBJECT, DEFAULT_VERIFICATION_EMAIL_BODY, DEFAULT_VERIFICATION_EMAIL_SUBJECT, ) from CTFd.utils.helpers import get_errors, get_infos, markup from CTFd.utils.modes import USERS_MODE from CTFd.utils.security.auth import login_user from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import ( BadSignature, BadTimeSignature, SignatureExpired, serialize, unserialize, ) from CTFd.utils.uploads import get_uploader, upload_file from CTFd.utils.user import authed, get_current_user, is_admin The provided code snippet includes necessary dependencies for implementing the `themes` function. Write a Python function `def themes(theme, path)` to solve the following problem: General static file handler :param theme: :param path: :return: Here is the function: def themes(theme, path): """ General static file handler :param theme: :param path: :return: """ for cand_path in ( safe_join(app.root_path, "themes", cand_theme, "static", path) # The `theme` value passed in may not be the configured one, e.g. for # admin pages, so we check that first for cand_theme in (theme, *config.ctf_theme_candidates()) ): if os.path.isfile(cand_path): return send_file(cand_path) abort(404)
General static file handler :param theme: :param path: :return:
158,462
import inspect import os from alembic.config import Config from alembic.migration import MigrationContext from alembic.operations import Operations from alembic.script import ScriptDirectory from flask import current_app from sqlalchemy import create_engine, pool from CTFd.utils import get_config, set_config def get_config(key, default=None): def current(plugin_name=None): if plugin_name is None: # Get the directory name of the plugin if unspecified # Doing it this way doesn't waste the rest of the inspect.stack call frame = inspect.currentframe() caller_info = inspect.getframeinfo(frame.f_back) caller_path = caller_info[0] plugin_name = os.path.basename(os.path.dirname(caller_path)) return get_config(plugin_name + "_alembic_version")
null
158,463
import inspect import os from alembic.config import Config from alembic.migration import MigrationContext from alembic.operations import Operations from alembic.script import ScriptDirectory from flask import current_app from sqlalchemy import create_engine, pool from CTFd.utils import get_config, set_config def get_config(key, default=None): def set_config(key, value): def upgrade(plugin_name=None, revision=None, lower="current"): database_url = current_app.config.get("SQLALCHEMY_DATABASE_URI") if database_url.startswith("sqlite"): current_app.db.create_all() return if plugin_name is None: # Get the directory name of the plugin if unspecified # Doing it this way doesn't waste the rest of the inspect.stack call frame = inspect.currentframe() caller_info = inspect.getframeinfo(frame.f_back) caller_path = caller_info[0] plugin_name = os.path.basename(os.path.dirname(caller_path)) # Check if the plugin has migraitons migrations_path = os.path.join(current_app.plugins_dir, plugin_name, "migrations") if os.path.isdir(migrations_path) is False: return engine = create_engine(database_url, poolclass=pool.NullPool) conn = engine.connect() context = MigrationContext.configure(conn) op = Operations(context) # Find the list of migrations to run config = Config() config.set_main_option("script_location", migrations_path) config.set_main_option("version_locations", migrations_path) script = ScriptDirectory.from_config(config) # Choose base revision for plugin upgrade # "current" points to the current plugin version stored in config # None represents the absolute base layer (e.g. first installation) if lower == "current": lower = get_config(plugin_name + "_alembic_version") # Do we upgrade to head or to a specific revision if revision is None: upper = script.get_current_head() else: upper = revision # Apply from lower to upper revs = list(script.iterate_revisions(lower=lower, upper=upper)) revs.reverse() try: for r in revs: with context.begin_transaction(): r.module.upgrade(op=op) # Set revision that succeeded so we don't need # to start from the beginning on failure set_config(plugin_name + "_alembic_version", r.revision) finally: conn.close() # Set the new latest revision set_config(plugin_name + "_alembic_version", upper)
null
158,464
def upgrade(op=None): bind = op.get_bind() url = str(bind.engine.url) if url.startswith("mysql"): op.drop_constraint( "dynamic_challenge_ibfk_1", "dynamic_challenge", type_="foreignkey" ) elif url.startswith("postgres"): op.drop_constraint( "dynamic_challenge_id_fkey", "dynamic_challenge", type_="foreignkey" ) op.create_foreign_key( None, "dynamic_challenge", "challenges", ["id"], ["id"], ondelete="CASCADE" ) # ### end Alembic commands ###
null
158,465
def downgrade(op=None): bind = op.get_bind() url = str(bind.engine.url) if url.startswith("mysql"): op.drop_constraint( "dynamic_challenge_ibfk_1", "dynamic_challenge", type_="foreignkey" ) elif url.startswith("postgres"): op.drop_constraint( "dynamic_challenge_id_fkey", "dynamic_challenge", type_="foreignkey" ) op.create_foreign_key(None, "dynamic_challenge", "challenges", ["id"], ["id"])
null
158,466
def pluralize(number, singular="", plural="s"): if number == 1: return singular else: return plural
null
158,467
The provided code snippet includes necessary dependencies for implementing the `ordinalize` function. Write a Python function `def ordinalize(n)` to solve the following problem: http://codegolf.stackexchange.com/a/4712 Here is the function: def ordinalize(n): """ http://codegolf.stackexchange.com/a/4712 """ k = n % 10 return "%d%s" % (n, "tsnrhtdd"[(n // 10 % 10 != 1) * (k < 4) * k :: 4])
http://codegolf.stackexchange.com/a/4712
158,468
from sqlalchemy.exc import OperationalError, ProgrammingError from CTFd.utils.exports.serializers import JSONSerializer class JSONSerializer(object): def __init__(self, query, fileobj): self.query = query self.fileobj = fileobj self.buckets = defaultdict(list) def serialize(self): for row in self.query: self.write(None, row) self.close() def write(self, path, result): self.buckets[path].append(result) def wrap(self, result): result = OrderedDict( [("count", len(result)), ("results", result), ("meta", {})] ) return result def close(self): for _path, result in self.buckets.items(): result = self.wrap(result) # Certain databases (MariaDB) store JSON as LONGTEXT. # Before emitting a file we should standardize to valid JSON (i.e. a dict) # See Issue #973 for i, r in enumerate(result["results"]): data = r.get("requirements") if data: try: if isinstance(data, string_types): result["results"][i]["requirements"] = json.loads(data) except ValueError: pass data = json.dumps(result, cls=JSONEncoder, separators=(",", ":")) self.fileobj.write(data.encode("utf-8")) def freeze_export(result, fileobj): try: query = result serializer = JSONSerializer(query, fileobj) serializer.serialize() except (OperationalError, ProgrammingError) as e: raise OperationalError("Invalid query: %s" % e)
null
158,469
import functools from flask import abort from CTFd.utils import get_config from CTFd.utils.modes import TEAMS_MODE, USERS_MODE def get_config(key, default=None): USERS_MODE = "users" def require_team_mode(f): @functools.wraps(f) def _require_team_mode(*args, **kwargs): if get_config("user_mode") == USERS_MODE: abort(404) return f(*args, **kwargs) return _require_team_mode
null
158,470
import functools from flask import abort from CTFd.utils import get_config from CTFd.utils.modes import TEAMS_MODE, USERS_MODE def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value TEAMS_MODE = "teams" def require_user_mode(f): @functools.wraps(f) def _require_user_mode(*args, **kwargs): if get_config("user_mode") == TEAMS_MODE: abort(404) return f(*args, **kwargs) return _require_user_mode
null
158,471
import functools from flask import abort, redirect, render_template, request, url_for from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.utils import get_config from CTFd.utils.user import authed, is_admin class ConfigTypes(str, RawEnum): CHALLENGE_VISIBILITY = "challenge_visibility" SCORE_VISIBILITY = "score_visibility" ACCOUNT_VISIBILITY = "account_visibility" REGISTRATION_VISIBILITY = "registration_visibility" class ScoreVisibilityTypes(str, RawEnum): PUBLIC = "public" PRIVATE = "private" HIDDEN = "hidden" ADMINS = "admins" def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def authed(): return bool(session.get("id", False)) def is_admin(): if authed(): user = get_current_user_attrs() return user.type == "admin" else: return False def check_score_visibility(f): @functools.wraps(f) def _check_score_visibility(*args, **kwargs): v = get_config(ConfigTypes.SCORE_VISIBILITY) if v == ScoreVisibilityTypes.PUBLIC: return f(*args, **kwargs) elif v == ScoreVisibilityTypes.PRIVATE: if authed(): return f(*args, **kwargs) else: if request.content_type == "application/json": abort(403) else: return redirect(url_for("auth.login", next=request.full_path)) elif v == ScoreVisibilityTypes.HIDDEN: if is_admin(): return f(*args, **kwargs) else: if request.content_type == "application/json": abort(403) else: return ( render_template( "errors/403.html", error="Scores are currently hidden" ), 403, ) elif v == ScoreVisibilityTypes.ADMINS: if is_admin(): return f(*args, **kwargs) else: abort(404) return _check_score_visibility
null
158,472
import functools from flask import abort, redirect, render_template, request, url_for from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.utils import get_config from CTFd.utils.user import authed, is_admin class ConfigTypes(str, RawEnum): CHALLENGE_VISIBILITY = "challenge_visibility" SCORE_VISIBILITY = "score_visibility" ACCOUNT_VISIBILITY = "account_visibility" REGISTRATION_VISIBILITY = "registration_visibility" class ChallengeVisibilityTypes(str, RawEnum): PUBLIC = "public" PRIVATE = "private" ADMINS = "admins" def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def authed(): return bool(session.get("id", False)) def is_admin(): if authed(): user = get_current_user_attrs() return user.type == "admin" else: return False def check_challenge_visibility(f): @functools.wraps(f) def _check_challenge_visibility(*args, **kwargs): v = get_config(ConfigTypes.CHALLENGE_VISIBILITY) if v == ChallengeVisibilityTypes.PUBLIC: return f(*args, **kwargs) elif v == ChallengeVisibilityTypes.PRIVATE: if authed(): return f(*args, **kwargs) else: if request.content_type == "application/json": abort(403) else: return redirect(url_for("auth.login", next=request.full_path)) elif v == ChallengeVisibilityTypes.ADMINS: if is_admin(): return f(*args, **kwargs) else: if authed(): abort(403) else: return redirect(url_for("auth.login", next=request.full_path)) return _check_challenge_visibility
null
158,473
import functools from flask import abort, redirect, render_template, request, url_for from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.utils import get_config from CTFd.utils.user import authed, is_admin class ConfigTypes(str, RawEnum): CHALLENGE_VISIBILITY = "challenge_visibility" SCORE_VISIBILITY = "score_visibility" ACCOUNT_VISIBILITY = "account_visibility" REGISTRATION_VISIBILITY = "registration_visibility" class AccountVisibilityTypes(str, RawEnum): PUBLIC = "public" PRIVATE = "private" ADMINS = "admins" def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def authed(): return bool(session.get("id", False)) def is_admin(): if authed(): user = get_current_user_attrs() return user.type == "admin" else: return False def check_account_visibility(f): @functools.wraps(f) def _check_account_visibility(*args, **kwargs): v = get_config(ConfigTypes.ACCOUNT_VISIBILITY) if v == AccountVisibilityTypes.PUBLIC: return f(*args, **kwargs) elif v == AccountVisibilityTypes.PRIVATE: if authed(): return f(*args, **kwargs) else: if request.content_type == "application/json": abort(403) else: return redirect(url_for("auth.login", next=request.full_path)) elif v == AccountVisibilityTypes.ADMINS: if is_admin(): return f(*args, **kwargs) else: abort(404) return _check_account_visibility
null
158,474
import functools from flask import abort, redirect, render_template, request, url_for from CTFd.constants.config import ( AccountVisibilityTypes, ChallengeVisibilityTypes, ConfigTypes, RegistrationVisibilityTypes, ScoreVisibilityTypes, ) from CTFd.utils import get_config from CTFd.utils.user import authed, is_admin class ConfigTypes(str, RawEnum): CHALLENGE_VISIBILITY = "challenge_visibility" SCORE_VISIBILITY = "score_visibility" ACCOUNT_VISIBILITY = "account_visibility" REGISTRATION_VISIBILITY = "registration_visibility" class RegistrationVisibilityTypes(str, RawEnum): PUBLIC = "public" PRIVATE = "private" def get_config(key, default=None): # Convert enums to raw string values to cache better if isinstance(key, Enum): key = str(key) value = _get_config(key) if value is KeyError: return default else: return value def check_registration_visibility(f): @functools.wraps(f) def _check_registration_visibility(*args, **kwargs): v = get_config(ConfigTypes.REGISTRATION_VISIBILITY) if v == RegistrationVisibilityTypes.PUBLIC: return f(*args, **kwargs) elif v == RegistrationVisibilityTypes.PRIVATE: abort(404) return _check_registration_visibility
null
158,475
from pybluemonday import UGCPolicy SANITIZER = UGCPolicy() SANITIZER.AllowAttrs(*SAFE_ATTRS).Globally() SANITIZER.AllowAttrs("class", "style").Globally() SANITIZER.AllowStyling() SANITIZER.AllowStandardAttributes() SANITIZER.AllowStandardURLs() SANITIZER.AllowDataAttributes() SANITIZER.AllowDataURIImages() SANITIZER.AllowRelativeURLs(True) SANITIZER.RequireNoFollowOnFullyQualifiedLinks(True) SANITIZER.RequireNoFollowOnLinks(True) SANITIZER.RequireNoReferrerOnFullyQualifiedLinks(True) SANITIZER.RequireNoReferrerOnLinks(True) SANITIZER.AllowComments() def sanitize_html(html): return SANITIZER.sanitize(html)
null
158,476
from CTFd.utils.crypto import hash_password as hp from CTFd.utils.crypto import sha256 as sha from CTFd.utils.crypto import verify_password as vp def hash_password(p): print( "This function will be deprecated in a future release. Please update to CTFd.utils.crypto.hash_password" ) return hp(p)
null
158,477
from CTFd.utils.crypto import hash_password as hp from CTFd.utils.crypto import sha256 as sha from CTFd.utils.crypto import verify_password as vp def check_password(p, hash): print( "This function will be deprecated in a future release. Please update to CTFd.utils.crypto.verify_password" ) return vp(p, hash)
null
158,478
from CTFd.utils.crypto import hash_password as hp from CTFd.utils.crypto import sha256 as sha from CTFd.utils.crypto import verify_password as vp def sha256(p): print( "This function will be deprecated in a future release. Please update to CTFd.utils.crypto.sha256" ) return sha(p)
null
158,479
import os from CTFd.utils.encoding import hexencode def hexencode(s): if isinstance(s, string_types): s = s.encode("utf-8") encoded = codecs.encode(s, "hex") try: encoded = encoded.decode("utf-8") except UnicodeDecodeError: pass return encoded def generate_nonce(): return hexencode(os.urandom(32))
null
158,480
import datetime import os from flask import session from CTFd.cache import clear_user_session from CTFd.exceptions import UserNotFoundException, UserTokenExpiredException from CTFd.models import UserTokens, db from CTFd.utils.encoding import hexencode from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import hmac def clear_user_session(user_id): def generate_nonce(): import hmac as _hmac def hmac(data, secret=None, digest=hashlib.sha1): def login_user(user): session["id"] = user.id session["nonce"] = generate_nonce() session["hash"] = hmac(user.password) # Clear out any currently cached user attributes clear_user_session(user_id=user.id)
null
158,481
import datetime import os from flask import session from CTFd.cache import clear_user_session from CTFd.exceptions import UserNotFoundException, UserTokenExpiredException from CTFd.models import UserTokens, db from CTFd.utils.encoding import hexencode from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import hmac def clear_user_session(user_id): import hmac as _hmac def hmac(data, secret=None, digest=hashlib.sha1): def update_user(user): session["id"] = user.id session["hash"] = hmac(user.password) # Clear out any currently cached user attributes clear_user_session(user_id=user.id)
null
158,482
import datetime import os from flask import session from CTFd.cache import clear_user_session from CTFd.exceptions import UserNotFoundException, UserTokenExpiredException from CTFd.models import UserTokens, db from CTFd.utils.encoding import hexencode from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import hmac def logout_user(): session.clear()
null
158,483
import datetime import os from flask import session from CTFd.cache import clear_user_session from CTFd.exceptions import UserNotFoundException, UserTokenExpiredException from CTFd.models import UserTokens, db from CTFd.utils.encoding import hexencode from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import hmac db = SQLAlchemy() class UserTokens(Tokens): def hexencode(s): def generate_user_token(user, expiration=None): temp_token = True while temp_token is not None: value = hexencode(os.urandom(32)) temp_token = UserTokens.query.filter_by(value=value).first() token = UserTokens(user_id=user.id, expiration=expiration, value=value) db.session.add(token) db.session.commit() return token
null
158,484
import datetime import os from flask import session from CTFd.cache import clear_user_session from CTFd.exceptions import UserNotFoundException, UserTokenExpiredException from CTFd.models import UserTokens, db from CTFd.utils.encoding import hexencode from CTFd.utils.security.csrf import generate_nonce from CTFd.utils.security.signing import hmac class UserNotFoundException(Exception): pass class UserTokenExpiredException(Exception): pass class UserTokens(Tokens): __mapper_args__ = {"polymorphic_identity": "user"} def lookup_user_token(token): token = UserTokens.query.filter_by(value=token).first() if token: if datetime.datetime.utcnow() >= token.expiration: raise UserTokenExpiredException return token.user else: raise UserNotFoundException return None
null
158,485
import hashlib import hmac as _hmac from flask import current_app from itsdangerous import Signer from itsdangerous.exc import ( # noqa: F401 BadSignature, BadTimeSignature, SignatureExpired, ) from itsdangerous.url_safe import URLSafeTimedSerializer from CTFd.utils import string_types def serialize(data, secret=None): if secret is None: secret = current_app.config["SECRET_KEY"] s = URLSafeTimedSerializer(secret) return s.dumps(data)
null
158,486
import hashlib import hmac as _hmac from flask import current_app from itsdangerous import Signer from itsdangerous.exc import ( # noqa: F401 BadSignature, BadTimeSignature, SignatureExpired, ) from itsdangerous.url_safe import URLSafeTimedSerializer from CTFd.utils import string_types def unserialize(data, secret=None, max_age=432000): if secret is None: secret = current_app.config["SECRET_KEY"] s = URLSafeTimedSerializer(secret) return s.loads(data, max_age=max_age)
null
158,487
import hashlib import hmac as _hmac from flask import current_app from itsdangerous import Signer from itsdangerous.exc import ( # noqa: F401 BadSignature, BadTimeSignature, SignatureExpired, ) from itsdangerous.url_safe import URLSafeTimedSerializer from CTFd.utils import string_types def sign(data, secret=None): if secret is None: secret = current_app.config["SECRET_KEY"] s = Signer(secret) return s.sign(data)
null
158,488
import hashlib import hmac as _hmac from flask import current_app from itsdangerous import Signer from itsdangerous.exc import ( # noqa: F401 BadSignature, BadTimeSignature, SignatureExpired, ) from itsdangerous.url_safe import URLSafeTimedSerializer from CTFd.utils import string_types def unsign(data, secret=None): if secret is None: secret = current_app.config["SECRET_KEY"] s = Signer(secret) return s.unsign(data)
null