Beispiel #1
0
    def setPassword(self):
        """
        abilty to set password in managed / admin_user resolver
        """
        params = {}
        try:
            params.update(request.params)

            old_pw = params['old_password']
            new_pw = params['new_password']

            username = request_context['AuthUser'].get('login', '')

            if not username:
                raise Exception("Missing authenticated user!")

            sql_url = linotp.model.meta.engine.url

            # -------------------------------------------------------------- --

            # the set password handling:
            # any error will raise an excecption which will be displayed
            # to the user

            c.audit['administrator'] = username
            c.audit['info'] = 'setPassword'

            set_pw_handler = SetPasswordHandler(DataBaseContext(sql_url))

            set_pw_handler.set_password(username,
                                        old_password=old_pw,
                                        new_password=new_pw)

            c.audit['success'] = True

            return sendResult(
                response,
                obj=True,
                opt={'detail': ('password updated for %r' % username)})

        except Exception as exx:

            c.audit['success'] = False

            log.exception(exx)
            Session.rollback()
            return sendError(response, exx)

        finally:
            Session.close()
Beispiel #2
0
    def create_admin_user(self):
        """
        for testing we require the admin user to exist
        """

        sqlconnect = self.appconf.get('sqlalchemy.url')
        engine = create_engine(sqlconnect)

        db_context = DataBaseContext(engine.url)

        SetPasswordHandler.create_table(db_context)
        SetPasswordHandler.create_admin_user(
            db_context,
            username='******',
            crypted_password=libcrypt_password('nimda'))
Beispiel #3
0
    def create_admin_user(self):
        """
        for testing we require the admin user to exist
        """

        sqlconnect = self.app.config.get('SQLALCHEMY_DATABASE_URI')
        engine = create_engine(sqlconnect)

        db_context = DataBaseContext(engine.url)

        SetPasswordHandler.create_table(db_context)
        SetPasswordHandler.create_admin_user(
            db_context,
            username='******',
            crypted_password=utils.crypt_password('nimda'))
Beispiel #4
0
    def setPassword(self):
        """
        abilty to set password in managed / admin_user resolver
        """
        try:
            old_pw = self.request_params["old_password"]
            new_pw = self.request_params["new_password"]

            authenticated_user = getUserFromRequest()
            username = authenticated_user.login

            if not username:
                raise Exception("Missing authenticated user!")

            sql_url = db.engine.url

            # -------------------------------------------------------------- --

            # the set password handling:
            # any error will raise an excecption which will be displayed
            # to the user

            g.audit["administrator"] = username
            g.audit["info"] = "setPassword"

            set_pw_handler = SetPasswordHandler(DataBaseContext(sql_url))

            set_pw_handler.set_password(username,
                                        old_password=old_pw,
                                        new_password=new_pw)

            g.audit["success"] = True

            return sendResult(
                response,
                obj=True,
                opt={"detail": ("password updated for %r" % username)},
            )

        except Exception as exx:

            g.audit["success"] = False

            log.error(exx)
            db.session.rollback()
            return sendError(response, exx)
Beispiel #5
0
def db_context(app):
    return DataBaseContext("")  # no URI needed
Beispiel #6
0
def setup_app(conf, conf_global=None, unitTest=False):
    '''
    setup_app is the hook, which is called, when the application is created

    :param conf: the application configuration

    :return: - nothing -
    '''

    if unitTest is True:
        log.debug("Deleting previous tables...")
        meta.metadata.drop_all(bind=meta.engine)

    # Create the tables if they don't already exist
    log.info("Creating tables...")
    meta.metadata.create_all(bind=meta.engine)

    # ---------------------------------------------------------------------- --

    # for the cloud mode we require the admin_user table to
    # manage the admin users to allow password setting

    if 'linotpadmin.username' in conf and 'linotpadmin.password' in conf:

        from linotp.lib.tools.set_password import SetPasswordHandler
        from linotp.lib.tools.set_password import DataBaseContext

        db_context = DataBaseContext(sql_url=meta.engine.url)

        SetPasswordHandler.create_table(db_context)

        # create the initial admin
        admin_user = conf.get('linotpadmin.username', '')
        admin_pw = conf.get('linotpadmin.password', '')

        if admin_user and admin_pw:
            SetPasswordHandler.create_admin_user(db_context,
                                                 username=admin_user,
                                                 crypted_password=admin_pw)

    # ---------------------------------------------------------------------- --

    #
    # hook for schema upgrade -
    # - called by paster setup-app or on the first request to linotp
    #

    # define the most recent target version
    sql_data_model_version = "2.9.1.0"

    # get the actual version - should be None or should be the same
    # if migration is finished
    current_data_model_version = get_config('sql_data_model_version')

    #
    # in case of unitTest the database has been erased and recreated - thus
    # the db model update is not require - so we have already the most recent
    # target version

    if unitTest:
        current_data_model_version = sql_data_model_version
        set_config('sql_data_model_version',
                   sql_data_model_version,
                   typ='text')

    if current_data_model_version != sql_data_model_version:
        run_data_model_migration(meta, target_version=sql_data_model_version)
        set_config('sql_data_model_version',
                   sql_data_model_version,
                   typ='text')

    #
    # create the secret key file if it does not exist
    #

    if "linotpSecretFile" in conf:
        filename = conf.get("linotpSecretFile")
        try:
            open(filename)
        except IOError:
            log.warning(
                "The Linotp Secret File could not be found. " +
                "Creating a new one at %s", filename)
            f_handle = open(filename, 'ab+')
            secret = os.urandom(32 * 5)
            f_handle.write(secret)
            f_handle.close()
            os.chmod(filename, 0400)
        log.debug("linotpSecretFile: %s", filename)

    set_defaults()

    Session.commit()

    init_logging_config()

    log.info("Successfully set up.")
Beispiel #7
0
def init_db_tables(app, drop_data=False, add_defaults=True):
    """Initialise LinOTP database tables.

    This function initialises the LinOTP tables given an empty database
    (it also works if the database isn't empty).

    :param drop_data: If `True`, all data will be cleared. Use with caution!
    :param add_defaults: Adds default configuration variables if `True`.
       Don't set this to `False` unless you know what you are doing.
    """

    # Use `app.echo()` if available, otherwise standard logging.
    echo = getattr(
        app,
        "echo",
        lambda msg, v=0: log.log(logging.INFO if v else logging.ERROR, msg),
    )

    echo("Setting up database...", v=1)

    try:
        if app.config["AUDIT_DATABASE_URI"] != "OFF":
            # The audit table is created in the configured audit database
            # connection if audit is not turned off. The database model is
            # added to SQLAlchemy if the file is imported.
            import linotp.lib.audit.SQLAudit

        if drop_data:
            echo("Dropping tables to erase all data...", v=1)
            db.drop_all()

        echo(f"Creating tables...", v=1)
        db.create_all()

        run_data_model_migration(db.engine)
        if add_defaults:
            set_defaults(app)

        # For the cloud mode, we require the `admin_user` table to
        # manage the admin users to allow password setting

        admin_username = app.config["ADMIN_USERNAME"]
        admin_password = app.config["ADMIN_PASSWORD"]

        if admin_username and admin_password:
            echo("Setting up cloud admin user...", v=1)
            from linotp.lib.tools.set_password import (
                DataBaseContext,
                SetPasswordHandler,
            )

            db_context = DataBaseContext(sql_url=db.engine.url)
            SetPasswordHandler.create_table(db_context)
            SetPasswordHandler.create_admin_user(
                db_context,
                username=admin_username,
                crypted_password=admin_password,
            )

    except Exception as exx:
        echo(f"Exception occured during database setup: {exx!r}")
        db.session.rollback()
        raise exx

    db.session.commit()
Beispiel #8
0
    def setUp(self):

        unittest.TestCase.setUp(self)

        self.db_context = DataBaseContext('sqlite:///:memory:')