Provision a system user
776363
def provision_system_user(items, database_name, overwrite=False, clear=False, skip_user_check=False):
    """"""

    from hfos.provisions.base import provisionList
    from hfos.database import objectmodels

    # TODO: Add a root user and make sure owner can access it later.
    # Setting up details and asking for a password here is not very useful,
    # since this process is usually run automated.

    if overwrite is True:
        hfoslog('Refusing to overwrite system user!', lvl=warn,
                emitter='PROVISIONS')
        overwrite = False

    system_user_count = objectmodels['user'].count({'name': 'System'})
    if system_user_count == 0 or clear is False:
        provisionList(Users, 'user', overwrite, clear,  skip_user_check=True)
        hfoslog('Provisioning: Users: Done.', emitter="PROVISIONS")
    else:
        hfoslog('System user already present.', lvl=warn, emitter='PROVISIONS')
760181
def create_user(email, password, active, confirmed_at, send_email):
    
    if confirmed_at == 'now':
        confirmed_at = security.datetime_factory()
    user = user_manager.create(email=email, password=password, active=active,
                               confirmed_at=confirmed_at)
    if click.confirm(f'Are you sure you want to create {user!r}?'):
        security_service.register_user(user, allow_login=False, send_email=send_email)
        user_manager.save(user, commit=True)
        click.echo(f'Successfully created {user!r}')
    else:
        click.echo('Cancelled.')
1237664
def prepare_monitor(tenant=tenant, user=user, password=password, organization=organization, zone_name=zone_name):
    
    router = PrivatePath(tenant, verify_codes=False)

    payload = {
        "firstName": "AllSeeingEye",
        "lastName": "Monitor",
        "email": user,
        "password": password,
        "accept": "true"
    }
    try:
        router.post_quick_sign_up(data=payload)
    except exceptions.ApiUnauthorizedError:
        pass

    platform = QubellPlatform.connect(tenant=tenant, user=user, password=password)
    org = platform.organization(name=organization)
    if zone_name:
        zone = org.zones[zone_name]
    else:
        zone = org.zone
    env = org.environment(name="Monitor for "+zone.name, zone=zone.id)
    env.init_common_services(with_cloud_account=False, zone_name=zone_name)

    # todo: move to env
    policy_name = lambda policy: "{}.{}".format(policy.get('action'), policy.get('parameter'))
    env_data = env.json()
    key_id = [p for p in env_data['policies'] if 'provisionVms.publicKeyId' == policy_name(p)][0].get('value')

    with env as envbulk:
        envbulk.add_marker('monitor')
        envbulk.add_property('publicKeyId', 'string', key_id)

    monitor = Manifest(file=os.path.join(os.path.dirname(__file__), './monitor_manifests/monitor.yml'))
    monitor_child = Manifest(file=os.path.join(os.path.dirname(__file__), './monitor_manifests/monitor_child.yml'))

    org.application(manifest=monitor_child, name='monitor-child')
    app = org.application(manifest=monitor, name='monitor')

    return platform, org.id, app.id, env.id
228456
public static void setUpUsers() {
        LOG.info("SETTING UP THE USERS TO BE USED ");
        adminUser = userProps.getProperty("adminUsername");
        adminUserPassword = userProps.getProperty("adminPassword");
        LOG.info("COMPLETED USER SETUP ");
    }
551465
def get_user(self, userPk):
        """"""
        r = self._request('user/' + str(userPk))
        if r:
            # Set base properties and copy data inside the user
            u = User()
            u.pk = u.id = userPk
            u.__dict__.update(r.json())
            return u
        return None
1337158
def cli(env, identifier):
    """"""

    mgr = SoftLayer.UserManager(env.client)
    user_id = helpers.resolve_id(mgr.resolve_ids, identifier, 'username')
    object_mask = "mask[id, permissions, isMasterUserFlag, roles]"

    user = mgr.get_user(user_id, object_mask)
    all_permissions = mgr.get_all_permissions()
    user_permissions = perms_to_dict(user['permissions'])

    if user['isMasterUserFlag']:
        click.secho('This account is the Master User and has all permissions enabled', fg='green')

    env.fout(roles_table(user))
    env.fout(permission_table(user_permissions, all_permissions))
669202
def user_to_uid(user):
    '''
    
    '''
    if user is None:
        user = salt.utils.user.get_user()
    try:
        if isinstance(user, int):
            return user
        return pwd.getpwnam(user).pw_uid
    except KeyError:
        return ''
85867
def guest_start(self, userid):
        """""""
        LOG.info("Begin to power on vm %s", userid)
        self._smtclient.guest_start(userid)
        LOG.info("Complete power on vm %s", userid)
1116455
def provisionUser( dbid, roleid, email, fname, lname )
      @dbid, @roleid, @email, @fname, @lname = dbid, roleid, email, fname, lname 
      
      xmlRequestData = toXML( :roleid, @roleid)
      xmlRequestData << toXML( :email, @email )
      xmlRequestData << toXML( :fname, @fname )
      xmlRequestData << toXML( :lname, @lname )
      
      sendRequest( :provisionUser, xmlRequestData )
      
      @userid = getResponseValue( :userid )
      
      return self if @chainAPIcalls
      @userid
   end
817344
def user(username, password, all):
    """"""
    if current_app.config['AUTH_PROVIDER'] != 'basic':
        raise click.UsageError('Not required for {} admin users'.format(current_app.config['AUTH_PROVIDER']))
    if username and username not in current_app.config['ADMIN_USERS']:
        raise click.UsageError('User {} not an admin'.format(username))
    if not username and not all:
        raise click.UsageError('Missing option "--username".')

    def create_user(admin):
        email = admin if '@' in admin else None
        user = User(
            name='Admin user',
            login=admin,
            password=generate_password_hash(password),
            roles=['admin'],
            text='Created by alertad script',
            email=email,
            email_verified=bool(email)
        )
        try:
            db.get_db()  # init db on global app context
            user = user.create()
        except Exception as e:
            click.echo('ERROR: {}'.format(e))
        else:
            click.echo('{} {}'.format(user.id, user.name))

    if all:
        for admin in current_app.config['ADMIN_USERS']:
            create_user(admin)
    else:
        create_user(username)
1239130
def enable(ctx):
    """"""

    if ctx.obj['username'] is None:
        log('Specify the username with "iso db user --username ..."')
        return

    change_user = ctx.obj['db'].objectmodels['user'].find_one({
        'name': ctx.obj['username']
    })

    change_user.active = True
    change_user.save()
    log('Done')
98708
function as_user(options, cb) {
  var user = options.user,
      bin = options.bin,
      type = options.type,
      opts = options.opts,
      args = options.args,
      finished = false,
      runner = options.bin,
      command = options.args;

  if (!(user === system.get_running_user())) {
    if (os_name == 'windows') {
      runner = safexec_bin;
      if (type == 'exec') runner = '"' + runner + '"';
      command = ['"' + bin + '"'].concat(args.map(function(x){ return '"' + x + '"'; }));
    } else {
      runner = runner_script;
      command = [user, bin].concat(args);

      if (fs.existsSync(node_bin)) {
        command = [runner].concat(command);
        runner = node_bin;
      }
    }
  }

  if (!opts.env) opts.env = process.env;

  if (process.platform == 'linux' && !opts.env.DISPLAY) {
    opts.env.DISPLAY = ':0'; // ensure active display is used
  }

  if (type == 'exec') {
    var cmd = runner + ' ' + command.join(' '),
        child = cp.exec(cmd, opts, cb);
    child.impersonating = user;
    return child;
  }

  var done = function(e) {
    if (finished) return;

    finished = true;
    cb(e, child);
  }

  // ok, so they want spawn mode. let's fire up the command.
  var child = cp.spawn(runner, command, opts);
  child.impersonating = user;

  // set a listener on error, so if it fails the app doesn't crash!
  child.on('error', function(err) {
    if (err.code == 'ENOENT')
      err.message = 'ENOENT - Executable not found: ' + runner;

    done(err);
  })

  process.nextTick(done);
}
1225633
def update_user(self, instance, user, name=None, password=None, host=None):
        
        return instance.update_user(user, name=name, password=password,
                host=host)
209368
def require_user(self, *users, user=None):
        """"""

        # accept old-style single user keyword-argument as well
        if user:
            users = (*users, user)

        def _require_auth(view_func):
            @wraps(view_func)
            def wrapper(*args, **kwargs):
                """ Effective wrapper """
                username, out_token = self.authenticate()
                if username and out_token:
                    b64_token = base64.b64encode(out_token).decode('utf-8')
                    auth_data = 'Negotiate {0}'.format(b64_token)
                    if not users or username in users:
                        response = make_response(view_func(*args,
                                                           username=username,
                                                           **kwargs))
                    else:
                        response = Response(status=403)
                    response.headers['WWW-Authenticate'] = auth_data
                    return response
                return Response(
                    status=401,
                    headers={'WWW-Authenticate': 'Negotiate'},
                )

            return wrapper
        return _require_auth
655432
def _get_credentials(username=None, password=None, dbhost=None):
    """"""

    # Database salt
    system_config = dbhost.objectmodels['systemconfig'].find_one({
        'active': True
    })

    try:
        salt = system_config.salt.encode('ascii')
    except (KeyError, AttributeError):
        log('No systemconfig or it is without a salt! '
            'Reinstall the system provisioning with'
            'hfos_manage.py install provisions -p system')
        sys.exit(3)

    if username is None:
        username = _ask("Please enter username: ")
    else:
        username = username

    if password is None:
        password = _ask_password()
    else:
        password = password

    try:
        password = password.encode('utf-8')
    except UnicodeDecodeError:
        password = password

    passhash = hashlib.sha512(password)
    passhash.update(salt)

    return username, passhash.hexdigest()
719693
def enable_root_user(self):
        
        uri = "/instances/%s/root" % self.id
        resp, body = self.manager.api.method_post(uri)
        return body["user"]["password"]
979278
def cli(env, identifier, passwords, price):
    """"""

    hardware = SoftLayer.HardwareManager(env.client)

    table = formatting.KeyValueTable(['name', 'value'])
    table.align['name'] = 'r'
    table.align['value'] = 'l'

    hardware_id = helpers.resolve_id(hardware.resolve_ids, identifier, 'hardware')
    result = hardware.get_hardware(hardware_id)
    result = utils.NestedDict(result)

    operating_system = utils.lookup(result, 'operatingSystem', 'softwareLicense', 'softwareDescription') or {}
    memory = formatting.gb(result.get('memoryCapacity', 0))
    owner = None
    if utils.lookup(result, 'billingItem') != []:
        owner = utils.lookup(result, 'billingItem', 'orderItem', 'order', 'userRecord', 'username')

    table.add_row(['id', result['id']])
    table.add_row(['guid', result['globalIdentifier'] or formatting.blank()])
    table.add_row(['hostname', result['hostname']])
    table.add_row(['domain', result['domain']])
    table.add_row(['fqdn', result['fullyQualifiedDomainName']])
    table.add_row(['status', result['hardwareStatus']['status']])
    table.add_row(['datacenter', result['datacenter']['name'] or formatting.blank()])
    table.add_row(['cores', result['processorPhysicalCoreAmount']])
    table.add_row(['memory', memory])
    table.add_row(['public_ip', result['primaryIpAddress'] or formatting.blank()])
    table.add_row(['private_ip', result['primaryBackendIpAddress'] or formatting.blank()])
    table.add_row(['ipmi_ip', result['networkManagementIpAddress'] or formatting.blank()])
    table.add_row(['os', operating_system.get('name') or formatting.blank()])
    table.add_row(['os_version', operating_system.get('version') or formatting.blank()])
    table.add_row(['created', result['provisionDate'] or formatting.blank()])
    table.add_row(['owner', owner or formatting.blank()])

    vlan_table = formatting.Table(['type', 'number', 'id'])
    for vlan in result['networkVlans']:
        vlan_table.add_row([vlan['networkSpace'], vlan['vlanNumber'], vlan['id']])

    table.add_row(['vlans', vlan_table])

    if result.get('notes'):
        table.add_row(['notes', result['notes']])

    if price:
        total_price = utils.lookup(result, 'billingItem', 'nextInvoiceTotalRecurringAmount') or 0

        price_table = formatting.Table(['Item', 'Recurring Price'])
        price_table.add_row(['Total', total_price])

        for item in utils.lookup(result, 'billingItem', 'children') or []:
            price_table.add_row([item['description'], item['nextInvoiceTotalRecurringAmount']])

        table.add_row(['prices', price_table])

    if passwords:
        pass_table = formatting.Table(['username', 'password'])
        for item in result['operatingSystem']['passwords']:
            pass_table.add_row([item['username'], item['password']])
        table.add_row(['users', pass_table])

        pass_table = formatting.Table(['ipmi_username', 'password'])
        for item in result['remoteManagementAccounts']:
            pass_table.add_row([item['username'], item['password']])
        table.add_row(['remote users', pass_table])

    table.add_row(['tags', formatting.tags(result['tagReferences'])])

    env.fout(table)