def create_user():
    data = json.loads(request.data)
    if len(g.db.get_specific_user(data['id'])) != 0:
        return create_error_response("Exists",  "A user with the id '{}' already exists".format(data['id']))
    if data['role'] in ('administrator', 'organizer', 'attacker'):
        g.db.create_user(data['id'], hash_password(data['password']), data['email'], data['role'])
        resp = redirect(url_for(".get_user", user_id=data['id']), code=201)
        return resp
    elif data['role'] == 'team':
        if 'team' not in data:
            return create_error_response('IllegalParameter', 'Users with role "team" must have the "team" parameter.')
        else:
            g.db.create_user(data['id'], hash_password(data['password']), data['email'], data['role'], team=data['team'])
            resp = redirect(url_for(".get_user", user_id=data['id']), code=201)
            return resp
    else:
        return create_error_response('InvalidRole', 'Users can only have roles "administrator", "organizer", "attacker", or "team".')
def create_new_session():
    data = json.loads(request.data)
    data["password"] = hash_password(data["password"])
    if g.db.get_specific_user(data["username"], data["password"]) == []:
        return create_error_response("IncorrectLogin", "Either the user does not exist or password is incorrect.")
    try:
        login_user(User(data["username"]), remember=True)
    except BaseException, e:
        return create_error_response(type(e).__name__, e.message)
def create_app(_config_dir=None, _config_filename='settings.cfg', _configspec_filename='configspec.cfg'):
    # Create Flask app
    global app
    app = Flask("CheshireCat")

    if _config_dir is not None:
        default_config_dirs.insert(0, _config_dir)

    configspec_path = get_first_file_that_exists(default_config_dirs, _configspec_filename)
    config_path = get_first_file_that_exists(default_config_dirs, _config_filename)

    if configspec_path is None:
        raise FileNotFound('configspec', default_config_dirs, _configspec_filename)
    if config_path is None:
        raise FileNotFound('config', default_config_dirs, _config_filename)

    # Load configuration file
    configspec = ConfigObj(configspec_path, list_values=False)
    config = ConfigObj(config_path, configspec=configspec)
    test = config.validate(Validator(), copy=True)
    for key in config['CORE']:
        app.config[key] = config['CORE'][key]

    # Change the session interface to be more secure and portalble than the default
    # which is provided by Werkzeug.
    # These break the engine currently. I don't know why.
    #app.session_interface = RedisSignedSessionInterface()
    #app.session_interface = ItsdangerousSessionInterface()

    # Flask-Login manages user sessions for us, but we need to set it up first, so
    # we'll do so here.
    global login_manager
    login_manager = LoginManager()
    login_manager.init_app(app)

    # Initialize our database
    dbconfig = config['CORE']['DATABASE']
    db = MongoDBWrapper(dbconfig['HOST'], int(dbconfig['PORT']), dbconfig['DB_NAME'])
    db.init_db()
    if len(db.get_all_users_with_role('administrator')) == 0:
        db.create_user('admin', hash_password('admin'), '*****@*****.**', 'administrator')

    # Initialize CheshireCat
    # Import the views, to apply the decorators which use the global app object.
    from . import views
def modify_current_user():
    user = current_user.get_id()
    data = json.loads(request.data)
    data["password"] = hash_password(data["password"])
    g.db.modify_user(user, **data)
    return Response(status=204)