Example #1
0
def delete_team(tid):
    team = get_team(tid=tid).first()
    sheets = team.sheets
    with app.app_context():
        db.session.delete(team)
        db.session.commit()

    # Remove all sheets belonging to the now deleted team
    for sheet in sheets:
        with app.app_context():
            db.session.delete(sheet)
            db.session.commit()
Example #2
0
    def test_set_list_of_strings(self):
        """Test setting a list of string."""
        with current_app.app_context():
            config.set_("FOO", "['bar', 'biz']", self.cfg)

        with open(self._tmp) as f:
            self.assertRegexpMatches(f.read(), "FOO\s*=\s*\['bar',\s?'biz'\]")
Example #3
0
    def test_set_false(self):
        """Test setting a False value."""
        with current_app.app_context():
            config.set_("EGGS", "False", self.cfg)

        with open(self._tmp) as f:
            self.assertRegexpMatches(f.read(), "EGGS\s*=\s*False")
Example #4
0
def team_invite():
	params = utils.flat_multi(request.form)
	_user = user.get_user().first()
	_team = get_team(tid=_user.tid).first()
	if _user.uid != _team.owner:
		raise WebException("You must be the captain of your team to invite members!")
	if _team.finalized:
		raise WebException("This team is finalized.")

	new_member = params.get("new_member")
	if new_member is None:
		raise WebException("Please provide a username!")
	_user2 = user.get_user(username_lower=new_member.lower()).first()
	if _user2 is None:
		raise WebException("User doesn't exist!")
	if _user2.tid > 0:
		raise WebException("This user is already a part of a team!")

	if _team.get_pending_invitations(toid=_user2.uid) is not None:
		raise WebException("You've already invited this member!")

	req = TeamInvitations(0, _team.tid, _user2.uid)
	with app.app_context():
		db.session.add(req)
		db.session.commit()
		db.session.close()

	return { "success": 1, "message": "Success!" }
Example #5
0
    def test_set_explicit_unicode(self):
        """Test setting an explicit unicode string (u + quotes)."""
        with current_app.app_context():
            config.set_("URL", u"u'http://тест.укр/'", self.cfg)

        with open(self._tmp) as f:
            self.assertRegexpMatches(f.read(), u"URL\s*=\s*u'http://\\\\u")
Example #6
0
def drop_db():
  """
  Drop the DB.
  """
  # TODO: ask for confirmation.
  with app.app_context():
    db.drop_all()
Example #7
0
    def test_set_true(self):
        """Test setting a True value."""
        with current_app.app_context():
            config.set_("SPAM", "True", self.cfg)

        with open(self._tmp) as f:
            self.assertRegexpMatches(f.read(), "SPAM\s*=\s*True")
Example #8
0
    def test_journal_detail_menu_with_one_issue(self):
        """
        Teste para verificar se os botões estão ``anterior``, ``atual``,
        ``próximo`` estão disponíveis no ``jorunal/detail.html`` quando o periódico
        tem um fascículo o botão ``próximo`` e ``anterior`` deve vir desabilitados.
        """
        journal = utils.makeOneJournal()

        with current_app.app_context():
            # Criando uma coleção para termos o objeto ``g`` na interface
            collection = utils.makeOneCollection()

            issue = utils.makeOneIssue({'journal': journal,
                                        'year': '2016', 'volume': '1',
                                        'number': '1', 'order': '1', })

            response = self.client.get(url_for('main.journal_detail',
                                       url_seg=journal.url_segment))

            self.assertStatus(response, 200)
            self.assertTemplateUsed('journal/detail.html')
            expect_btn_anterior = '<a href="/journal_acron//" class="btn group  disabled ">\n          &laquo; número anterior\n        </a>'

            expect_btn_atual = '<a href="%s" class="btn group  ">\n          número atual\n        </a>' % url_for('.issue_toc', url_seg=journal.url_segment, url_seg_issue=issue.url_segment)

            expect_btn_proximo = '<a href="" class="btn group  disabled ">\n          número seguinte &raquo;\n        </a>'

            expected_btns = [expect_btn_anterior, expect_btn_atual, expect_btn_proximo]

            # Verificar se todos os btns do menu estão presentes no HTML da resposta
            response_data = response.data.decode('utf-8')
            for btn in expected_btns:
                self.assertIn(btn, response_data)
Example #9
0
def import_problem(path, pid):
	with app.app_context():
		existing_problem = Problems.query.filter_by(pid=pid).first()
		if existing_problem is not None:
			db.session.delete(existing_problem)
			db.session.commit()
		metadata = yaml.load(open(os.path.join(path, "problem.yml")))
		title = metadata.get("title")
		category = metadata.get("category")
		value = int(metadata.get("value"))
		hint = metadata.get("hint")
		description = open(os.path.join(path, "description.md")).read()
		grader = open(os.path.join(path, "grader.py")).read()

		if "files" in metadata:
			files = metadata["files"]
			files_dir = os.path.join(app.config["UPLOAD_FOLDER"], pid)
			if os.path.exists(files_dir):
				shutil.rmtree(files_dir)
			os.mkdir(files_dir)
			for file in files:
				src = os.path.join(path, file)
				if os.path.exists(src):
					shutil.copyfile(src, os.path.join(files_dir, file))

		try:
			problem.add_problem(title, category, description, value, grader, pid=pid, hint=hint)
		except Exception, e:
			logger.log(__name__, "Error when importing problem '%s': %s" % (pid, str(e)))
Example #10
0
 def __new__(self, path = None, data = None):
     with current_app.app_context():
         if isinstance(data, FileStorage):
             files    = { 'media': data }
             response = requests.post(current_app.config['THUMBOR_IMAGE_ENDPOINT'], files=files)
             path     = response.headers['location']
     return str.__new__(self, path)
Example #11
0
def setup_db():
    """
    Either initialize the database if none yet exists, or migrate as needed
    """

    from alembic.config import Config
    from alembic import command

    with current_app.app_context():
        # Alembic config used by migration or stamping
        alembic_cfg = Config(
            os.path.join(current_app.config["PROJECT_PATH"], "alembic.ini")
        )

        # Database connections
        g.db_session = create_db_session()
        con = g.db_session.connection()

        # Query list of existing tables
        tables = con.execute("show tables").fetchall()
        alembic_table = ('alembic_version',)
        if alembic_table in tables:
            # Latest version has been stamped or we have been upgrading
            logging.info("Database: Migrating")
            command.upgrade(alembic_cfg, "head")
        else:
            # The database needs to be initialized
            logging.info("Database: Initializing")
            init_db()
            command.stamp(alembic_cfg, "head")
Example #12
0
def init(start, end):
    """Initializes db with historical data"""
    with app.app_context():
        extra = {'models': models, 'end': end, 'start': start}
        kwargs = merge([app.config, extra])
        job = partial(swutils.populate, utils.gen_data, db.engine, **kwargs)
        utils.run_or_schedule(job, False, utils.exception_handler)
Example #13
0
    def test_journal_open_access_in_issue_toc(self):
        """
        Testa se os links e o conteúdo da licença este de acordo com a licença
        cadastrado no periódico.
        """

        with current_app.app_context():
            collection = utils.makeOneCollection()

            journal = utils.makeOneJournal()

            issue = utils.makeOneIssue({"journal": journal})

            with self.client as c:

                response = c.get(
                    url_for("main.issue_toc", url_seg=issue.journal.url_segment, url_seg_issue=issue.url_segment)
                )

                self.assertStatus(response, 200)

                self.assertTemplateUsed("issue/toc.html")

                self.assertIn(b"/static/img/oa_logo_32.png", response.data)
                self.assertIn('href="%s"' % url_for("main.about_collection"), response.data.decode("utf-8"))
                self.assertIn(b"Open Access", response.data)
Example #14
0
def run():
    """Populates db with most recent data"""
    limit = 0

    with app.app_context():
        f = urlopen(app.config['DATA_URL'])
        objects = items(f, app.config['DATA_LOCATION'])
        row_limit = app.config['ROW_LIMIT']
        chunk_size = min(row_limit or 'inf', app.config['CHUNK_SIZE'])
        debug = app.config['DEBUG']

        if app.config['TESTING']:
            createdb()

        for records in utils.chunk(objects, chunk_size):
            count = len(records)
            limit += count
            flattened = [dict(utils.flatten_fields(r)) for r in records]

            if debug:
                print('Inserting %s records into the database...' % count)
                # pprint(flattened)

            db.engine.execute(Data.__table__.insert(), flattened)

            if row_limit and limit >= row_limit:
                break

        if debug:
            print('Successfully inserted %s records into the database!' % limit)
Example #15
0
    def html(self, groups='all', template=None, **context):
        """Return an html string of the routes specified by the doc() method

        A template can be specified. A list of routes is available under the
        'autodoc' value (refer to the documentation for the generate() for a
        description of available values). If no template is specified, a
        default template is used.

        By specifying the group or groups arguments, only routes belonging to
        those groups will be returned.
        """
        if template:
            return render_template(template,
                                   autodoc=self.generate(groups=groups),
                                   **context)
        else:
            filename = os.path.join(
                os.path.dirname(__file__),
                'templates',
                'autodoc_default.html'
            )
            with open(filename) as file:
                content = file.read()
                with current_app.app_context():
                    return render_template_string(
                        content,
                        autodoc=self.generate(groups=groups),
                        **context)
Example #16
0
File: tasks.py Project: oii/ogre
def store_ebook(ebook_id, filename, file_hash, fmt, username):
    """
    Store an ebook in the datastore
    """
    with app.app_context():
        # initialise the DB connection in our fake app context
        setup_db_session(app)

        try:
            # create the datastore
            ds = DataStore(app.config, app.logger)

            # local path of uploaded file
            filepath = os.path.join(app.config['UPLOADED_EBOOKS_DEST'], os.path.basename(filename))

            # store the file into S3
            ds.store_ebook(ebook_id, file_hash, filepath, username)

        except S3DatastoreError as e:
            app.logger.error('Failed uploading {} with {}'.format(file_hash, e))

        finally:
            # always delete local files who share the same hash in their filename
            # (these are repeat uploads, uniquely named by Flask-Uploads)
            for fn in os.listdir(app.config['UPLOADED_EBOOKS_DEST']):
                if fn.startswith(file_hash):
                    os.remove(os.path.join(app.config['UPLOADED_EBOOKS_DEST'], fn))
def get_file_from_request(ext=None, folder=None, name='file'):
    """
    Get file from a request, save it locally and return its path
    """
    if ext is None:
        ext = []

    print("get_file_from_request() INVOKED. We have: request.files = %r" % request.files)

    if name not in request.files:
        raise NotFoundError(source='{}', detail='File not found')
    uploaded_file = request.files[name]
    if uploaded_file.filename == '':
        raise NotFoundError(source='{}', detail='File not found')
    if not _allowed_file(uploaded_file.filename, ext):
        raise NotFoundError(source='{}', detail='Invalid file type')

    if not folder:
        if 'UPLOAD_FOLDER' in app.config:
            folder = app.config['UPLOAD_FOLDER']
        else:
            folder = 'static/uploads/' + UPLOAD_PATHS['temp']['event'].format(uuid=uuid.uuid4())
    else:
        with app.app_context():
            folder = app.config['BASE_DIR'] + folder
    if not os.path.isdir(folder):
        os.makedirs(folder)

    filename = secure_filename(uploaded_file.filename)
    uploaded_file.save(os.path.join(folder, filename))
    return os.path.join(folder, filename)
Example #18
0
def create():
    """
    Creates and initializes the SQLite database from the schema file.
    """
    with current_app.app_context():
        connect()
        with current_app.open_resource(schema_name, mode="r") as f:
            g.sqlite_connection.cursor().executescript(f.read())

        add_user({
            "username": "******",
            "password_hash": generate_password_hash("password"),
            "email": "*****@*****.**",
            "permissions": "administrator"
        })
        add_user({
            "username": "******",
            "password_hash": generate_password_hash("password"),
            "email": "*****@*****.**",
            "permissions": "author"
        })
        add_category({"name": "Uncategorized"})
        add_post({
            "author": "author",
            "creation_date": str(datetime.now()).split(".")[0],
            "category": category_id("Uncategorized"),
            "title": "Test Post",
            "body": "<p>Your bones don't break, mine do. That's clear. Your cells react to bacteria and viruses differently than mine. You don't get sick, I do. That's also clear. But for some reason, you and I react the exact same way to water. We swallow it too fast, we choke. We get some in our lungs, we drown. However unreal it may seem, we are connected, you and I. We're on the same curve, just on opposite ends.</p><p>The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee.</p><p>The path of the righteous man is beset on all sides by the iniquities of the selfish and the tyranny of evil men. Blessed is he who, in the name of charity and good will, shepherds the weak through the valley of darkness, for he is truly his brother's keeper and the finder of lost children. And I will strike down upon thee with great vengeance and furious anger those who would attempt to poison and destroy My brothers. And you will know My name is the Lord when I lay My vengeance upon thee.</p>"
        })
        create_about("New Site", "This is a blank description.")
        create_site_avatar("/static/face.png")
        g.sqlite_connection.commit()
Example #19
0
File: tasks.py Project: oii/ogre
def image_upload(ebook_data):
    """
    Upload book image to S3
    """
    with app.app_context():
        # fetch remote image into temp directory
        with make_temp_directory() as tmpdir:
            try:
                res = urllib.urlretrieve(
                    ebook_data['meta']['amazon']['image_url'],
                    os.path.join(tmpdir, 'image_file')
                )
            except KeyError:
                app.logger.error('No image available: {}'.format(
                    ebook_data['meta']['amazon']['image_url']
                ))
            except Exception as e:
                app.logger.error('Failed retrieving image {}: {}'.format(
                    ebook_data['meta']['amazon']['image_url'], e
                ))
                return

            # generate new S3 filename
            filename = '{}-0.jpg'.format(ebook_data['ebook_id'])

            try:
                # upload to S3
                s3 = connect_s3(app.config)
                bucket = s3.get_bucket(app.config['STATIC_S3_BUCKET'])
                k = boto.s3.key.Key(bucket)
                k.key = filename
                k.set_contents_from_filename(res[0])
            except S3ResponseError as e:
                app.logger.error('Error uploading to S3: {}'.format(e))
                return
Example #20
0
def first_run():
    """
    Init the database and
    query the user for an administrator email/password.
    """
    init_db()

    email = None
    while not email:
        email_tmp = prompt("Administrator email")

        email_test = _DummyEmailField(email_tmp)
        email_validator = Email()
        try:
            email_validator(None, email_test)
        except ValidationError:
            print("Email is invalid")
        else:
            with current_app.app_context():
                if User.query.filter_by(email=email_tmp).first():
                    print("User already exists")
                else:
                    email = email_tmp

    password = None
    while not password:
        password = prompt_pass("Administrator Password")

    add_user(email, password, ("Admin",), True)

    print("Setup complete")
Example #21
0
def get_config(key):
    with app.app_context():
        value = app.config.get(key)
        if value:
            if value and value.isdigit():
                return int(value)
            elif value and isinstance(value, six.string_types):
                if value.lower() == 'true':
                    return True
                elif value.lower() == 'false':
                    return False
                else:
                    return value
    config = Config.query.filter_by(key=key).first()
    if config and config.value:
        value = config.value
        if value and value.isdigit():
            return int(value)
        elif value and isinstance(value, six.string_types):
            if value.lower() == 'true':
                return True
            elif value.lower() == 'false':
                return False
            else:
                return value
    else:
        set_config(key, None)
        return None
Example #22
0
def make_app(set_path=False, db_setup=True, testing=False):
    # If you are reading this code and wonder how to access the app:
    # >>> from flask import current_app as app
    # This only works while inside an application context but you really shouldn't have any
    # reason to access it outside this method without being inside an application context.
    # When set_path is enabled, SERVER_NAME and APPLICATION_ROOT are set according to BaseURL
    # so URLs can be generated without an app context, e.g. in the indico shell

    if _app_ctx_stack.top:
        Logger.get('flask').warn('make_app({}) called within app context, using existing app:\n{}'.format(
            set_path, '\n'.join(traceback.format_stack())))
        return _app_ctx_stack.top.app
    app = IndicoFlask('indico', static_folder=None, template_folder='web/templates')
    app.config['TESTING'] = testing
    fix_root_path(app)
    configure_app(app, set_path)
    setup_jinja(app)
    with app.app_context():
        setup_assets()

    if db_setup:
        configure_db(app)

    extend_url_map(app)
    add_handlers(app)
    add_blueprints(app)
    if app.config['INDICO_COMPAT_ROUTES']:
        add_compat_blueprints(app)
    if not app.config['TESTING']:
        add_plugin_blueprints(app)

    Logger.init_app(app)

    return app
Example #23
0
def update(pid=None):
    """ Updates the database

    Args:
        pid (str): Package id of the package to update.
    """
    kwargs = {k: parse(v) for k, v in request.args.to_dict().items()}
    sync = kwargs.pop('sync', False)
    whitelist = [
        'CHUNK_SIZE', 'ROW_LIMIT', 'ERR_LIMIT', 'MOCK_FREQ', 'TIMEOUT',
        'RESULT_TTL']

    with app.app_context():
        defaults = {
            k.lower(): v for k, v in app.config.items() if k in whitelist}

        opts = defaultdict(int, pid=pid, **defaults)
        opts.update(kwargs)
        base = 'http://%(HOST)s:%(PORT)s%(API_URL_PREFIX)s' % app.config
        endpoint = '%s/age' % base

        if sync:
            resp = {'result': utils.update(endpoint, **opts)}
        else:
            job = q.enqueue(utils.update, endpoint, **opts)
            result_url = '%s/result/%s/' % (base, job.id)

            resp = {
                'job_id': job.id,
                'job_status': job.get_status(),
                'result_url': result_url}

        return jsonify(**resp)
def get_file_from_request(ext=None, folder=None, name='file'):
    """
    Get file from a request, save it locally and return its path
    """
    if ext is None:
        ext = []

    print("get_file_from_request() INVOKED. We have: request.files = %r" % request.files)

    if name not in request.files:
        raise NotFoundError('File not found')
    uploaded_file = request.files[name]
    if uploaded_file.filename == '':
        raise NotFoundError('File not found')
    if not _allowed_file(uploaded_file.filename, ext):
        raise NotFoundError('Invalid file type')

    if not folder:
        folder = app.config['UPLOAD_FOLDER']
    else:
        with app.app_context():
            folder = app.config['BASE_DIR'] + folder

    filename = secure_filename(uploaded_file.filename)
    uploaded_file.save(os.path.join(folder, filename))
    return os.path.join(folder, filename)
Example #25
0
def link_picturename_for_node(node_id, picturename, **kw):
    """
    Link a picture for a node id.  Use this if the picture has already been added to the database.
    """
    with current_app.app_context():
        c = db.cursor()

        result = c.execute(fetch_query_string("select_picture_by_name.sql"), {
            'picturename':picturename
            })
        (result, col_names) = rowify(result, c.description)
        if result:
            picture = result[0].get('id')
        else:
            current_app.logger.warn('picture by name:"{0}" is not in database.'.format(filepath))
            return False

        c.execute(fetch_query_string("insert_node_picture.sql"),{
            'node_id': node_id,
            'picture': picture
            })

        db.commit()

        insert_query(name='select_picture_for_node.sql', node_id=node_id)

        db.commit()
Example #26
0
def team_delete():
	params = utils.flat_multi(request.form)
	if "tid" in params:
		tid = params.get("tid")
	else:
		tid = session.get("tid")

	username = session["username"]
	team = Teams.query.filter_by(tid=tid).first()
	usr = Users.query.filter_by(username=username).first()
	owner = team.owner
	if usr.uid == owner or usr.admin:
		with app.app_context():
			for member in Users.query.filter_by(tid=tid).all():
				member.tid = -1
				db.session.add(member)
			UserActivity.query.filter_by(tid=tid).delete()
			Solves.query.filter_by(tid=tid).delete()
			ProgrammingSubmissions.query.filter_by(tid=tid).delete()
			db.session.delete(team)
			db.session.commit()
			db.session.close()
			session.pop("tid")
		return { "success": 1, "message": "Success!" }
	else:
		raise WebException("Not authorized.")
Example #27
0
def team_remove_member():
	username = session.get("username")
	tid = session.get("tid")
	team = Teams.query.filter_by(tid=tid).first()
	usr = Users.query.filter_by(username=username).first()
	owner = team.owner
	if team.finalized:
		raise WebException("This team is finalized.")
	if usr.uid == owner or usr.admin:
		params = utils.flat_multi(request.form)
		to_remove = params.get("username")
		if to_remove is None:
			return { "success": 0, "message": "ur high" }
		user_to_remove = Users.query.filter_by(username_lower=to_remove.lower()).first()
		if user_to_remove is None:
			return { "success": 0, "message": "User not found." }
		if user_to_remove.tid != tid:
			return { "success": 0, "message": "This user is not on your team!" }
		with app.app_context():
			Users.query.filter_by(uid=user_to_remove.uid).update({ "tid": -1 })
			db.session.commit()
			db.session.close()
		return { "success": 1, "message": "Success!" }
	else:
		raise WebException("Not authorized.")
Example #28
0
def invites_incoming():
    """\
    Gets an invitation from a POST request, adds it to the db, and returns its
    ID.
    """
    incoming = request.form
    import pprint
    pprint.pprint(incoming)
    print('{} files'.format(len(request.files)))
    for file_value in request.files.values():
        print(file_value.filename)
        print(file_value.read())
        print()

    with current_app.app_context():
        try:
            profiles = {p.userid: p for p in db.session.query(Profile)}
            key = incoming['envelope[from]'].split('@')[0]
            owner = insert_or_create(profiles, key, lambda: profile(key))
            attendees = read_recipients(incoming, profiles)
            attendee_set = set(attendee.userid for attendee in attendees)
            subject = incoming['headers[Subject]']
            body = incoming['plain']
            meeting_time = parse_when(body)
            meeting_date = meeting_time.start_time
            duration = meeting_time.duration
            attendees += read_attendee(attendee_set, profiles, subject) \
                + read_attendee(attendee_set, profiles, body)
            if meeting_date < datetime.datetime.now(meeting_date.tzinfo):
                status = 1
            else:
                status = 0

            invitation = Invitation(
                subject=subject,
                body=body,
                status=status,
                meeting_date=meeting_date,
                duration=round(duration.total_seconds() / 60.0),
                owner=owner,
                attendees=attendees,
            )

            db.session.add(invitation)
            db.session.commit()
        except:
            db.session.rollback()
            db.session.add(ErrorReport(
                message='error creating invitation',
                route='calendar /invites/incoming/',
                stacktrace=traceback.format_exc(),
            ))
            db.session.commit()
            raise

        return json.jsonify(
            status=1,
            id=invitation.id,
            url=url_for('.invite', invite_id=invitation.id),
            )
Example #29
0
def team_accept_invite_request():
	params = utils.flat_multi(request.form)
	_user = user.get_user().first()
	if not user.in_team(_user):
		raise WebException("You must be in a team!")
	_team = get_team(tid=_user.tid).first()
	tid = _team.tid
	if _user.uid != _team.owner:
		raise WebException("You must be the captain of your team to rescind invitations!")
	if _team.finalized:
		raise WebException("This team is finalized.")

	if len(_team.get_members()) >= utils.get_config("team_size"):
		raise WebException("Your team is full.")

	uid = params.get("uid")
	_user2 = user.get_user(uid=uid).first()
	if user.in_team(_user2):
		raise WebException("This user is already in a team!")

	invitation = TeamInvitations.query.filter_by(rtype=1, frid=_user2.uid, toid=tid).first()
	if invitation is None:
		raise WebException("Invitation doesn't exist.")

	with app.app_context():
		_user2 = Users.query.filter_by(uid=_user2.uid).first()
		_user2.tid = tid
		db.session.delete(invitation)
		invitation2 = TeamInvitations.query.filter_by(rtype=0, frid=tid, toid=_user2.uid).first()
		if invitation2 is not None:
			db.session.delete(invitation2)
		db.session.commit()
		db.session.close()

	return { "success": 1, "message": "Success!" }
Example #30
0
def create_user():
    """
    Create a new user.
    """
    email = None
    while not email:
        email_tmp = prompt("Email")

        email_test = _DummyEmailField(email_tmp)
        email_validator = Email()
        try:
            email_validator(None, email_test)
        except ValidationError:
            print("Email is invalid")
        else:
            with current_app.app_context():
                if User.query.filter_by(email=email_tmp).first():
                    print("User already exists")
                else:
                    email = email_tmp

    password = None
    while not password:
        password = prompt_pass("Password")

    admin = prompt_bool("Administrator?")

    roles = ("Admin",) if admin else ()

    add_user(email, password, roles)

    print("User added")
Example #31
0
def send_async_email(app, msg):
    with app.app_context():
        mail.send(msg)
Example #32
0
"""

import logging

from flask import current_app

from cmdb.interface.route_utils import make_response, login_required
from cmdb.interface.blueprint import RootBlueprint
from cmdb.user_management import UserManager

try:
    from cmdb.utils.error import CMDBError
except ImportError:
    CMDBError = Exception

with current_app.app_context():
    user_manager: UserManager = current_app.user_manager

LOGGER = logging.getLogger(__name__)
right_blueprint = RootBlueprint('right_rest', __name__, url_prefix='/right')


@right_blueprint.route('/', methods=['GET'])
@login_required
def get_all_rights():
    right_list = user_manager.get_all_rights()
    resp = make_response(right_list)
    return resp


@right_blueprint.route('/tree', methods=['GET'])
Example #33
0
def override_template(template, html):
    with app.app_context():
        app.jinja_loader.overriden_templates[template] = html
Example #34
0
 def __call__(self, *args, **kwargs):
     with current_app.app_context():
         return TaskBase.__call__(self, *args, **kwargs)
Example #35
0
    def test_article_detail_menu_when_first_article(self):
        """
        Teste para verificar se os botões estão ``anterior``, ``atual``,
        ``próximo`` estão disponíveis no ``article/detail.html`` quando é o
        primeiro artigo. O botão anterior deve esta desativado.
        """

        journal = utils.makeOneJournal()

        with current_app.app_context():
            # Criando uma coleção para termos o objeto ``g`` na interface
            utils.makeOneCollection()

            issue = utils.makeOneIssue({
                'journal': journal,
                'year': '2016',
                'volume': '1',
                'number': '1',
                'order': '1'
            })

            article1 = utils.makeOneArticle({
                'issue': issue,
                'order': 1,
                'elocation': 'e1234562'
            })

            article2 = utils.makeOneArticle({
                'issue': issue,
                'order': 2,
                'elocation': 'e1234562'
            })

            utils.makeOneArticle({
                'issue': issue,
                'order': 3,
                'elocation': 'e1234562'
            })

            article_detail_url = url_for('main.article_detail',
                                         url_seg=journal.url_segment,
                                         url_seg_issue=issue.url_segment,
                                         url_seg_article=article1.url_segment)

            response = self.client.get(article_detail_url)

            self.assertStatus(response, 200)
            self.assertTemplateUsed('article/detail.html')

            expect_btn_anterior = '<a href="#" class="btn group disabled">'  # artigo anterior

            expect_btn_atual = '<a href="#" class="btn group disabled">'  # número atual

            expect_btn_proximo = '<a href="%s" class="btn group">' % url_for(
                '.article_detail',
                url_seg=journal.url_segment,
                url_seg_issue=issue.url_segment,
                url_seg_article=article2.url_segment)  # artigo seguinte

            expected_btns = [
                expect_btn_anterior, expect_btn_atual, expect_btn_proximo
            ]

            # Verificar se todos os btns do menu estão presentes no HTML da resposta
            for btn in expected_btns:
                self.assertIn(btn, response.data.decode('utf-8'))
Example #36
0
    def test_journal_detail_menu_access_issue_toc_oldest_issue(self):
        """
        Teste para verificar se os botões estão ``anterior``, ``atual``,
        ``próximo`` estão disponíveis no ``jorunal/detail.html``, quando acessamos
        o número mais antigo.
        """
        journal = utils.makeOneJournal()

        with current_app.app_context():
            # Criando uma coleção para termos o objeto ``g`` na interface
            utils.makeOneCollection()

            issue1 = utils.makeOneIssue({
                'journal': journal,
                'year': '2016',
                'volume': '1',
                'number': '1',
                'order': '1',
            })
            issue2 = utils.makeOneIssue({
                'journal': journal,
                'year': '2016',
                'volume': '1',
                'number': '2',
                'order': '2',
            })
            issue3 = utils.makeOneIssue({
                'journal': journal,
                'year': '2016',
                'volume': '1',
                'number': '3',
                'order': '3',
            })

            response = self.client.get(
                url_for('main.issue_toc',
                        url_seg=journal.url_segment,
                        url_seg_issue=issue1.url_segment))

            self.assertStatus(response, 200)
            self.assertTemplateUsed('issue/toc.html')

            expect_btn_anterior = '<a href="#" class="btn group disabled">'  # número anterior

            expect_btn_atual = '<a href="%s" class="btn group ">' % url_for(
                '.issue_toc',
                url_seg=journal.url_segment,
                url_seg_issue=issue3.url_segment)  # número atual

            expect_btn_proximo = '<a href="%s" class="btn group">' % url_for(
                '.issue_toc',
                url_seg=journal.url_segment,
                url_seg_issue=issue2.url_segment)  # número seguinte

            expected_btns = [
                expect_btn_anterior, expect_btn_atual, expect_btn_proximo
            ]

            # Verificar se todos os btns do menu estão presentes no HTML da resposta
            for btn in expected_btns:
                self.assertIn(btn, response.data.decode('utf-8'))
Example #37
0
    def test_links_in_hamburger_menu(self):
        """
        no menú de hamurger, verificamos os links que apontam a views do opac
        """
        with current_app.app_context():
            collection = utils.makeOneCollection({'name': 'dummy collection'})

            with self.client as c:

                response = c.get(url_for('main.index'))
                response_data = response.data.decode('utf-8')
                self.assertStatus(response, 200)
                expected_anchor1 = """<a href="%s">\n        <strong>%s</strong>""" % (
                    url_for('.index'), collection.name
                    or __('NOME DA COLEÇÃO!!'))
                self.assertIn(expected_anchor1, response_data)
                expected_anchor2 = """<li>\n            <a href="%s" class="tab_link">\n              %s\n            </a>\n          </li>""" % (
                    url_for('.collection_list') + '#alpha',
                    __('Lista alfabética de periódicos'))
                self.assertIn(expected_anchor2, response_data)
                expected_anchor3 = """<li>\n            <a href="%s" class="tab_link">\n              %s\n            </a>\n          </li>""" % (
                    url_for('.collection_list') + '#theme',
                    __('Lista temática de periódicos'))
                self.assertIn(expected_anchor3, response_data)
                # expected_anchor4 = """<li>\n            <a href="%s" class="tab_link">\n              %s\n            </a>\n          </li>""" % (url_for('.collection_list') + '#publisher', __('Lista de periódicos por editoras'))
                # self.assertIn(expected_anchor4, response_data)
                expected_anchor5 = """<li>\n            <a href="%s">\n              %s\n            </a>\n          </li>""" % (
                    current_app.config['URL_SEARCH'] +
                    "?q=*&lang=pt&filter[in][]=" +
                    current_app.config['OPAC_COLLECTION'], 'Busca')
                self.assertIn(expected_anchor5, response_data)
                expected_anchor6 = """<li>\n            <a target="_blank" href="%s/?collection=%s">\n              %s\n            </a>\n          </li>\n          <li>""" % (
                    current_app.config['METRICS_URL'],
                    current_app.config['OPAC_COLLECTION'], __('Métricas'))
                self.assertIn(expected_anchor6, response_data)
                expected_anchor7 = """<a href="%s" class="onlineSubmission">\n      <span class="glyphBtn infoMenu"></span>\n      %s %s\n    </a>""" % (
                    url_for('.about_collection'), __('Sobre o SciELO'),
                    collection.name)
                self.assertIn(expected_anchor7, response_data)
                expected_anchor8 = """<li>\n            <a href="/about/">\n              %s\n            </a>\n          </li>""" % __(
                    'Contatos')
                self.assertIn(expected_anchor8, response_data)
                expected_anchor9 = """<a href="#">\n        <strong>SciELO.org - %s</strong>\n      </a>""" % __(
                    'Rede SciELO')
                self.assertIn(expected_anchor9, response_data)
                # rede/scielo org
                expected_anchor10 = """<li>\n          <a target="_blank" href="%s">\n            %s\n          </a>\n        </li>""" % (
                    current_app.config['URL_SCIELO_ORG'],
                    __('Coleções nacionais e temáticas'))
                self.assertIn(expected_anchor10, response_data)
                expected_anchor11 = """<li>\n          <a target="_blank" href="%s/pt/periodicos/listar-por-ordem-alfabetica/">\n              %s\n          </a>\n        </li>""" % (
                    current_app.config['URL_SCIELO_ORG'],
                    __('Lista alfabética de periódicos'))
                self.assertIn(expected_anchor11, response_data)
                expected_anchor12 = """<li>\n          <a target="_blank" href="%s/pt/periodicos/listar-por-assunto/">\n              %s\n          </a>\n        </li>""" % (
                    current_app.config['URL_SCIELO_ORG'],
                    __('Lista de periódicos por assunto'))
                self.assertIn(expected_anchor12, response_data)
                expected_anchor13 = """<li>\n          <a target="_blank" href="%s">\n            %s\n          </a>\n        </li>""" % (
                    current_app.config['URL_SEARCH'], 'Busca')
                self.assertIn(expected_anchor13, response_data)
                expected_anchor14 = """<li>\n            <a target="_blank" href="%s/?collection=%s">\n              %s\n            </a>\n          </li>""" % (
                    current_app.config['METRICS_URL'],
                    current_app.config['OPAC_COLLECTION'], 'Métricas')
                self.assertIn(expected_anchor14, response_data)
                expected_anchor15 = """<li>\n          <a target="_blank" href="%s/pt/sobre-o-scielo/acesso-via-oai-e-rss/">\n              %s\n          </a>\n        </li>""" % (
                    current_app.config['URL_SCIELO_ORG'],
                    __('Acesso OAI e RSS'))
                self.assertIn(expected_anchor15, response_data)
                expected_anchor16 = """<li>\n          <a target="_blank" href="%s/pt/sobre-o-scielo/">\n              %s\n          </a>\n        </li>""" % (
                    current_app.config['URL_SCIELO_ORG'],
                    __('Sobre a Rede SciELO'))
                self.assertIn(expected_anchor16, response_data)
                expected_anchor17 = """<li>\n          <a target="_blank" href="%s/pt/sobre-o-scielo/contato/">\n            %s\n          </a>\n        </li>""" % (
                    current_app.config['URL_SCIELO_ORG'], __('Contatos'))
                self.assertIn(expected_anchor17, response_data)
Example #38
0
 def wrapper(*args, **kwargs):
     with current_app.app_context():
         token = args_get("token")
         if token != current_app.config[access_token]:
             abort(403)
     return fn(*args, **kwargs)
Example #39
0
def register():
    if not can_register():
        return redirect(url_for('auth.login'))
    if request.method == 'POST':
        errors = []
        name = request.form['name']
        email = request.form['email']
        password = request.form['password']

        name_len = len(name) == 0
        names = 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 = re.match(
            r"(^[a-zA-Z0-9_.+-]+@[a-zA-Z0-9-]+\.[a-zA-Z0-9-.]+$)",
            request.form['email'])

        if not valid_email:
            errors.append("That email doesn't look right")
        if names:
            errors.append('That username is already taken')
        if emails:
            errors.append('That email has already been used')
        if pass_short:
            errors.append('Pick a longer password')
        if pass_long:
            errors.append('Pick a shorter password')
        if name_len:
            errors.append('Pick a longer team name')

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

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

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

        db.session.close()

        logger = logging.getLogger('regs')
        logger.warn("[{0}] {1} registered with {2}".format(
            time.strftime("%m/%d/%Y %X"), request.form['name'].encode('utf-8'),
            request.form['email'].encode('utf-8')))
        if request.args.get('next') and is_safe_url(request.args.get('next')):
            return redirect(request.args.get('next'))
        return redirect(url_for('challenges.challenges_view'))
    else:
        return render_template('register.html')
Example #40
0
def setup():
    # with app.app_context():
    # admin = Teams.query.filter_by(admin=True).first()

    if not utils.is_setup():
        if not session.get('nonce'):
            session['nonce'] = utils.sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = utils.set_config('ctf_name', ctf_name)

            # CSS
            css = utils.set_config('start', '')

            # Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            # Index page
            page = Pages(
                'index',
                """<div class="container main-container index" id="index">
    <img class="logo" src="static/original/img/logo.png" />
    <h3 class="text-center">
        <p>A cool CTF platform from (tom)<a href="https://ctfd.io">ctfd.io</a></p>
        <p>Follow us on social media:</p>
        <a href="https://twitter.com/ctfdio"><i class="fa fa-twitter fa-2x" aria-hidden="true"></i></a>&nbsp;
        <a href="https://facebook.com/ctfdio"><i class="fa fa-facebook-official fa-2x" aria-hidden="true"></i></a>&nbsp;
        <a href="https://github.com/ctfd"><i class="fa 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>""".format(request.script_root))

            # max attempts per challenge
            max_tries = utils.set_config('max_tries', 0)

            # Start time
            start = utils.set_config('start', None)
            end = utils.set_config('end', None)
            freeze = utils.set_config('freeze', None)

            # Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = utils.set_config(
                'view_challenges_unregistered', None)

            # Allow/Disallow registration
            prevent_registration = utils.set_config('prevent_registration',
                                                    None)

            # Verify emails
            verify_emails = utils.set_config('verify_emails', None)

            mail_server = utils.set_config('mail_server', None)
            mail_port = utils.set_config('mail_port', None)
            mail_tls = utils.set_config('mail_tls', None)
            mail_ssl = utils.set_config('mail_ssl', None)
            mail_username = utils.set_config('mail_username', None)
            mail_password = utils.set_config('mail_password', None)

            setup = utils.set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()

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

            db.session.close()
            app.setup = False
            with app.app_context():
                cache.clear()

            return redirect(url_for('views.static_html'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect(url_for('views.static_html'))
Example #41
0
 def _image_url(self, url, **kwargs):
     with current_app.app_context():
         url = image_url(url, **kwargs)
         parsed = urlparse(url) if url else None
         qs = parse_qs(parsed.query) if parsed else None
         return url, parsed, qs
Example #42
0
def setup():
    if not config.is_setup():
        if not session.get('nonce'):
            session['nonce'] = generate_nonce()
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            set_config('ctf_name', ctf_name)

            # CSS
            set_config('start', '')

            # Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Admins(
                name=name,
                email=email,
                password=password,
                type='admin',
                hidden=True
            )

            user_mode = request.form['user_mode']

            set_config('user_mode', user_mode)

            # Index page

            index = """<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="themes/core/static/img/logo.png" />
        <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>""".format(request.script_root)

            page = Pages(
                title=None,
                route='index',
                content=index,
                draft=False
            )
            # Visibility
            set_config('challenge_visibility', 'private')
            set_config('registration_visibility', 'public')
            set_config('score_visibility', 'public')
            set_config('account_visibility', 'public')

            # Start time
            set_config('start', None)
            set_config('end', None)
            set_config('freeze', None)

            # 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)

            setup = 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()
            app.setup = False
            with app.app_context():
                cache.clear()

            return redirect(url_for('views.static_html'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect(url_for('views.static_html'))
Example #43
0
def remove_existing_role(body: dict) -> Tuple[dict, int]:
    if not current_user.is_authenticated:
        return create_error_response(
            403,
            'Resource does not exists or you are not allowed to access it!'
        ), 403

    if flask.session['current_title_id'] != app.config[
            'MY_AUTO_SUPERUSER_TITLE_ID']:
        log.info(message='#todo')
        return create_error_response(
            403,
            'Resource does not exists or you are not allowed to access it!'
        ), 403

    try:
        with app.app_context():
            found_existing_role = db.session.query(ExistingRole).filter_by(
                uid=body['uid']).first()
        if found_existing_role is None:
            return create_error_response(
                403, 'uid not found. Please enter valid uid.'), 403

        #delete ExistingRoleTranslation based on found_existing_role
        n_existing_role_translation = db.session.query(
            ExistingRoleTranslation).filter(
                ExistingRoleTranslation.existing_role_id ==
                found_existing_role.id).delete(synchronize_session=False)

        #delete allowed role for user
        n_allowed_role_for_user = db.session.query(AllowedRoleForUser).filter(
            AllowedRoleForUser.existing_role_id ==
            found_existing_role.id).delete(synchronize_session=False)

        #delete user based on existingRole
        n_allowed_role_for_user = db.session.query(User).filter(
            User.default_role_id == found_existing_role.id).delete(
                synchronize_session=False)

        #delete ExistingRole based on found_existing_role
        addresses = db.session.query(ExistingRole).filter(
            ExistingRole.id == found_existing_role.id).delete(
                synchronize_session=False)

        db.session.commit()
    except IntegrityError as ie:
        db.session.rollback()
        log.info(
            message=str(ie),
            error=
            "SQLAlchemy.IntegrityError (constraint violation found) or Database chnages found",
            action="will return 403 (403)")
        return create_error_response(403, "Internal Server Error"), 200
    except exc.SQLAlchemyError as e:
        db.session.rollback()
        log.info(message=str(e),
                 error="SQLAlchemyError or Database chnages found",
                 action="will return 403 (403)")
        return create_error_response(403, "Internal Server Error"), 200
    return {
        'code': 200,
        'message': 'Sucessfully remove existing role',
        "existing-roles-list":
        show_existing_roles(flask.session['current_locale'])
    }, 200
Example #44
0
def create_users():
    # print('\nusers.__init__.create_users')
    users_bp = Blueprint(
        'users_bp',
        __name__,
        static_folder='static',
        # static_url_path='/users',
        template_folder='templates')

    # CORS(users_bp)

    with current_app.app_context():

        # Custom error handler
        # from ..errors.register import register_error_handler
        # register_error_handler(users_bp)

        # flask_restful and routining
        from .modules.api_users import api_users
        api_users.init_app(users_bp)

        # flask_cors. Keep it in modules to have independed
        # Cross Origin Resource Sharing (CORS) handling
        from .modules.crs_users import crs_users
        crs_users.init_app(users_bp)

        # flask_sqlalchemy - whole application registered.
        # from application.modules.dbs_global import dbs_global
        # from .modules.dbs_users import dbs_users
        # dbs_global.init_app(current_app)

        # @current_app.before_first_request
        # def init_dbs():
        # pass
        #     from .modules.dbs_init_users import dbs_init_users
        #     dbs_init_users()

        # flask_marshmallow
        from .modules.fma_users import fma_users
        fma_users.init_app(users_bp)
        # fma_users.init_app(current_app)

        # flask_bcrypt
        # Anable to user blueprint couse:
        # AttributeError: 'Blueprint' object has no attribute 'config'
        from .modules.fbc_users import fbc_users
        # fbc_users.init_app(users_bp)
        fbc_users.init_app(current_app)

        # Flask-JWT-Extended
        # Anable to user blueprint couse:
        # AttributeError: 'Blueprint' object has no attribute 'config'
        from .modules.jwt_users import jwt_users
        # jwt_users.init_app(users_bp)
        jwt_users.init_app(current_app)

        # Data bases initiation (creation reference table values and
        # admin user if not created).
        # dbs_init()
        # @current_app.before_first_request
        # def init_dbs():
        #     dbs_init_users()

    return users_bp
Example #45
0
def import_event_json(task_handle, zip_path):
    """
    Imports and creates event from json zip
    """
    global CUR_ID, UPLOAD_QUEUE
    UPLOAD_QUEUE = []
    update_state(task_handle, 'Started')

    with app.app_context():
        path = app.config['BASE_DIR'] + '/static/uploads/import_event'
    # delete existing files
    if os.path.isdir(path):
        shutil.rmtree(path, ignore_errors=True)
    # extract files from zip
    with zipfile.ZipFile(zip_path, "r") as z:
        z.extractall(path)
    # create event
    try:
        update_state(task_handle, 'Importing event core')
        data = json.loads(open(path + '/event', 'r').read())
        _, data = _trim_id(data)
        srv = ('event', EventDAO)
        data = _delete_fields(srv, data)
        new_event = EventDAO.create(data, 'dont')[0]
        version_data = data.get('version', {})
        write_file(path + '/social_links',
                   json.dumps(data.get('social_links',
                                       [])))  # save social_links
        _upload_media_queue(srv, new_event)
    except BaseError as e:
        raise make_error('event', er=e)
    except Exception as e:
        raise make_error('event', er=e)
    # create other services
    try:
        service_ids = {}
        for item in IMPORT_SERIES:
            item[1].is_importing = True
            data = open(path + '/%s' % item[0], 'r').read()
            dic = json.loads(data)
            changed_ids = create_service_from_json(task_handle, dic, item,
                                                   new_event.id, service_ids)
            service_ids[item[0]] = changed_ids.copy()
            CUR_ID = None
            item[1].is_importing = False
    except BaseError as e:
        EventDAO.delete(new_event.id)
        raise make_error(item[0], er=e, id_=CUR_ID)
    except IOError:
        EventDAO.delete(new_event.id)
        raise NotFoundError('File %s missing in event zip' % item[0])
    except ValueError:
        EventDAO.delete(new_event.id)
        raise make_error(item[0], er=ServerError('Invalid json'))
    except Exception:
        print traceback.format_exc()
        EventDAO.delete(new_event.id)
        raise make_error(item[0], id_=CUR_ID)
    # run uploads
    _upload_media(task_handle, new_event.id, path)
    # set version
    VersionUpdater(False, new_event.id, '').set(version_data)
    # return
    return new_event
Example #46
0
def add_existing_role(body: dict) -> Tuple[dict, int]:
    if not current_user.is_authenticated:
        return create_error_response(
            403,
            'Resource does not exists or you are not allowed to access it!'
        ), 403
    if flask.session['current_title_id'] != app.config[
            'MY_AUTO_SUPERUSER_TITLE_ID']:
        log.info(message='#todo')
        return create_error_response(
            403,
            'Resource does not exists or you are not allowed to access it!'
        ), 403

    #validating json
    if not bool(body) or not len(body) == 3:
        return create_error_response(403,
                                     'You did not enter complete json'), 403

    if not checkKey(body, "translation"):
        return create_error_response(403, 'You did not enter translation'), 403

    if not checkKey(body, "title-uid"):
        return create_error_response(403, 'You did not enter title-uid'), 403

    if not checkKey(body, "organization-uid"):
        return create_error_response(
            403, 'You did not enter organization-uid.'), 403

    if not isinstance(body['title-uid'], str) or not re.match(
            r'^title\-(\S){4,}$', body['title-uid']):
        return create_error_response(
            403, 'title-uid should be string with ex. title-g2g2'), 200
    if not isinstance(body['organization-uid'], str) or not re.match(
            r'^org\-(\S){4}$', body['organization-uid']):
        return create_error_response(
            403, 'organization-uid should be string with ex. org-g2g2'), 200

    if not isinstance(body['translation'], list) or len(
            body['translation']) == 0:
        return create_error_response(
            403, 'translation should be list with length of more then 0'), 200

    unique_locale = []
    unique_description = []
    for r_dict in body['translation']:
        if not isinstance(r_dict, dict) or len(r_dict) != 2:
            return create_error_response(
                403,
                'inside translation should be multiple dict with each dict length is two'
            ), 200
        if not checkKey(r_dict, 'locale') or not isinstance(
                r_dict['locale'], str):
            return create_error_response(
                403, 'You did not enter: locale propery'), 200
        if not re.match(r'^[a-z][a-z]$', r_dict['locale']):
            return create_error_response(
                403, 'locale should be lower case with only two char'), 200
        if not checkKey(r_dict, 'description') or not isinstance(
                r_dict['description'], str):
            return create_error_response(
                403, 'You did not enter: short-name propery'), 200
        if len(r_dict['description'].strip()) <= 9:
            return create_error_response(
                403, 'description should be more then nine character'), 200

        #check for dublicate locale present in request body
        if not r_dict['locale'] in unique_locale:
            unique_locale.append(r_dict['locale'])
        else:
            return create_error_response(403,
                                         'Same locale in request body'), 200

        #check for dublicate description present in request body
        if not r_dict['description'] in unique_description:
            unique_description.append(r_dict['description'])
        else:
            return create_error_response(
                403, 'Same description in request body'), 200

    try:
        #check for existing title uid present or not
        with app.app_context():
            found_title = db.session.query(Title).filter_by(
                uid=body["title-uid"]).first()

        if found_title is None:
            return create_error_response(
                403, 'title-uid not found in database'), 200

        #check for organization uid present or not
        with app.app_context():
            found_organization = db.session.query(Organization).filter_by(
                uid=body["organization-uid"]).first()

        if found_organization is None:
            return create_error_response(
                403, 'organization-uid not found in database'), 200

        #check for existing role table like record is already present or not
        with app.app_context():
            found_existing_role = db.session.query(ExistingRole).filter_by(
                title_id=found_title.id,
                organization_id=found_organization.id).first()

        if not found_existing_role is None:
            return create_error_response(403,
                                         'record is already present.'), 200

        #insert into existing role table
        existing_role = ExistingRole(title_id=found_title.id,
                                     organization_id=found_organization.id)
        db.session.add(existing_role)
        db.session.flush()
        #insert into existing role translation
        for r_dict in body['translation']:
            existing_role_trans = ExistingRoleTranslation(
                existing_role_id=existing_role.id,
                locale=r_dict['locale'],
                description=r_dict['description'])
            db.session.add(existing_role_trans)

        db.session.commit()
    except IntegrityError as ie:
        db.session.rollback()
        log.info(
            message=str(ie),
            error=
            "SQLAlchemy.IntegrityError (constraint violation found) or Database chnages found",
            action="will return 403 (403)")
        return create_error_response(403, "Internal Server Error"), 200
    except exc.SQLAlchemyError as e:
        db.session.rollback()
        log.info(message=str(e),
                 error="SQLAlchemyError or Database chnages found",
                 action="will return 403 (403)")
        return create_error_response(403, "Internal Server Error"), 200
    return {
        'code': 200,
        'message': 'Sucessfully add existing role',
        "existing-roles-list":
        show_existing_roles(flask.session['current_locale'])
    }, 200
Example #47
0
def setup():
    """Removes all content from database and creates new tables"""

    with app.app_context():
        cleardb()
        createdb()
Example #48
0
def edit_existing_role(body: dict) -> Tuple[dict, int]:
    if not current_user.is_authenticated:
        return create_error_response(
            403,
            'Resource does not exists or you are not allowed to access it!'
        ), 403
    if flask.session['current_title_id'] != app.config[
            'MY_AUTO_SUPERUSER_TITLE_ID']:
        log.info(message='#todo')
        return create_error_response(
            403,
            'Resource does not exists or you are not allowed to access it!'
        ), 403

    #validating json
    if not bool(body):
        return create_error_response(403,
                                     'You did not enter complete json'), 403

    if not checkKey(body, "uid"):
        return create_error_response(403, 'You did not enter uid'), 403

    if not checkKey(body, "translation"):
        return create_error_response(403,
                                     'You did not enter translation key'), 403
    if not isinstance(body['translation'], list) or len(
            body['translation']) == 0:
        return create_error_response(
            403, 'translation should be list with length of more then 0'), 200
    unique_locale = []
    unique_description = []
    for r_dict in body['translation']:
        if not isinstance(r_dict, dict) or len(r_dict) != 2:
            return create_error_response(
                403,
                'inside translation should be multiple dict with each dict length is two'
            ), 200
        if not checkKey(r_dict, 'locale') or not isinstance(
                r_dict['locale'], str):
            return create_error_response(
                403, 'You did not enter: locale propery'), 200
        if not re.match(r'^[a-z][a-z]$', r_dict['locale']):
            return create_error_response(
                403, 'locale should be lower case with only two char'), 200
        if not checkKey(r_dict, 'description') or not isinstance(
                r_dict['description'], str):
            return create_error_response(
                403, 'You did not enter: description propery'), 200
        if len(r_dict['description'].strip()) <= 9:
            return create_error_response(
                403, 'description should be more then nine character'), 200
        #check for dublicate locale present in request body
        if not r_dict['locale'] in unique_locale:
            unique_locale.append(r_dict['locale'])
        else:
            return create_error_response(403,
                                         'Same locale in request body'), 200

        #check for dublicate description present in request body
        if not r_dict['description'] in unique_description:
            unique_description.append(r_dict['description'])
        else:
            return create_error_response(
                403, 'Same description in request body'), 200
    try:
        #check uid present in db or not
        with app.app_context():
            found_exist_role = db.session.query(ExistingRole).filter_by(
                uid=body["uid"]).first()

        if found_exist_role is None:
            return create_error_response(403, 'uid is not present in db'), 200

        #update or insert locale
        for r_dict in body['translation']:
            found_exist_role_trans = db.session.query(
                ExistingRoleTranslation).filter_by(
                    existing_role_id=found_exist_role.id,
                    locale=r_dict['locale']).first()
            if found_exist_role_trans == None:
                #existing_role translation not present in DB needs to insert
                newExistingRoleTrans = ExistingRoleTranslation(
                    existing_role_id=found_exist_role.id,
                    locale=r_dict['locale'],
                    description=r_dict['description'])
                db.session.add(newExistingRoleTrans)
            else:
                #existing_role translation is present in DB there needs to update
                addresses = db.session.query(ExistingRoleTranslation).filter(
                    ExistingRoleTranslation.id ==
                    found_exist_role_trans.id).update({
                        "locale":
                        r_dict['locale'],
                        "description":
                        r_dict['description']
                    })
        db.session.commit()
    except IntegrityError as ie:
        db.session.rollback()
        log.info(
            message=str(ie),
            error=
            "SQLAlchemy.IntegrityError (constraint violation found) or Database chnages found",
            action="will return 403 (403)")
        return create_error_response(403, "Internal Server Error"), 200
    except exc.SQLAlchemyError as e:
        db.session.rollback()
        log.info(message=str(e),
                 error="SQLAlchemyError or Database chnages found",
                 action="will return 403 (403)")
        return create_error_response(403, "Internal Server Error"), 200
    return {
        'code': 200,
        'message': 'Sucessfully edit existing role',
        "existing-roles-list":
        show_existing_roles(flask.session['current_locale'])
    }, 200
Example #49
0
def createdb():
    """Creates database if it doesn't already exist"""

    with app.app_context():
        db.create_all()
        print('Database created')
Example #50
0
def setup():
    # with app.app_context():
        # admin = Teams.query.filter_by(admin=True).first()

    if not is_setup():
        if not session.get('nonce'):
            session['nonce'] = sha512(os.urandom(10))
        if request.method == 'POST':
            ctf_name = request.form['ctf_name']
            ctf_name = set_config('ctf_name', ctf_name)

            ## CSS
            css = set_config('start', '')

            ## Admin user
            name = request.form['name']
            email = request.form['email']
            password = request.form['password']
            admin = Teams(name, email, password)
            admin.admin = True
            admin.banned = True

            ## Index page
            page = Pages('index', """<div class="container main-container">
    <img class="logo" src="{0}/static/original/img/logo.png" />
    <h3 class="text-center">
        Welcome to a cool CTF framework written by <a href="https://github.com/ColdHeat">Kevin Chung</a> of <a href="https://github.com/isislab">@isislab</a>
    </h3>

    <h4 class="text-center">
        <a href="{0}/admin">Click here</a> to login and setup your CTF
    </h4>
</div>""".format(request.script_root))

            #max attempts per challenge
            max_tries = set_config("max_tries",0)

            ## Start time
            start = set_config('start', None)
            end = set_config('end', None)

            ## Challenges cannot be viewed by unregistered users
            view_challenges_unregistered = set_config('view_challenges_unregistered', None)

            ## Allow/Disallow registration
            prevent_registration = set_config('prevent_registration', None)

            ## Verify emails
            verify_emails = set_config('verify_emails', None)

            mail_server = set_config('mail_server', None)
            mail_port = set_config('mail_port', None)
            mail_tls = set_config('mail_tls', None)
            mail_ssl = set_config('mail_ssl', None)
            mail_username = set_config('mail_username', None)
            mail_password = set_config('mail_password', None)

            setup = set_config('setup', True)

            db.session.add(page)
            db.session.add(admin)
            db.session.commit()
            db.session.close()
            app.setup = False
            with app.app_context():
                cache.clear()
            return redirect(url_for('views.static_html'))
        return render_template('setup.html', nonce=session.get('nonce'))
    return redirect(url_for('views.static_html'))
Example #51
0
def register():
    errors = get_errors()
    if request.method == "POST":
        name = request.form["name"]
        email_address = request.form["email"]
        password = request.form["password"]

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

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

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

                login_user(user)

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

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

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

        return redirect(url_for("challenges.listing"))
    else:
        return render_template("register.html", errors=errors)
Example #52
0
def cleardb():
    """Removes all content from database"""

    with app.app_context():
        db.drop_all()
        print('Database cleared')
Example #53
0
def async_calculating_earnings(parentid: int,
                               level: int,
                               earning_dict: dict,
                               task_id: int,
                               profit_percentage_arr: list,
                               type_set: int = 2):
    '''
        异步任务 计算该用户 所有上级 收益更新
        #type_set 收益来源:2:分销佣金 
        '''
    with current_app.app_context():
        res = dict()
        if earning_dict:
            fromuser = earning_dict['member_id']
            origin_money = earning_dict['amounts']
            logger.info(f'ORING收益:{origin_money}')
            logger.info(profit_percentage_arr)

            # get drpconfigs from cache
            drp_config = Redis.hgetall(redis_key_drp)
            per_set = drp_config[b'profit_percentage']
            per_set = str(per_set, encoding="utf-8")

            logger.info(f'分销比例all:{per_set}')
            per_set = json.loads(per_set)
            per_set = per_set[::-1]

            logger.info(f'reversed分销比例all:{per_set}')
            profit_percentage = per_set[level - 1]['per']
            logger.info(f'分销比例cur:{profit_percentage}')

            drp_money = origin_money * float(profit_percentage)
            logger.info(f'分销收益:{drp_money}')

            drp_earning_dict = {
                "member_id": parentid,
                "from_task_id": earning_dict['task_id'],
                "amounts": drp_money,
                "from_member_id": fromuser,
            }
            new_drp_earning = EtMemberDrp(**drp_earning_dict)
            db.session.add(new_drp_earning)
            logger.info(f'edt: {earning_dict}')

            user = db.session.query(EtMember).filter(
                EtMember.id == parentid).first()

            if user.status == 2:
                res.update(
                    dict(code=ResponseCode.Success,
                         data={},
                         msg=f'该用户已禁用,无法获得收益'))
                return res
            try:
                update_dict = {
                    "balance": drp_money * 100 + user.balance,
                    "balance_version": int(time.time())
                }

                db.session.query(EtMember).filter(
                    EtMember.id == parentid, EtMember.balance_version ==
                    user.balance_version).update(update_dict)

                db.session.commit()

                # update user cache
                Redis.delete(user_center_key + str(user.id))
                Redis.delete(user_info_key + str(user.mobile))
                Redis.delete(user_task_earnings_key + str(user.id))
                Redis.delete(user_appretice_detail_key + str(user.id))
                Redis.delete(user_apprentice_key + str(user.id))

                res.update(
                    dict(code=ResponseCode.Success,
                         data={},
                         msg=f'用户{fromuser}to{parentid}分销收益发放成功'))
                logger.info(res)
                return res
            except Exception as why:

                res.update(
                    dict(code=ResponseCode.Success,
                         data={},
                         msg=f'用户{fromuser}to{parentid}分销收益发放失败{why}'))
                logger.info(res)
                return res
Example #54
0
def admin_config():
    if request.method == "POST":
        start = None
        end = None
        if request.form.get('start'):
            start = int(request.form['start'])
        if request.form.get('end'):
            end = int(request.form['end'])

        try:
            view_challenges_unregistered = bool(
                request.form.get('view_challenges_unregistered', None))
            view_scoreboard_if_authed = bool(
                request.form.get('view_scoreboard_if_authed', None))
            prevent_registration = bool(
                request.form.get('prevent_registration', None))
            prevent_name_change = bool(
                request.form.get('prevent_name_change', None))
            view_after_ctf = bool(request.form.get('view_after_ctf', None))
            verify_emails = bool(request.form.get('verify_emails', None))
            mail_tls = bool(request.form.get('mail_tls', None))
            mail_ssl = bool(request.form.get('mail_ssl', None))
        except (ValueError, TypeError):
            view_challenges_unregistered = None
            view_scoreboard_if_authed = None
            prevent_registration = None
            prevent_name_change = None
            view_after_ctf = None
            verify_emails = None
            mail_tls = None
            mail_ssl = None
        finally:
            view_challenges_unregistered = set_config(
                'view_challenges_unregistered', view_challenges_unregistered)
            view_scoreboard_if_authed = set_config('view_scoreboard_if_authed',
                                                   view_scoreboard_if_authed)
            prevent_registration = set_config('prevent_registration',
                                              prevent_registration)
            prevent_name_change = set_config('prevent_name_change',
                                             prevent_name_change)
            view_after_ctf = set_config('view_after_ctf', view_after_ctf)
            verify_emails = set_config('verify_emails', verify_emails)
            mail_tls = set_config('mail_tls', mail_tls)
            mail_ssl = set_config('mail_ssl', mail_ssl)

        mail_server = set_config("mail_server",
                                 request.form.get('mail_server', None))
        mail_port = set_config("mail_port",
                               request.form.get('mail_port', None))

        mail_username = set_config("mail_username",
                                   request.form.get('mail_username', None))
        mail_password = set_config("mail_password",
                                   request.form.get('mail_password', None))

        ctf_name = set_config("ctf_name", request.form.get('ctf_name', None))
        ctf_theme = set_config("ctf_theme",
                               request.form.get('ctf_theme', None))

        mailfrom_addr = set_config("mailfrom_addr",
                                   request.form.get('mailfrom_addr', None))
        mg_base_url = set_config("mg_base_url",
                                 request.form.get('mg_base_url', None))
        mg_api_key = set_config("mg_api_key",
                                request.form.get('mg_api_key', None))

        max_tries = set_config("max_tries",
                               request.form.get('max_tries', None))

        db_start = Config.query.filter_by(key='start').first()
        db_start.value = start

        db_end = Config.query.filter_by(key='end').first()
        db_end.value = end

        db.session.add(db_start)
        db.session.add(db_end)

        db.session.commit()
        db.session.close()
        with app.app_context():
            cache.clear()
        return redirect(url_for('admin.admin_config'))

    with app.app_context():
        cache.clear()
    ctf_name = get_config('ctf_name')
    ctf_theme = get_config('ctf_theme')
    max_tries = get_config('max_tries')

    mail_server = get_config('mail_server')
    mail_port = get_config('mail_port')
    mail_username = get_config('mail_username')
    mail_password = get_config('mail_password')

    mailfrom_addr = get_config('mailfrom_addr')
    mg_api_key = get_config('mg_api_key')
    mg_base_url = get_config('mg_base_url')
    if not max_tries:
        set_config('max_tries', 0)
        max_tries = 0

    view_after_ctf = get_config('view_after_ctf')
    start = get_config('start')
    end = get_config('end')

    mail_tls = get_config('mail_tls')
    mail_ssl = get_config('mail_ssl')

    view_challenges_unregistered = get_config('view_challenges_unregistered')
    view_scoreboard_if_authed = get_config('view_scoreboard_if_authed')
    prevent_registration = get_config('prevent_registration')
    prevent_name_change = get_config('prevent_name_change')
    verify_emails = get_config('verify_emails')

    db.session.commit()
    db.session.close()

    themes = get_themes()
    themes.remove(ctf_theme)

    return render_template(
        'admin/config.html',
        ctf_name=ctf_name,
        ctf_theme_config=ctf_theme,
        start=start,
        end=end,
        max_tries=max_tries,
        mail_server=mail_server,
        mail_port=mail_port,
        mail_username=mail_username,
        mail_password=mail_password,
        mail_tls=mail_tls,
        mail_ssl=mail_ssl,
        view_challenges_unregistered=view_challenges_unregistered,
        view_scoreboard_if_authed=view_scoreboard_if_authed,
        prevent_registration=prevent_registration,
        mailfrom_addr=mailfrom_addr,
        mg_base_url=mg_base_url,
        mg_api_key=mg_api_key,
        prevent_name_change=prevent_name_change,
        verify_emails=verify_emails,
        view_after_ctf=view_after_ctf,
        themes=themes)
Example #55
0
def register():
    errors = get_errors()
    if request.method == "POST":
        name = request.form.get("name", "").strip()
        email_address = request.form.get("email", "").strip().lower()
        password = request.form.get("password", "").strip()

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

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

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

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

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

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

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

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

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

                login_user(user)

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

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

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

        return redirect(url_for("challenges.listing"))
    else:
        return render_template("register.html", errors=errors)
Example #56
0
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
            theme = request.form.get("ctf_theme", "core")
            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
            )

            # Index page

            index = """<div class="row">
    <div class="col-md-9 offset-md-2">
        <img class="w-100 mx-auto d-block" style="max-width: 500px;padding: 50px;padding-top: 14vh;" src="themes/core/static/img/xsutd-istd-logo-web-2021.png.pagespeed.ic.w1dqDYZAE-.webp">
        <h3 class="text-center">
            <p>A CTF platform for System Security course</p>
        </h3>
        <br>
        <h4 class="text-center">
            <a href="admin">Click here</a> to login and setup your CTF
        </h4>
    </div>
</div>"""

# """<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="themes/core/static/img/logo.png" />
#         <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 = Pages(title=None, route="index", content=index, draft=False)

            # 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"))
        return render_template("setup.html", state=serialize(generate_nonce()))
    return redirect(url_for("views.static_html"))
Example #57
0
 def __call__(self, app=None, *args, **kwargs):
     with app.app_context():
         return self.run(*args, **kwargs)
Example #58
0
def async_alipay_service(serial_number: int, alipay_account: str,
                         real_name: str, pay_amount: int, mid: int):
    """
    @req: req_data
    req_data = {'alipay_account': alipay, 'alipay_name': real_name,
                        'amount': amount, 'serial_number': serial_number}
    @resp: result_status, error_code

    :return:
    """
    with current_app.app_context():
        res = {}
        now_timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

        headers = {'content-type': 'application/json;charset=UTF-8'}
        req_data = {
            'alipay_account': alipay_account,
            'alipay_name': real_name,
            'amount': pay_amount,
            'serial_number': serial_number
        }

        req_data['secret_key'] = 'FA77E2804734C22F72B22D9B7EDB41A9'
        wd_record = db.session.query(EtMemberWithdrawal).filter(
            EtMemberWithdrawal.id == serial_number).first()

        if wd_record:
            if wd_record.pay_status == 3:
                res.update(
                    dict(code=ResponseCode.Success,
                         data={},
                         msg=f'该单已发放无法再次提现'))
                return res

        user = db.session.query(EtMember).filter(EtMember.id == mid).first()

        verify_orders = db.session.query(EtMemberWithdrawal).filter(
            EtMemberWithdrawal.id == serial_number,
            EtMemberWithdrawal.member_id == mid).first()

        if user.status == 2:

            drp_config = Redis.hgetall(redis_key_drp)
            handling_fee_s = drp_config[b'handling_fee']
            handling_fee = float(str(handling_fee_s, encoding="utf-8"))

            add_balance = 0
            if handling_fee == 0:
                add_balance = verify_orders.amounts
            else:
                handling_fee = (1 - float(handling_fee) / 100)
                add_balance = round(verify_orders.amounts / handling_fee, 2)

            if verify_orders.origin_amount:
                add_balance = verify_orders.origin_amount

            update_dict = {
                "balance": user.balance + add_balance * 100,
                "balance_version": int(time.time())
            }

            db.session.query(EtMember).filter(
                EtMember.id == mid, EtMember.balance_version ==
                user.balance_version).update(user_update_dict)
            update_dict = {
                "id": serial_number,
                "verify": 1,
                "pay_status": 4,
                "end_time": now_timestr,
                "verify_log": '账号已封禁,无法提现',
                "pay_log": '账号已封禁,无法提现',
            }
            update_dict_ready = helpers.rmnullkeys(update_dict)

            db.session.query(EtMemberWithdrawal).filter(
                EtMemberWithdrawal.id == serial_number).update(
                    update_dict_ready)
            try:
                db.session.commit()
                Redis.delete(user_center_key + str(user.id))
                Redis.delete(user_info_key + str(user.mobile))
                Redis.delete(user_withdraw_recode_key + str(user.id))

            except Exception as why:
                msg = f'支付失败,请稍后再试{why}'
                logging.info(str(why))
                return msg

            if user.status == 2:
                res.update(
                    dict(code=ResponseCode.Success,
                         data={},
                         msg=f'该用户已禁用,无法提现'))
                return res

            res.update(
                dict(code=ResponseCode.Success, data={}, msg=f'该用户余额已不足,无法提现'))
            return res

        try:

            resp = requests.post(
                'http://47.91.142.164/api/alipay/transfer',
                data=req_data,
            )

            resp_json = resp.json()

            if resp_json.get('code') == 0:
                resp_data = resp_json.get('data', {})
                result_status, error_code = resp_data.get(
                    'status'), resp_data.get('error_code')
            else:
                result_status, error_code = False, resp_json.get('msg', u'')

        except Exception as e:
            result_status, error_code = False, '网络错误' + str(e)
            logger.info(str(e))
            logger.info(result_status)

        if result_status:
            # update_db pay_status

            pay_status = 3
            update_dict = {
                "id": serial_number,
                "pay_status": pay_status,
                "end_time": now_timestr,
                "verify_log": '提现成功,已到账',
                "pay_log": '提现成功,已到账',
            }
            update_dict_ready = helpers.rmnullkeys(update_dict)

            db.session.query(EtMemberWithdrawal).filter(
                EtMemberWithdrawal.id == serial_number).update(
                    update_dict_ready)

            try:

                db.session.commit()
                # update user cache
                Redis.delete(user_center_key + str(user.id))
                Redis.delete(user_info_key + str(user.mobile))
                Redis.delete(user_withdraw_recode_key + str(user.id))

                #send balance 100 to a parent which is never get the balance from this member
                new_member_reward(from_user=user.id)

            except Exception as why:
                msg = f'修改失败,请稍后再试{why}'
                return msg

            # title = '提现成功'
            # content = '恭喜您提现审核通过成功提现 {0}元'.format('%.2f' % (pay_amount))
            # logger.info(result_status)

        else:
            remark = ''
            if error_code in [
                    '支付宝提现系统升级中!', 'INVALID_PARAMETER',
                    'PAYCARD_UNABLE_PAYMENT', 'PAYER_DATA_INCOMPLETE',
                    'PERMIT_CHECK_PERM_LIMITED', 'PAYER_STATUS_ERROR',
                    'PAYER_STATUS_ERROR', 'PAYER_DATA_INCOMPLETE',
                    'PAYMENT_INFO_INCONSISTENCY', 'CERT_MISS_TRANS_LIMIT',
                    'CERT_MISS_ACC_LIMIT', 'PAYEE_ACC_OCUPIED',
                    'MEMO_REQUIRED_IN_TRANSFER_ERROR',
                    'PERMIT_PAYER_LOWEST_FORBIDDEN', 'PERMIT_PAYER_FORBIDDEN',
                    'PERMIT_CHECK_PERM_IDENTITY_THEFT',
                    'REMARK_HAS_SENSITIVE_WORD', 'ACCOUNT_NOT_EXIST',
                    'PAYER_CERT_EXPIRED', 'SYNC_SECURITY_CHECK_FAILED',
                    'TRANSFER_ERROR'
            ]:
                remark = '支付宝提现系统升级中!请销后尝试'
            elif error_code in [
                    'PERM_AML_NOT_REALNAME_REV', 'PERM_AML_NOT_REALNAME_REV',
                    'PERMIT_NON_BANK_LIMIT_PAYEE'
            ]:
                remark = '请登录支付宝站内或手机客户端完善身份信息后,重试!'
            elif error_code in [
                    'PAYEE_NOT_EXIST', 'PERMIT_NON_BANK_LIMIT_PAYEE'
            ]:
                remark = '支付宝账号不存在!请检查之后重试'
            elif error_code == 'PAYEE_USER_INFO_ERROR':
                remark = '支付宝账号和姓名不匹配,请更换成实名信息支付宝账号!'
            elif error_code in [
                    '服务暂时不可用!', 'SYSTEM_ERROR', 'PAYER_BALANCE_NOT_ENOUGH'
            ]:
                remark = '服务暂时不可用'
            elif error_code == 'BLOCK_USER_FORBBIDEN_RECIEVE':
                remark = '账户异常被冻结,无法收款,请咨询支付宝客服95188'
            else:
                remark = '支付失败,请稍后再试' + str(error_code)

            now_timestr = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime())

            pay_status = 4

            update_dict = {
                "id": serial_number,
                "verify": 1,
                "pay_status": pay_status,
                "verify_log": str(remark),
                "pay_log": str(remark) + ':' + str(error_code),
                # "end_time": now_timestr
            }
            update_dict_ready = helpers.rmnullkeys(update_dict)

            db.session.query(EtMemberWithdrawal).filter(
                EtMemberWithdrawal.id == serial_number).update(
                    update_dict_ready)

            drp_config = Redis.hgetall(redis_key_drp)
            handling_fee_s = drp_config[b'handling_fee']
            handling_fee = float(str(handling_fee_s, encoding="utf-8"))
            logging.info('+提现失败金额:')
            logging.info(str(verify_orders.amounts))
            add_balance = 0
            if handling_fee == 0:
                add_balance = verify_orders.amounts
            else:
                handling_fee = (1 - float(handling_fee) / 100)
                add_balance = round(verify_orders.amounts / handling_fee, 2)

            if verify_orders.origin_amount:
                add_balance = verify_orders.origin_amount

            user_update_dict = {
                "balance": user.balance + add_balance * 100,
                "balance_version": int(time.time())
            }

            db.session.query(EtMember).filter(
                EtMember.id == mid, EtMember.balance_version ==
                user.balance_version).update(user_update_dict)

            try:
                db.session.commit()
                Redis.delete(user_center_key + str(user.id))
                Redis.delete(user_info_key + str(user.mobile))
                Redis.delete(user_withdraw_recode_key + str(user.id))

            except Exception as why:
                msg = f'支付失败,请稍后再试{why}'
                logging.info(str(why))
                return msg

            logging.info(error_code + remark)
            return error_code + remark
 def __init__(self):
     self.participant_id = 0
     with current_app.app_context():
         self.cur = conn.cursor()
Example #60
0
def register():
    errors = get_errors()
    if request.method == 'POST':
        name = request.form['name']
        email_address = request.form['email']
        password = request.form['password']

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

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

        domain_whitelist = get_config('domain_whitelist')

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

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

                login_user(user)

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

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