Example #1
0
def add_user(args, l, rc):
    """Add or update a user"""
    from ambry.util import random_string

    from getpass import getpass

    account = l.find_or_new_account(args.user_name)

    account.major_type = 'user'

    account.access_key = args.user_name

    if args.admin:
        account.minor_type = 'admin'

    if not account.encrypted_secret or args.secret:
        account.secret = random_string(20)
        prt("Secret: {}".format(account.secret))

    if args.password:
        password = args.password
    elif not account.encrypted_password:
        password = getpass().strip()
    else:
        password = None

    if password:
        account.encrypt_password(password)
        assert account.test(password)

    account.url = None

    l.commit()
Example #2
0
def library_export(args, l, config):
    from simplecrypt import encrypt, decrypt, DecryptionException
    import json
    from ambry.util import random_string

    if args.password:
        password = args.password
    else:
        password = random_string(16)

    d = {
        'remotes': {},
        'accounts': {},
        'bundles': {}
    }

    for r in l.remotes:
        d['remotes'][r.short_name] = { k:v for k,v in r.dict.items() if bool(v ) and k not in ('id','list' ) }

    for k in l.accounts.keys():
        a = l.account(k)

        da = { k:v for k,v in a.dict.items() if bool(v )and k != 'secret' }

        # Change the secret encryption password
        if 'encrypted_secret' in da and da['encrypted_secret']:
            ds = a.decrypt_secret()
            if ds:
                da['encrypted_secret'] = a.encrypt_secret(ds, password)


        d['accounts'][a.account_id] = da

    for b in l.bundles:
        d['bundles'][b.identity.vid] = {
            'vid' : b.identity.vid,
            'vname': str(b.identity.name),
            'cache_key': b.identity.cache_key
        }

    if not args.password:
        prt("Password: {}".format(password))

    args.config_file.write(encrypt(password, json.dumps(d, indent = 4)).encode('base64'))
    args.config_file.close()
Example #3
0
def library_export(args, l, config):
    from simplecrypt import encrypt, decrypt, DecryptionException
    import json
    from ambry.util import random_string

    if args.password:
        password = args.password
    else:
        password = random_string(16)

    d = {'remotes': {}, 'accounts': {}, 'bundles': {}}

    for r in l.remotes:
        d['remotes'][r.short_name] = {
            k: v
            for k, v in r.dict.items() if bool(v) and k not in ('id', 'list')
        }

    for k in l.accounts.keys():
        a = l.account(k)

        da = {k: v for k, v in a.dict.items() if bool(v) and k != 'secret'}

        # Change the secret encryption password
        if 'encrypted_secret' in da and da['encrypted_secret']:
            ds = a.decrypt_secret()
            if ds:
                da['encrypted_secret'] = a.encrypt_secret(ds, password)

        d['accounts'][a.account_id] = da

    for b in l.bundles:
        d['bundles'][b.identity.vid] = {
            'vid': b.identity.vid,
            'vname': str(b.identity.name),
            'cache_key': b.identity.cache_key
        }

    if not args.password:
        prt("Password: {}".format(password))

    args.config_file.write(
        encrypt(password, json.dumps(d, indent=4)).encode('base64'))
    args.config_file.close()
Example #4
0
def start_ui(args, l, rc):

    from ambry_ui import app
    import ambry_ui.views
    import ambry_ui.jsonviews
    import ambry_ui.api
    import ambry_ui.user
    import webbrowser
    import socket
    from ambry.util import random_string, set_url_part

    if args.use_proxy:
        from werkzeug.contrib.fixers import ProxyFix
        app.wsgi_app = ProxyFix(app.wsgi_app)

    if not args.debug:
        webbrowser.open("http://{}:{}".format(args.host, args.port))

    else:
        import logging
        import os
        logging.basicConfig(level=logging.DEBUG)
        log = logging.getLogger('werkzeug')
        log.setLevel(logging.DEBUG)

        os.environ["AMBRY_UI_DEBUG"] = 'true' # DOn't know why this needs to be done, but it does.
        #prt("Running at http://{}:{}".format(args.host, args.port))

    if not app.config.get('AMBRY_ADMIN_PASS') and not args.no_accounts:
        app.config['AMBRY_ADMIN_PASS'] = random_string(20)
        app.config['LOGGED_IN_USER'] = '******'
        l.logger.info("Setting admin password to: {}".format(app.config['AMBRY_ADMIN_PASS'] ))

    db_init(args,l,rc)

    try:

        app.config['SECRET_KEY'] = 'secret'  # To Ensure logins persist
        app.config["WTF_CSRF_SECRET_KEY"] = 'secret'
        app.run(host=args.host, port=int(args.port), debug=args.debug)
    except socket.error as e:
        warn("Failed to start ui: {}".format(e))
Example #5
0
def config_install(args, l, rc):
    import yaml
    import pkgutil
    import os
    from os.path import join, dirname
    import getpass
    import ambry.support
    from ambry.run import ROOT_DIR, USER_DIR, CONFIG_FILE, ACCOUNTS_FILE
    from ambry.util import AttrDict

    user = getpass.getuser()

    default_config_file = join(dirname(ambry.support.__file__),'ambry-{}.yaml'.format(args.template))

    d = AttrDict().update_yaml(default_config_file)

    user_config_dir = os.path.join(os.path.expanduser('~'), USER_DIR)

    if user == 'root': # Root user
        config_dir = ROOT_DIR
        default_root = d.library.filesystem_root

    elif os.getenv('VIRTUAL_ENV'):  # Special case for python virtual environments
        config_dir = os.path.join(os.getenv('VIRTUAL_ENV'), USER_DIR)
        default_root = os.path.join(os.getenv('VIRTUAL_ENV'), 'data')

    else: # Non-root user, outside of virtualenv
        config_dir = user_config_dir
        warn(("Installing as non-root, to '{}'\n" +
              "Run as root to install for all users.").format(config_dir))
        default_root = os.path.join(os.path.expanduser('~'), 'ambry')

    if args.root:
        default_root = args.root

    if not os.path.exists(user_config_dir):
        os.makedirs(user_config_dir)

    if not os.path.exists(config_dir):
        os.makedirs(config_dir)

    if os.path.exists(os.path.join(config_dir, CONFIG_FILE)):
        if args.force:
            prt("File output file exists, overwriting: {}".format(config_dir))

        else:
            fatal("Output file {} exists. Use  -f to overwrite".format(config_dir))

    d['library']['filesystem_root'] = default_root

    s = d.dump()

    if args.prt:
        prt(s.replace("{", "{{").replace("}", "}}"))
        return

    #Create an empty accounts file, if it does not exist
    user_accounts_file =os.path.join(user_config_dir, ACCOUNTS_FILE)

    if not os.path.exists(user_accounts_file):
        with open(user_accounts_file, 'w') as f:
            from ambry.util import random_string
            d = dict(accounts=dict(
                        password=random_string(16),
                        ambry=dict(
                            name=None, email=None
                        )
                    )
                )

            prt('Writing accounts file: {}'.format(user_accounts_file))
            f.write(yaml.dump(d, indent=4, default_flow_style=False))

    config_file = os.path.join(config_dir, CONFIG_FILE)

    with open(config_file, 'w') as f:
        prt('Writing config file: {}'.format(config_file))
        f.write(s)

    # Make the directories.

    from ..run import get_runconfig
    rc = get_runconfig(config_file)

    for name, v in iteritems(rc.filesystem):
        dr = v.format(root=rc.library.filesystem_root)

        try:

            if not os.path.exists(dr):
                prt("Making directory: {}".format(dr))
                os.makedirs(dr)
        except KeyError:
            pass