コード例 #1
0
def ipa_connect(ipa_user, ipa_password, ipa_hostname):
    """
        Connect and login to FreeIPA system with a secured
        SSL connection.
    """
    client = Client(ipa_hostname, version='2.215')
    client.login(ipa_user, ipa_password)
    return client
コード例 #2
0
 def auth_user(self, username, password):
     try:
         conn = Client(current_app.config['IPA_HOST'])
         #conn.login(username, password)
         conn.login_kerberos()
         return True
     except freeipa.exceptions:
         return
コード例 #3
0
def add_user(user_name, first_name, last_name):
    print("Adding User into IPA")

    client = Client(IPA_SERVER_HOST, version='2.215')
    client.login(IPA_ADMIN_USER, IPA_ADMIN_PASSWORD)
    user = client.user_add(user_name, first_name, last_name,
                           "{} {}".format(first_name, last_name))
    print user
コード例 #4
0
 def get_user_info(self, username):
     try:
         conn = Client(current_app.config['IPA_HOST'])
         conn.login_kerberos()
         #query = ClientMeta(current_app.config['IPA_HOST'])
         info = conn.user_show(username)
         return info
     except freeipa.exceptions as e:
         raise IPAException(self.error(e.args))
コード例 #5
0
    def initialize(self):
        """Initialize a connection to the IPA server.

        :return: IPA connection object.
        """

        try:
            conn = Client(current_app.config['IPA_HOST'])
            conn.login(current_app.config['IPA_USERNAME'],
                       current_app.config['IPA_PASSWORD'])
            return conn
        except freeipa.exceptions as e:
            raise IPAException(self.error(e.args))
コード例 #6
0
def valid_login(username, password):
    '''
    Tries to login and checks if user is member of admin-group

    :param username: user trying to log in
    :param password: user trying to log in
    :return: True on valid credentials, false on faliure
    '''
    try:
        client = Client(_config['ipa']['server'],
                        verify_ssl=True,
                        version=_config['ipa']['version'])
        client.login(username, password)
        return True
    except Unauthorized:
        return False
コード例 #7
0
def login():
    form = LoginForm(request.form)
    if request.method == "POST" and form.validate():
        client = Client("ipa.freeside.co.uk", verify_ssl=False, version="2.215")
        try:
            uid = form.username.data
            client.login(uid, form.password.data)
            data = client.user_show(uid)
            login_user(UserSession(uid, data))
            flash("Logged in!")
            return redirect("/")
        except exceptions.Unauthorized:
            flash("Invalid username or password")
        except exceptions.NotFound:
            flash("User not in database.")
    return render_template("login.html", form=form)
コード例 #8
0
def isAdmin(username, password):
    '''
    Checks if user is member of admin-group.

    :param username: of the user to the checked
    :param password: of the user to the checked
    :return: True if admin, false otherwise
    '''
    try:
        client = Client(_config['ipa']['server'],
                        verify_ssl=True,
                        version=_config['ipa']['version'])
        client.login(username, password)
        var = client.group_find(_config['ipa']['admin_group'])
        return username in json.dumps(var)

    except Unauthorized:
        return False
コード例 #9
0
def verify_user(uid):
    form = RegisterForm(request.form)
    user = User.query.filter_by(uuid=uid).first_or_404()

    if request.method == "POST" and form.validate():
        client = Client("ipa.freeside.co.uk",
                        verify_ssl=False,
                        version="2.215")
        client.login("admin", app.config["IPA_PASSWORD"])
        username = user.email.split("@")[0]
        firstname = form.first_name.data
        firstname = firstname.title()
        lastname = username.split(".")[-1].title()
        username = re.sub("[^a-zA-Z]+", "", username)
        username = username.lower()

        try:
            ipauser = client.user_add(
                username,
                firstname,
                lastname,
                form.first_name.data + " " + lastname,
                display_name=form.display_name.data,
                mail=user.email,
                preferred_language="EN",
                random_pass=True,
            )
        except exceptions.DuplicateEntry:
            flash("Account already exists.")
            return render_template("layout.html")
        print(ipauser["randompassword"])
        client.change_password(username, form.password.data,
                               ipauser["randompassword"])
        user.account_created = True
        db.session.commit()

        createHomeDir(username)

        msg = Message("Welcome to Freeside", recipients=[user.email])
        msg.html = render_template("emails/welcome.html",
                                   firstname=firstname,
                                   username=username)
        with app.app_context():
            mail.send(msg)
        flash("Account created! Your username is: " + username)
        return redirect(url_for("accounts.home"))
    else:
        if user.account_created is True:
            flash("Account already verified!")
            return redirect(url_for("accounts.home"))
        else:
            return render_template("complete_registration.html", form=form)
コード例 #10
0
ファイル: cli.py プロジェクト: ryanlerch/fas2ipa
def cli(skip_groups, only_members):
    config = toml.load(["config.toml.example", "config.toml"])
    for section, keys in INPUT_IF_EMTPY.items():
        for key in keys:
            if config[section][key]:
                continue
            is_password = key == "password"
            config[section][key] = click.prompt(f"Enter {key} for {section}",
                                                hide_input=is_password)
    config["skip_groups"] = skip_groups
    config["only_members"] = only_members

    fas = FASWrapper(config)
    click.echo("Logged into FAS")

    instances = []
    for instance in config["ipa"]["instances"]:
        ipa = Client(host=instance, verify_ssl=config["ipa"]["cert_path"])
        ipa.login(config["ipa"]["username"], config["ipa"]["password"])
        instances.append(ipa)
    click.echo("Logged into IPA")

    stats = defaultdict(lambda: 0)

    updated_stats = migrate_groups(config, fas, ipa)
    stats.update(updated_stats)

    alphabet = string.ascii_lowercase + string.digits

    for letter in alphabet:
        click.echo(f"finding users starting with {letter}")
        users = fas.send_request("/user/list",
                                 req_params={"search": letter + "*"},
                                 auth=True,
                                 timeout=240)
        updated_stats = migrate_users(config, users["people"], instances)
        stats.update(updated_stats)

    print_stats(stats)
コード例 #11
0
from database import db
from mail import mail

from app.accounts.models.user import UserSession

from app.accounts.views import accounts_blueprint
from app.oauth.views import oauth_blueprint

app = Flask(__name__)
app.config.from_object("config")
db.init_app(app)
mail.init_app(app)
migrate = Migrate(app, db)
login_manager = LoginManager(app)

bind = Client("ipa.freeside.co.uk", verify_ssl=False, version="2.215")


@app.login_manager.user_loader
def load_user(uid):
    try:
        bind.login("admin", app.config["IPA_PASSWORD"])
        data = bind.user_show(uid)
        user = UserSession(uid, data)
        return user
    except exceptions.NotFound:
        return None
    except exceptions.Unauthorized:
        return None

コード例 #12
0
import xmlrpc.client
from unidecode import unidecode
from python_freeipa import Client
from python_freeipa import exceptions
import datetime

weekago = (datetime.datetime.now() -
           datetime.timedelta(days=7)).strftime('%Y-%m-%d %H:%M:%S')

ourl = 'https://hostname'
domain = 'domain'
db = 'db'
username = '******'
password = '******'

client = Client('ipahost', version='2.230')
client.login('autoprovisioner', 'redacted')

common = xmlrpc.client.ServerProxy('https://{}/xmlrpc/2/common'.format(domain))
uid = common.authenticate(db, username, password, {})
models = xmlrpc.client.ServerProxy('{}/xmlrpc/2/object'.format(ourl))

circs = models.execute_kw(
    db, uid, password, 'o2.circuit', 'search_read',
    [[['write_date', '>', weekago]]], {
        'fields': [
            'write_date', 'write_uid', 'name', 'partner', 'site_b', 'status',
            'tech_attributes_id'
        ],
        'limit':
        0
コード例 #13
0
 def setUp(self):
     self.client = Client('ipa.demo1.freeipa.org', version='2.215')
     self.client._current_host='ipa.demo1.freeipa.org'
     self.url = 'https://ipa.demo1.freeipa.org/ipa/session/json'
     self.maxDiff = None
コード例 #14
0
ファイル: cli.py プロジェクト: markobrien1/fas2ipa
def cli(
    pull,
    push,
    check,
    dataset_file,
    conflicts_file,
    force_overwrite,
    skip_groups,
    skip_user_add,
    skip_user_membership,
    skip_user_signature,
    users_start_at,
    restrict_users,
    config_file,
):
    _orig_check = check

    if check is False:
        if conflicts_file:
            raise click.BadOptionUsage(
                option_name="--check",
                message="--no-check and --conflicts-file can't be combined",
            )
    elif check is True:
        if not (pull or push or conflicts_file or dataset_file):
            raise click.BadOptionUsage(
                option_name="--check",
                message=(
                    "--check without --pull or --push needs --conflicts-file or"
                    " --dataset-file"),
            )
    else:
        check = True

    if pull is None and push is None:
        if not check:
            raise click.BadOptionUsage(
                option_name=("--pull", "--push", "--check"),
                message="Neither pulling, pushing nor, checking. Bailing out.",
            )
        if _orig_check is None:
            pull = push = True
    elif False in (pull, push):
        pull = pull is not False
        push = push is not False
    elif True in (pull, push):
        push = bool(push)
        pull = bool(pull)

    if not dataset_file and pull != push:
        raise click.BadOptionUsage(
            option_name="--dataset-file",
            message=
            "Pulling without pushing or vice versa needs --dataset-file",
        )

    config = get_config(config_file)
    config["skip_groups"] = skip_groups
    config["skip_user_add"] = skip_user_add
    config["skip_user_membership"] = skip_user_membership
    config["skip_user_signature"] = skip_user_signature

    # If dataset or conlicts files should be written later, bail out before overwriting
    # an existing file (unless force_overwrite is set). This will be checked again later
    # to avoid race conditions.

    if dataset_file:
        dataset_file = pathlib.Path(dataset_file)

        if pull and dataset_file.exists() and not force_overwrite:
            raise click.ClickException(
                f"Refusing to overwrite '{dataset_file}', use --force-overwrite to override."
            )

    if conflicts_file:
        conflicts_file = pathlib.Path(conflicts_file)

        if check and dataset_file and conflicts_file.exists(
        ) and not force_overwrite:
            raise click.ClickException(
                f"Refusing to overwrite '{conflicts_file}', use --force-overwrite to override."
            )

    if dataset_file and not pull:
        dataset = load_data(dataset_file)
    else:
        dataset = {}
    dataset.setdefault("users", [])
    dataset.setdefault("groups", [])

    fas_instances = {}

    if pull:
        for inst_name, inst_conf in config["fas"].items():
            fas = FASWrapper(config, inst_conf)
            fas_instances[inst_name] = fas
            click.echo(f"Logged into FAS ({inst_name}): {inst_conf['url']}")

    if push:
        ipa_instances = []
        for instance in config["ipa"]["instances"]:
            ipa = Client(host=instance, verify_ssl=config["ipa"]["cert_path"])
            ipa.login(config["ipa"]["username"], config["ipa"]["password"])
            ipa_instances.append(ipa)
        click.echo("Logged into IPA")
    else:
        ipa_instances = None

    stats = Stats()

    agreements_mgr = Agreements(config, ipa_instances, fas_instances)
    users_mgr = Users(config,
                      ipa_instances,
                      fas_instances,
                      agreements=agreements_mgr)
    groups_mgr = Groups(config,
                        ipa_instances,
                        fas_instances,
                        agreements=agreements_mgr)

    if pull:
        if not skip_groups:
            dataset["groups"] = groups_mgr.pull_from_fas()

        dataset["users"] = users_mgr.pull_from_fas(
            users_start_at=users_start_at, restrict_users=restrict_users)

    conflicts = {}
    if check:
        if dataset_file:
            users_to_conflicts = users_mgr.find_user_conflicts(
                dataset["users"])
            groups_to_conflicts = groups_mgr.find_group_conflicts(
                dataset["groups"])

            conflicts = {}
            if users_to_conflicts:
                conflicts["users"] = users_to_conflicts
            if groups_to_conflicts:
                conflicts["groups"] = groups_to_conflicts

            if conflicts_file:
                save_data(conflicts,
                          conflicts_file,
                          force_overwrite=force_overwrite)
        elif conflicts_file and os.path.exists(conflicts_file):
            conflicts = load_data(conflicts_file)
        report_conflicts(conflicts)
    conflicts.setdefault("users", [])
    conflicts.setdefault("groups", [])

    if pull and dataset_file:
        save_data(munch.unmunchify(dataset),
                  dataset_file,
                  force_overwrite=force_overwrite)

    if push:
        if any(fas.get("agreement") for fas in config["fas"].values()):
            # Create agreements, relations to users and groups will be done later
            agreements_mgr.push_to_ipa()

        if not skip_groups:
            groups_stats = groups_mgr.push_to_ipa(dataset["groups"],
                                                  conflicts["groups"])
            stats.update(groups_stats)

        users_stats = users_mgr.push_to_ipa(dataset["users"], users_start_at,
                                            restrict_users, conflicts["users"])
        stats.update(users_stats)

    stats.print()
コード例 #15
0
ファイル: __init__.py プロジェクト: mfrancis95/self-service
# Create recaptcha object
recaptcha = ReCaptcha()
recaptcha.init_app(app)

# OIDC Initialization
auth = OIDCAuthentication(
    app,
    issuer=app.config["OIDC_ISSUER"],
    client_registration_info=app.config["OIDC_CLIENT_CONFIG"],
)

# Connect to LDAP
ldap = CSHLDAP(app.config["LDAP_BIND_DN"], app.config["LDAP_BIND_PW"])

# FreeIPA API Connection
ipa = Client("stone.csh.rit.edu", version="2.215")

# Configure rate limiting
if not app.config["DEBUG"]:
    limiter = Limiter(app,
                      key_func=get_remote_address,
                      default_limits=["50 per day", "10 per hour"])

# Initialize QR Code Generator
qr = QRcode(app)

# Import blueprints
# pylint: disable=wrong-import-position
from selfservice.blueprints.recovery import recovery_bp
from selfservice.blueprints.change import change_bp
from selfservice.blueprints.otp import otp_bp
コード例 #16
0
#!/usr/bin/env python

# Adds and removes 10 test user accounts on the FreeIPA demo server
# Uses Python Fire library to generate a CLI for the TestUsers class
# Uses names library to generate randon user names
# Run with no arguments for usage help

import sys
import os
import fire
import names
from python_freeipa import Client, exceptions

client = Client("ipa.demo1.freeipa.org", version="2.215")
client.login("admin", "Secret123")


class TestUsers:
    def add(self):
        """Generate and add test users to IPA and append the UIDs to a data file."""
        datafile = open('userlist.txt', 'a')
        for i in range(0, 10):
            full_name = names.get_full_name()
            username = full_name.lower().replace(" ", ".")
            first_name = full_name.split()[0]
            last_name = full_name.split()[1]
            print("Adding user: {}".format(full_name))
            client.user_add(username,
                            first_name,
                            last_name,
                            full_name,
コード例 #17
0
def get_ipa_client():
    client = Client(ipa_server, version='2.230', verify_ssl=False)
    client.login(ipa_service_user, ipa_service_pass)
    return client
コード例 #18
0
import progressbar

try:
    from settings import *
except:
    from settings_default import *

fas = AccountSystem(
    'https://admin.fedoraproject.org/accounts',
    username=fas_user,
    password=fas_pw,
)

instances = []
for instance in ipa_instances:
    ipa = Client(host=instance, verify_ssl=ipa_ssl)
    ipa.login(ipa_user, ipa_pw)
    instances.append(ipa)

if not skip_group_creation:
    # Start by creating groups
    fas_groups = fas.send_request(
        '/group/list',
        req_params={'search': group_search},
        auth=True,
        timeout=240
    )

    fas_groups = [g for g in fas_groups['groups'] if g['name'] not in ignore_groups]

    for group in progressbar.progressbar(fas_groups, redirect_stdout=True):
コード例 #19
0
OIDC_PROVIDER = "csh"
client_info = ClientMetadata(**app.config["OIDC_CLIENT_CONFIG"])
provider = ProviderConfiguration(issuer=app.config["OIDC_ISSUER"],
                                 client_metadata=client_info)
auth = OIDCAuthentication(app=app,
                          provider_configurations={OIDC_PROVIDER: provider})

# Connect to LDAP
ldap = CSHLDAP(app.config["LDAP_BIND_DN"], app.config["LDAP_BIND_PW"])

# Find FreeIPA server
ldap_srvs = srvlookup.lookup("ldap", "tcp", "csh.rit.edu")
ldap_uri = ldap_srvs[0].hostname

# FreeIPA API Connection
ipa = Client(ldap_uri, version="2.215")

# Configure rate limiting
if not app.config["DEBUG"]:
    limiter = Limiter(app,
                      key_func=get_remote_address,
                      default_limits=["50 per day", "10 per hour"])

# Initialize QR Code Generator
qr = QRcode(app)

# Import blueprints
# pylint: disable=wrong-import-position
from selfservice.blueprints.recovery import recovery_bp
from selfservice.blueprints.change import change_bp
from selfservice.blueprints.otp import otp_bp