def test_get_configuration(self): """test the get_configuration function""" string_config = model.Configuration( "String_Config", "sample", "string", "admin" ) bool_config = model.Configuration("Bool_Config", "True", "bool", "admin") integer_config = model.Configuration("Integer_Config", "12", "integer", "admin") db_session.add_all([string_config, bool_config, integer_config]) db_session.commit() self.assertEqual(util.get_configuration("String_Config"), "sample") self.assertEqual(util.get_configuration("Bool_Config"), True) self.assertEqual(util.get_configuration("Integer_Config"), 12)
def signup(): if not request.json: return jsonify({"msg": "Bad request"}), 400 extra_signup_fields = util.get_configuration("extra_signup_fields") is_sucess, fields_or_error = _validate_and_get_required_fields( [ "username", "name", "password", "password2", "contest_name", *extra_signup_fields, ] ) if not is_sucess: return fields_or_error fields = fields_or_error if fields["password"] != fields["password2"]: return jsonify({"msg": "Passwords don't match"}), 400 user = model.User.query.filter_by(username=fields["username"]).scalar() if user: return jsonify({"msg": "User already exists with that username"}), 400 defedant_role = model.UserRole.query.filter_by(name="defendant").scalar() new_user = model.User( username=fields["username"], name=fields["name"], password=fields["password"], user_roles=[defedant_role], ) extra_signup_fields_dict = {k: fields[k] for k in extra_signup_fields} new_user.merge_metadata(extra_signup_fields_dict) contest = model.Contest.query.filter_by(name=fields["contest_name"]).scalar() if not contest: return make_response(jsonify({"error": "Invalid contest name"}), 400) new_user.contests.append(contest) db_session.add(new_user) db_session.commit() ret = {"access_token": create_access_token(identity=new_user.id)} return jsonify(ret), 200
def create_app(): """ Initializes the flask app object Returns: Flask: the initialized flask app """ app = Flask(__name__) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 86400 # 1 day app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_ECHO'] = False app.config['SQLALCHEMY_RECORD_QUERIES'] = False app.config['model'] = model app.config[ 'SECRET_KEY'] = '2jrlkfjoi1j3kljekdlasjdklasjdk139999d9d' #TODO: put this in config app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(days=30) if app.config.get("SSL"): app.config.update(dict(PREFERRED_URL_SCHEME='https')) app.config['RUNMODE'] = "PRODUCTION" if os.getenv(CODE_COURT_PRODUCTION_ENV_VAR) else "DEVELOPMENT" # Add datetime to string filter to Jinja2 # http://flask.pocoo.org/docs/0.12/templating/ app.jinja_env.filters['dt_to_str'] = model.dt_to_str app.jinja_env.filters['dt_to_date_str'] = model.dt_to_date_str app.jinja_env.filters['dt_to_time_str'] = model.dt_to_time_str setup_logging(app) app.logger.setLevel(logging.DEBUG) init_db() if not app.config['TESTING']: setup_database(app) with app.app_context(): app.config['MAX_CONTENT_LENGTH'] = util.get_configuration( "max_output_length") * 1024 # kilobytes CORS(app) JWTManager(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = "auth.login_view" DebugToolbarExtension(app) app.logger.info("Setting up app") @login_manager.user_loader def load_user(user_email): return model.User.query.filter_by(email=user_email).one() app.register_blueprint(main, url_prefix='') app.register_blueprint(api, url_prefix='/api') app.register_blueprint(admin, url_prefix='/admin') app.register_blueprint(configurations, url_prefix='/admin/configurations') app.register_blueprint(clarifications, url_prefix='/admin/clarifications') app.register_blueprint(languages, url_prefix='/admin/languages') app.register_blueprint(problems, url_prefix='/admin/problems') app.register_blueprint(users, url_prefix='/admin/users') app.register_blueprint(runs, url_prefix='/admin/runs') app.register_blueprint(contests, url_prefix='/admin/contests') app.register_blueprint(defendant, url_prefix='/defendant') app.register_blueprint(auth, url_prefix='/admin') @app.context_processor def inject_user(): return {} @app.route('/') def defendant_index(): return send_from_directory('static/defendant-frontend', "index.html") @app.route('/<path:path>') def all(path): try: return send_from_directory('static/defendant-frontend', path) except werkzeug.exceptions.NotFound as e: return send_from_directory('static/defendant-frontend', "index.html") @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(401) @login_manager.unauthorized_handler def unauthorized(callback=None): if not current_user.is_authenticated: return render_template('auth/login.html'), 401 return render_template('401.html'), 401 @app.teardown_appcontext def teardown(exception=None): db_session.remove() @app.after_request def after_request(resp): if app.config.get('SQLALCHEMY_RECORD_QUERIES'): with open("/home/ben/sql", "a+") as f: f.write("=========\n{}:\n\n".format(request.url)) for q in get_debug_queries(): f.write("{}\n\n".format(q)) f.write("=========\n\n") return resp return app
def create_app(): """ Initializes the flask app object Returns: Flask: the initialized flask app """ app = Flask(__name__) app.config['SEND_FILE_MAX_AGE_DEFAULT'] = 86400 # 1 day app.config['SQLALCHEMY_DATABASE_URI'] = "sqlite:////tmp/code_court.db" #TODO: put this in config app.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False app.config['SQLALCHEMY_ECHO'] = False app.config['model'] = model app.config['SECRET_KEY'] = 'secret key1234' #TODO: put this in config app.config['JWT_ACCESS_TOKEN_EXPIRES'] = datetime.timedelta(days=30) if app.config.get("SSL"): app.config.update(dict(PREFERRED_URL_SCHEME = 'https')) # Add datetime to string filter to Jinja2 # http://flask.pocoo.org/docs/0.12/templating/ app.jinja_env.filters['dt_to_str'] = model.dt_to_str app.jinja_env.filters['dt_to_date_str'] = model.dt_to_date_str app.jinja_env.filters['dt_to_time_str'] = model.dt_to_time_str db.init_app(app) if not app.config['TESTING']: setup_database(app) with app.app_context(): app.config['MAX_CONTENT_LENGTH'] = util.get_configuration("max_output_length") * 1024 #kilobytes CORS(app) jwt = JWTManager(app) login_manager = LoginManager() login_manager.init_app(app) login_manager.login_view = "auth.login_view" toolbar = DebugToolbarExtension(app) @login_manager.user_loader def load_user(user_email): return model.User.query.filter_by(email=user_email).one() app.logger.setLevel(logging.DEBUG) app.register_blueprint(main, url_prefix='') app.register_blueprint(api, url_prefix='/api') app.register_blueprint(admin, url_prefix='/admin') app.register_blueprint(configurations, url_prefix='/admin/configurations') app.register_blueprint(clarifications, url_prefix='/admin/clarifications') app.register_blueprint(languages, url_prefix='/admin/languages') app.register_blueprint(problems, url_prefix='/admin/problems') app.register_blueprint(users, url_prefix='/admin/users') app.register_blueprint(runs, url_prefix='/admin/runs') app.register_blueprint(contests, url_prefix='/admin/contests') app.register_blueprint(defendant, url_prefix='/defendant') app.register_blueprint(auth, url_prefix='/admin') @app.context_processor def inject_user(): return { } @app.route('/') def defendant_index(): return send_from_directory('static/defendant-frontend', "index.html") @app.route('/<path:path>') def all(path): try: return send_from_directory('static/defendant-frontend', path) except werkzeug.exceptions.NotFound as e: return send_from_directory('static/defendant-frontend', "index.html") @app.errorhandler(404) def page_not_found(e): return render_template('404.html'), 404 @app.errorhandler(401) @login_manager.unauthorized_handler def unauthorized(callback=None): if not current_user.is_authenticated: return render_template('auth/login.html'), 401 return render_template('401.html'), 401 return app
def submit_run(): """submit a run to be executed""" model = util.get_model() current_user_id = get_jwt_identity() user = model.User.query.filter_by(id=current_user_id).scalar() MAX_RUNS = util.get_configuration("max_user_submissions") TIME_LIMIT = util.get_configuration("user_submission_time_limit") over_limit_runs_query= model.Run.submit_time >\ (datetime.datetime.utcnow() - datetime.timedelta(minutes=TIME_LIMIT)) run_count = model.Run.query.filter_by(user_id=user.id)\ .filter(over_limit_runs_query)\ .count() if run_count > MAX_RUNS: return make_response( jsonify({'error': 'Submission rate limit exceeded'}), 400) contest = user.contests[0] lang_name = request.json.get('lang', None) problem_slug = request.json.get('problem_slug', None) source_code = request.json.get('source_code', None) is_submission = request.json.get('is_submission', False) user_test_input = request.json.get('user_test_input', None) lang = model.Language.query.filter_by(name=lang_name).one() problem = model.Problem.query.filter_by(slug=problem_slug).scalar() run_input = None run_output = None if is_submission: run_input = problem.secret_input run_output = problem.secret_output else: if user_test_input: run_input = user_test_input else: run_input = problem.sample_input run_output = problem.sample_output run = model.Run(user, contest, lang, problem, datetime.datetime.utcnow(), source_code, run_input, run_output, is_submission) run.state = "Judging" resp = None if datetime.datetime.utcnow() > contest.end_time: run.state = "ContestEnded" run.started_execing_time = datetime.datetime.utcnow() run.finished_execing_time = datetime.datetime.utcnow() resp = make_response(jsonify({'error': 'Contest has ended'}), 400) elif datetime.datetime.utcnow() < contest.start_time: run.state = "ContestHasNotBegun" run.started_execing_time = datetime.datetime.utcnow() run.finished_execing_time = datetime.datetime.utcnow() resp = make_response(jsonify({'error': 'Contest has not begun'}), 400) else: resp = make_response(jsonify({'status': 'good'}), 200) model.db.session.add(run) model.db.session.commit() return resp
def load_test(): existing_user = model.User.query.filter_by(username="******").scalar() contest = model.Contest.query.first() defendants = ( model.User.query.filter(model.User.user_roles.any(name="defendant")) .filter(model.User.contests.any(id=contest.id)) .all() ) problems = ( model.Problem.query.filter(model.Problem.contests.any(id=contest.id)) .filter(model.Problem.is_enabled) .all() ) user_points = [] for user in defendants: problem_states = {} penalty = 0 for problem in problems: is_passed = 0 < len( model.Run.query.filter_by( is_submission=True, is_passed=True, user=user, contest=contest, problem=problem, ).all() ) problem_states[problem.slug] = is_passed failed_subs = model.Run.query.filter_by( is_submission=True, is_passed=False, user=user, contest=contest, problem=problem, ).all() for sub in failed_subs: penalty += 1 # TODO we may want to use the time submitted instead of 1 # to match ICPC scoring user_points.append( { "user": user.get_output_dict(), "num_solved": len([x for x in problem_states.values() if x]), "penalty": penalty, "problem_states": problem_states, } ) user_points.sort(key=lambda x: (x["num_solved"], -x["penalty"]), reverse=True) user = model.User.query.filter_by(username="******").scalar() if not user or not user.verify_password("test"): pass user = model.User.query.filter_by(username="******").scalar() if not user or not user.verify_password("password"): pass langs = model.Language.query.all() filter_langs = [x.get_output_dict() for x in langs if x.is_enabled] curr_user = model.User.query.filter_by(id=util.i(5)).scalar() contests = curr_user.contests resp = None if curr_user: resp = curr_user.get_output_dict() over_limit_runs_query = model.Run.submit_time > ( datetime.datetime.utcnow() - datetime.timedelta(minutes=5) ) run_count = ( model.Run.query.filter_by(user_id=curr_user.id) .filter(over_limit_runs_query) .count() ) matching_user = model.User.query.filter_by(username="******").scalar() current_user_id = 5 user = model.User.query.filter_by(id=util.i(current_user_id)).scalar() MAX_RUNS = util.get_configuration("max_user_submissions") TIME_LIMIT = util.get_configuration("user_submission_time_limit") over_limit_runs_query = model.Run.submit_time > ( datetime.datetime.utcnow() - datetime.timedelta(minutes=TIME_LIMIT) ) run_count = ( model.Run.query.filter_by(user_id=user.id).filter(over_limit_runs_query).count() ) contest = user.contests[0] lang_name = "python" problem_slug = "fizzbuzz" source_code = "asjdnsadjkasd" * 10000 is_submission = False user_test_input = "asdkamdlkamdklas" * 10000 lang = model.Language.query.filter_by(name=lang_name).one() problem = model.Problem.query.filter_by(slug=problem_slug).scalar() run_input = None run_output = None if is_submission: run_input = problem.secret_input run_output = problem.secret_output else: if user_test_input: run_input = user_test_input else: run_input = problem.sample_input run_output = problem.sample_output return "good"
def submit_run(): current_user_id = get_jwt_identity() user = model.User.query.get(util.i(current_user_id)) MAX_RUNS = util.get_configuration("max_user_submissions") TIME_LIMIT = util.get_configuration("user_submission_time_limit") over_limit_runs_query = model.Run.submit_time > ( datetime.datetime.utcnow() - datetime.timedelta(minutes=TIME_LIMIT) ) run_count = ( model.Run.query.filter_by(user_id=user.id).filter(over_limit_runs_query).count() ) if run_count > MAX_RUNS: return make_response(jsonify({"error": "Submission rate limit exceeded"}), 400) contest = user.contests[0] lang_name = request.json.get("lang", None) problem_slug = request.json.get("problem_slug", None) source_code = request.json.get("source_code", None) is_submission = request.json.get("is_submission", False) user_test_input = request.json.get("user_test_input", None) if lang_name is None or problem_slug is None or source_code is None: return make_response( jsonify({"error": "Invalid submission, missing input"}), 400 ) lang = model.Language.query.filter_by(name=lang_name).scalar() if not lang: return make_response(jsonify({"error": "Invalid language"}), 400) problem = model.Problem.query.filter_by(slug=problem_slug).scalar() if not problem: return make_response(jsonify({"error": "Invalid problem slug"}), 400) run_input = None correct_output = None if is_submission: run_input = problem.secret_input correct_output = problem.secret_output else: if user_test_input: run_input = user_test_input else: run_input = problem.sample_input correct_output = problem.sample_output run = model.Run( user, contest, lang, problem, datetime.datetime.utcnow(), source_code, run_input, correct_output, is_submission, local_submit_time=datetime.datetime.now(), ) run.state = model.RunState.JUDGING resp = None if datetime.datetime.utcnow() < contest.start_time: run.state = model.RunState.CONTEST_HAS_NOT_BEGUN run.started_execing_time = datetime.datetime.utcnow() run.finished_execing_time = datetime.datetime.utcnow() resp = make_response(jsonify({"error": "Contest has not begun"}), 400) else: resp = make_response(jsonify({"status": "good"}), 200) db_session.add(run) db_session.commit() util.invalidate_cache_item(util.RUN_CACHE_NAME, run.user_id) return resp