Beispiel #1
0
    def get_implementation(cls) -> "UserNameGen":
        """Returns an implementation of `UserNameGen`.

        If you want to load occupied usernames from AD or elsewhere, you can
        call `load_occupied_names` on the instance returned by this method.

        By default, no occupied names are loaded on the instance returned by
        this method. This can be used in the cases where we want to spare the
        overhead of retrieving all AD usernames, for instance.
        """
        implementation_class = UserNameGenMethod2  # this is the default

        get_class_name = load_setting(f"{cls._setting_prefix}.class")

        try:
            name = get_class_name()
            implementation_class = cls._lookup_class_by_name(name)
        except (ValueError, FileNotFoundError):
            # ValueError: "not in settings file and no default"
            # FileNotFoundError: could not find "settings.json"
            logger.warning(
                "could not read settings, defaulting to %r",
                implementation_class,
            )
        except NameError:
            logger.warning(
                "could not find class %r, defaulting to %r",
                name,
                implementation_class,
            )

        instance = implementation_class()
        return instance
Beispiel #2
0
def cli(ctx,
        rundb_path: Optional[str] = None,
        rundb_variable: Optional[str] = None):
    rundb: str = ""
    if rundb_path:
        rundb = cast(str, rundb_path)
    elif rundb_variable:
        rundb = load_setting(rundb_variable)()
    else:
        raise click.ClickException(
            "Must provide either rundb-path or rundb-variable")

    ctx.ensure_object(dict)
    ctx.obj["dboverview"] = DBOverview(rundb)
Beispiel #3
0
    def load_occupied_names(self):
        # Always load AD usernames when this method is called
        self.add_occupied_names(UserNameSetInAD())

        # Load any extra username sets specified in settings
        setting_name = f"{self._setting_prefix}.extra_occupied_name_classes"
        get_usernameset_class_names = load_setting(setting_name, default=[])
        try:
            usernameset_class_names = get_usernameset_class_names()
        except FileNotFoundError:  # could not find "settings.json"
            logger.info("could not read settings, not adding extra username sets")
        else:
            for name in usernameset_class_names:
                try:
                    cls = self._lookup_class_by_name(name)
                except NameError:
                    raise ImproperlyConfigured(
                        f"{setting_name!r} refers to unknown class {name!r}"
                    )
                else:
                    username_set = cls()
                    self.add_occupied_names(username_set)
                    logger.debug("added %r to set of occupied names", username_set)
Beispiel #4
0
        level=LOG_LEVEL,
        filename=LOG_FILE,
    )


@cli.command()
@click.option(
    "--org-only",
    is_flag=True,
    default=False,
    type=click.BOOL,
    help="Only import organisation structure",
)
@click.option(
    "--mora-base",
    default=load_setting("mora.base", "http://localhost:5000"),
    help="URL for OS2mo.",
)
@click.option(
    "--mox-base",
    default=load_setting("mox.base", "http://localhost:8080"),
    help="URL for LoRa.",
)
def full_import(org_only: bool, mora_base: str, mox_base: str):
    """Tool to do an initial full import."""
    # Check connection to MO before we fire requests against SD
    mh = MoraHelper(mora_base)
    if not mh.check_connection():
        raise click.ClickException("No MO reply, aborting.")

    importer = ImportHelper(
Beispiel #5
0
        employees = list(employees)
        if units:
            return "organisationenhed", only(units)
        elif employees:
            return "bruger", only(employees)

    terminated_employees = list(terminated_employees)
    if terminated_employees:
        msg = "Employee was terminated, try --full-history"
    else:
        msg = f"No object with {opus_id=} was found."
    raise ValueError(msg)


@click.command()
@click.option("--mox-base", default=load_setting("mox.base"))
@click.option("--mora-base", default=load_setting("mora.base"))
@click.option("--delete", is_flag=True)
@click.option("--full-history", is_flag=True)
@click.option("--opus-id", type=int, required=True)
@click.option("--use-ad", is_flag=True, help="Read from AD")
@click.option("--dry-run", is_flag=True)
def cli(mox_base, mora_base, delete, full_history, opus_id, use_ad, dry_run):
    """Reimport object from opus with given opus-ID to MO
    Optionally deletes the object and all related orgfuncs directly from Lora.
    Defaults to reading latest file only, but supports reading full history
    """
    helper = MoraHelper(hostname=mora_base)
    object_type, obj = find_type(opus_id, full_history)
    if object_type == "bruger":
        cpr = opus_helpers.read_cpr(obj)
Beispiel #6
0
import click
from os2mo_helpers.mora_helpers import MoraHelper
from ra_utils.load_settings import load_setting


@click.command()
@click.option("--mora_base",
              default=load_setting("mora.base", "http://*****:*****@click.option("--bvn", required=True)
@click.option("--facet", required=True)
@click.option("--title")
@click.option("--uuid", type=click.UUID)
@click.option("--scope", default="TEXT")
def ensure_class_in_facet(mora_base, bvn, facet, title, uuid, scope):
    """Creates a class if it doesn't allready exist

    Example:
        metacli ensure_class_exists --bvn=Orlov --facet=leave_type

    Returns the uuid of the created/existing class.
    """
    helper = MoraHelper(hostname=mora_base, use_cache=False)
    title = title or bvn
    assert all(arg != ""
               for arg in (bvn, title, facet, scope)), "Inputs can't be empty"
    class_uuid = helper.ensure_class_in_facet(facet=facet,
                                              bvn=bvn,
                                              title=title,
                                              uuid=uuid,
                                              scope=scope)
    if uuid:
Beispiel #7
0
        payload = {
            "extUuid": employee["uuid"],
            "userId": sam_account_name,
            "name": get_employee_name(employee),
            "email": get_employee_email(employee_uuid, mh),
            "positions": positions,
        }
        converted_users.append(payload)

    return converted_users


@click.command()
@click.option(
    "--mora-base",
    default=load_setting("mora.base", "http://localhost:5000"),
    help="URL for OS2mo.",
)
@click.option(
    "--rollekatalog-url",
    default=load_setting("exporters.os2rollekatalog.rollekatalog.url"),
    help="URL for Rollekataloget.",
    required=True,
)
@click.option(
    "--rollekatalog-api-key",
    default=load_setting("exporters.os2rollekatalog.rollekatalog.api_token"),
    type=click.UUID,
    required=True,
    help="API key to write to Rollekataloget.",
)
Beispiel #8
0
            end_date=end_date,
            enddate_field=self.enddate_field,
            uuid_field=self.uuid_field,
            complete=self._ps_boiler_plate()["complete"],
            credentials=self._ps_boiler_plate()["credentials"],
        )
        return cmd

    def run(self, cmd):
        return self._run_ps_script("%s\n%s" % (self._build_user_credential(), cmd))


@click.command()
@click.option(
    "--enddate-field",
    default=load_setting("integrations.ad_writer.fixup_enddate_field"),
)
@click.option("--uuid-field", default=load_setting("integrations.ad.write.uuid_field"))
@click.option("--dry-run", is_flag=True)
def cli(enddate_field, uuid_field, dry_run):
    """Fix enddates of terminated users.
    AD-writer does not support writing enddate of a terminated employee,
    this script finds and corrects the enddate in AD of terminated engagements.
    """

    c = CompareEndDate(enddate_field, uuid_field)
    users = c.compare_mo()
    u = UpdateEndDate(enddate_field, uuid_field, c.cpr_field)
    users = u.get_changes(users)

    for uuid, end_date in tqdm(users, unit="user", desc="Changing enddate in AD"):
Beispiel #9
0
 def __init__(self):
     get_path = load_setting("integrations.ad_writer.user_names.disallowed.csv_path")
     with io.open(get_path(), "r", encoding=self._encoding) as stream:
         reader = csv.DictReader(stream)
         self._usernames = set(row[self._column_name] for row in reader)