Esempio n. 1
0
def admin_user_create():
    if not is_admin(session):
        abort(403)

    if request.method == "GET":
        return render_template("admin_create_user.html")
    else:
        try:
            username = request.form['username']
            password = request.form['password']
            make_admin = False
            try:
                make_admin = request.form['admin']
                make_admin = make_admin == "on"
            except KeyError:
                pass

            db_session = db.get_session()
            pwhash = pbkdf2_sha256.encrypt(password, rounds=200000, salt_size=16)
            user_obj = db.Users(username=username, password=pwhash, admin=make_admin)
            db_session.add(user_obj)
            db_session.commit()
            return redirect(url_for('.admin_user_detail', user=username))

        except KeyError:
            abort(400)
Esempio n. 2
0
def setup(**kw):
    """initialize the setup"""
    settings = AttributeMapper()
    settings['staticapp'] = get_static_urlparser(
        pkg_resources.resource_filename(__name__, 'static'))

    settings[
        'secret_key'] = "ccdhsiuccdhsiuhhci28228zs7s8c6c8976c89c7s6s8976cs87d6"  #os.urandom(20)
    settings['log'] = logbook.Logger("jmstvcamp")
    settings['dbname'] = "jmstvcamp"
    settings['shared_secret'] = "c6cs8cd67c8s76c9cs76ds98c76scds"
    settings['usercoll'] = "users"
    settings['maxpeople'] = 100
    settings['mailername'] = "real"
    settings.update(kw)

    settings.pts = Environment(loader=PackageLoader("jmstvcamp", "pages"))
    settings.email_templates = Environment(
        loader=PackageLoader("jmstvcamp", "email_templates"))

    settings.db = pymongo.Connection()[settings.dbname]
    settings.userdb = settings.db[settings.usercoll]
    settings.users = db.Users(settings)
    settings.maxpeople = int(settings.maxpeople)
    settings.mailer = emails.MAILERS[settings.mailername]()
    return settings
Esempio n. 3
0
def createNewUser(jsondata):
    session = Session()

    user = jsondata['username']
    email = jsondata['email']
    pw = jsondata['password']

    #first check if account with user unique
    if (session.query(exists().where(db.Users.email == email)).scalar()):
        return jsonify(
            '{"Message":"An account with this email already exists!"}')

    #then check to see if username is unique
    if (session.query(exists().where(db.Users.username == user)).scalar()):
        return jsonify(
            '{"Message":"An account with this username already exists!"}')

    #we can then prepare to create the account

    #first hash the password using bcrypt
    hashed = bcrypt.hashpw(pw.encode('utf8'), bcrypt.gensalt())

    new_user = db.Users(username=user, email=email, password=hashed)
    session.add(new_user)
    session.commit()

    return jsonify('{"Message":"Account created successfully!"}')
Esempio n. 4
0
def reset_and_fill_all_indices():
    all_orgs = [
        'explaain',
        'Matthew_Rusk_62352643',
        'yc',
        'Andrew_Davies_29862274',
        'financialtimes',
    ]
    all_index_names = [org.lower() + '__cards' for org in all_orgs] + [
        org.lower() + '__files' for org in all_orgs
    ] + ['organisations', 'sources', 'users']

    all_card_indices = [db.Cards(org) for org in all_orgs]
    all_file_indices = [db.Files(org) for org in all_orgs]
    # all_indices = all_card_indices + all_file_indices + [db.Organisations(), db.Sources(), db.Users()]
    all_indices = all_file_indices + [
        db.Organisations(), db.Sources(),
        db.Users()
    ]

    template_type = 'cards'
    template = templates.get_template(template_type)
    pp.pprint(
        es_client.IndicesClient(es).put_template(name=template_type,
                                                 body=template))
    # for org in all_orgs:
    #   index_name = org.lower() + '__cards'
    #   print(index_name)
    # print(json.dumps(es_client.IndicesClient(es).get_mapping(index=index_name, doc_type='card'), indent=2))
    # es_client.IndicesClient(es).close(index=index_name)
    # try:
    #   es_client.IndicesClient(es).put_mapping(index=index_name, doc_type='card', body=cards_template['mappings']['card'])
    #   es_client.IndicesClient(es).put_settings(index=index_name, body=cards_template['settings'])
    # except Exception as e:
    #   print(e)
    # es_client.IndicesClient(es).open(index=index_name)

    template_type = 'files'
    template = templates.get_template(template_type)
    pp.pprint(
        es_client.IndicesClient(es).put_template(name=template_type,
                                                 body=template))
    # for org in all_orgs:
    #   index_name = org.lower() + '__files'
    #   print(index_name)
    # es_client.IndicesClient(es).put_mapping(index=index_name, doc_type='file', body=files_template['mappings']['file'])

    # for index_name in all_index_names:
    #   print(index_name)
    #   if es_client.IndicesClient(es).exists(index=index_name):
    #     es_client.IndicesClient(es).delete(index=index_name)
    #   es_client.IndicesClient(es).create(index=index_name)
    for index in all_indices:
        copy_docs_from_algolia(index=index)
Esempio n. 5
0
def new_user():

	username = request.json.get('username')
	password = request.json.get('password')
	hash = pbkdf2_sha256.encrypt(password, rounds=200000, salt_size=16)
	print hash
	if username is None or password is None:
		abort(400) # missing arguments
	if db.session.query(db.Users).filter_by(username = username).first() is not None:
		abort(400) # existing user
	user = db.Users(username = username)
	user.password = hash
	db.session.begin()
	db.session.add(user)
	db.session.commit()

	return jsonify({ 'username': user.username }), 201
Esempio n. 6
0
def setup(**kw):
    """initialize the setup"""
    settings = starflyer.AttributeMapper()

    settings.log_name = "participate"
    settings.static_file_path = pkg_resources.resource_filename(
        __name__, 'static')
    settings.mongodb_name = "usermanager"
    settings.mongodb_port = 27017
    settings.mongodb_host = "localhost"

    # cookie related
    # TODO: add expiration dates, domains etc. maybe make it a dict?
    settings.cookie_secret = "czcds7z878cdsgsdhcdjsbhccscsc87csds76876ds"
    settings.session_cookie_name = "s"
    settings.message_cookie_name = "m"

    ####################################################################
    settings.update(kw)
    ####################################################################

    settings.db = pymongo.Connection(
        settings.mongodb_host, settings.mongodb_port)[settings.mongodb_name]
    settings.db_users = db.Users(settings.db.users)
    settings.log = Logger(settings.log_name)

    settings.templates = Environment(loader=PrefixLoader(
        {
            "framework": PackageLoader("starflyer", "templates"),
            "master": PackageLoader("usermanager", "templates"),
        }))

    # read text constants
    #
    fp = pkg_resources.resource_stream(__name__, 'text.ini')
    settings.texts = yaml.load(fp)

    return settings
Esempio n. 7
0
def index():
    db_session = db.get_session()
    admins = db_session.query(db.Users).filter_by(admin=True).all()
    if not admins:  # Check if no admin exists
        # If there is no admin we need to do an initial setup now, and create one
        if request.method == "GET":
            return render_template("initial_setup.html")
        else:
            try:
                username = request.form['setup_username']
                password1 = request.form['setup_password1']
                password2 = request.form['setup_password2']
            except KeyError:
                abort(400)
                raise
            # Create the initial admin
            if password1 != password2:
                return # TODO error out
            pwhash = pbkdf2_sha256.encrypt(password1, rounds=200000, salt_size=16)
            admin_obj = db.Users(username=username, password=pwhash, admin=True)
            db_session.add(admin_obj)
            db_session.commit()
            return redirect(url_for('.index'))
    else:
        if request.method == "GET":
            wrongpw = False
            if request.args.get('pw') == "1":
                wrongpw = True

            try:
                registration_key = db_session.query(db.Config).filter_by(key="registration").one()
                registration_allowed = (registration_key.value == "True")
            except NoResultFound:
                registration_allowed = True  # Default to: Registration allowed

            return render_template(
                "index.html", wrongpw=wrongpw, logged_in=check_login(session),
                registration_allowed=registration_allowed
            )
        else:
            # Check password
            try:
                username = request.form['login_username']
                password = request.form['login_password']

                user = db_session.query(db.Users).filter_by(username=username).one()

                if pbkdf2_sha256.verify(password, user.password):
                    session["login"] = True
                    session["user"] = user.username
                    return redirect(url_for('.manage'))
                else:
                    return redirect(url_for('.index') + '?pw=1')
            except KeyError:
                try:
                    registration_key = db_session.query(db.Config).filter_by(key="registration").one()
                    registration_allowed = (registration_key.value == "True")
                except NoResultFound:
                    registration_allowed = True  # Default to: Registration allowed

                if not registration_allowed:  # Check if registration is not allowed
                    abort(400)
                    raise
                try:
                    # Registration logic
                    username = request.form['register_username']
                    password1 = request.form['register_password1']
                    password2 = request.form['register_password2']

                    if password1 != password2:
                        return  # TODO error out

                    pwhash = pbkdf2_sha256.encrypt(password1, rounds=200000, salt_size=16)
                    user_obj = db.Users(username=username, password=pwhash, admin=False)
                    db_session.add(user_obj)
                    db_session.commit()
                    session["login"] = True
                    session["user"] = user_obj.username
                    return redirect(url_for('.manage'))

                except KeyError:
                    abort(400)
                    raise
Esempio n. 8
0
def send_post(message):
    for user in db.Users():
        try:
            bot.forward_message(user.user_id, message.chat.id, message.message_id)
        except:
            bot.send_message(message.chat.id, f"Не удалось отправить пост пользователю @{user.user_name}")
Esempio n. 9
0
def start_handler(message):
    if not db.Users().exists(message.chat.id):
        db.Users().add(message.chat.id, message.from_user.username)
    bot.send_message(message.chat.id, "Выберите знак зодиака", reply_markup=keyboards.inline_horoscope)
    db.Users().update_interface_state(message.chat.id, 0)