Ember-cli upgrade from ~3.8 to ~3.20 (#9972)

* Update ember-cli to ~3.20

* Remove bad optional-feature

* Remove ember-fetch dep

* re-install ember-fetch

* update model fragments pr

* update ember model fragments correct package name

* update ember composable helpers to solve array helper error

* update ember-concurrency

* add back engine dependencies, automatically removed during ember-cli-upgrade

* make author-form-options component js file otherwise error

* for now comment out withTestWaiter

* add eslint-node and fix if not with unless in templates

* fix linting for tab index of false is now -1 and add type button to all buttons without types

* fix href errors for linting, likely have to come back and fix

* using eslint fix flag to fix all this.gets

* ember modules codemode removed files that had module twice, will fix in next commit

* finish codemode ember-data-codemod needed to rename const model

* more this.get removal codemode did not work

* cont. removal of this.get

* stop mixin rules until figure out how to reconfig them all

* smaller eslint ignores

* get codemode

* testing app small fixes to bring it back after all the changes

* small changes to eslint

* test removal of getProperties

* fix issue with baseKey because value could be unknown needed to add a question mark in nested get

* smaller linting fixes

* get nested fixes

* small linting error fixes

* small linting changes

* working through more small linting changes

* another round of linting modifications

* liniting fixes

* ember module codemod

* quinit dom codemod

* angle bracket codemod

* discovered that components must have js files

* ran all codemods this is all that's left

* small changes to fix get needs two object, should not have been using get.

* fix issue with one input in form field

* fun times with set and onChange from oninput

* fix issue with model not being passed through on secret-edit-display

* fix issue with yarn run test not working, revert without npm run all

* linting and small fix when loading without a selectAuthBackend

* fix failing test with ui-wizard issue

* fix test failure due to model not being asked for correctly with new changes, probably run into this more.

* fix issue with component helper and at props specific to wizard

* rename log to clilog due to conflict with new eslint rule

* small changes for test failures

* component helper at fixes

* Revert to old component style something with new one broke this and can't figure it out for now

* small fishy smelling test fixes will revisit

* small test changes

* more small test changes, appears upgrade treats spaces differently

* comment out code and test that no longer seems relevant but confirm

* clean run on component test though still some potential timing issues on ui-console test

* fixing one auth test issue and timing issue on enable-test

* small mods

* fix this conditional check from upgrade

* linting fixes after master merge

* package updates using yarn upgrade-interactive

* update libraries that did not effect any of the test failures.

* update ember truth helpers library

* settling tests

* Fix ui-panel control group output

* fix features selection test failures

* Fix auth tests (x-vault-token)

* fix shared test

* fix issue with data null on backend

* Revert "Fix auth tests (x-vault-token)"

This reverts commit 89cb174b2f1998efa56d9604d14131415ae65d6f.

* Fix auth tests (x-vault-token) without updating this.set

* Update redirect-to tests

* fix wrapped token test

* skip some flaky test

* fix issue with href and a tags vs buttons

* fix linting

* updates to get tests running (#10409)

* yarn isntall

* increasing resource_class

* whoops

* trying large

* back to xlarge

* Fix param issue on transform item routes

* test fixes

* settle on policies (old) test

* fix browserstack test warning and skips of test confirmed worked

* Fix redirect-to test

* skips

* fix transformation test and skip some kmip

* Skip tests

* Add meep marker to remaining failing tests

* Skip test with failing component

* rever skip on secret-create test

* Skip piece of test that fails due to navigation-input

* fix settings test where can and skip in others after confirming

* fix circle ci test failures

* ssh role settle

* Fix navigate-input and add settled to test

* Remove extra import

* secret cubbyhole and alicloud

* Add settled to gcpkms test

* settles on redirect to test

* Bump browserstack test resource to large

* Update browserstack resource size to xlarge

* update todos

* add back in withTestWaiter

* try and fix credentials conditional action added comment instead

* Update volatile computed properies to get functions

* this step was never reached and we never defined secretType anywhere so I removed

* add settled to policy old test

* Fix navigate-input on policies and leases

* replace ssh test with no var hoping that helps and add settled to other failing tests, unskip console tests

* kmip, transit, role test remove a skip and add in settled

* fix hover copy button, had to remove some testing functionality

* Remove private router service

* remove skip on control ssh and ui panel, fix search select by restructuring how to read the error

* final bit of working through skipped test

* Replace clearNonGlobalModels by linking directly to namespace with href-to

* Remove unused var

* Fix role-ssh id bug by updating form-field-from-model to form-field-group-loop

* Fix transit create id would not update

* Update option toggle selector for ssh-role

* Fix ssh selector

* cleanup pt1

* small clean up

* cleanup part2

* Fix computed on pricing-metrics-form

* small cleanup based on chelseas comments.

Co-authored-by: Chelsea Shaw <chelshaw.dev@gmail.com>
Co-authored-by: Sarah Thompson <sthompson@hashicorp.com>
This commit is contained in:
Angel Garbarino 2020-12-03 16:00:22 -07:00 committed by GitHub
parent 8d8b7f287f
commit 081db3a240
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
584 changed files with 6266 additions and 5106 deletions

4
.circleci/config.yml generated
View File

@ -515,7 +515,7 @@ jobs:
- image: docker.mirror.hashicorp.services/node:10-buster - image: docker.mirror.hashicorp.services/node:10-buster
shell: /usr/bin/env bash -euo pipefail -c shell: /usr/bin/env bash -euo pipefail -c
working_directory: /go/src/github.com/hashicorp/vault working_directory: /go/src/github.com/hashicorp/vault
resource_class: medium+ resource_class: xlarge
steps: steps:
- checkout - checkout
- restore_cache: - restore_cache:
@ -631,7 +631,7 @@ jobs:
- image: docker.mirror.hashicorp.services/node:10-buster - image: docker.mirror.hashicorp.services/node:10-buster
shell: /usr/bin/env bash -euo pipefail -c shell: /usr/bin/env bash -euo pipefail -c
working_directory: /go/src/github.com/hashicorp/vault working_directory: /go/src/github.com/hashicorp/vault
resource_class: medium+ resource_class: xlarge
steps: steps:
- checkout - checkout
- restore_cache: - restore_cache:

View File

@ -1,5 +1,5 @@
executor: node executor: node
resource_class: medium+ resource_class: xlarge
steps: steps:
- checkout - checkout
- restore_yarn_cache - restore_yarn_cache

View File

@ -1,5 +1,5 @@
executor: node executor: node
resource_class: medium+ resource_class: xlarge
steps: steps:
- checkout - checkout
- restore_yarn_cache - restore_yarn_cache

View File

@ -4,7 +4,6 @@
root = true root = true
[*] [*]
end_of_line = lf end_of_line = lf
charset = utf-8 charset = utf-8

View File

@ -1,10 +1,16 @@
// env: node /* eslint-disable no-undef */
'use strict';
module.exports = { module.exports = {
parser: 'babel-eslint', parser: 'babel-eslint',
root: true, root: true,
parserOptions: { parserOptions: {
ecmaVersion: 2018, ecmaVersion: 2018,
sourceType: 'module', sourceType: 'module',
ecmaFeatures: {
legacyDecorators: true,
},
}, },
plugins: ['ember', 'prettier'], plugins: ['ember', 'prettier'],
extends: ['eslint:recommended', 'plugin:ember/recommended', 'prettier'], extends: ['eslint:recommended', 'plugin:ember/recommended', 'prettier'],
@ -13,13 +19,9 @@ module.exports = {
es6: true, es6: true,
}, },
rules: { rules: {
'no-unused-vars': ['error', { ignoreRestSiblings: true }], // TODO revisit once figure out how to replace, added during upgrade to 3.20
'prettier/prettier': 'error', 'ember/no-new-mixins': 'off',
'ember/no-jquery': 'error', 'ember/no-mixins': 'off',
},
globals: {
TextEncoderLite: true,
TextDecoderLite: true,
}, },
overrides: [ overrides: [
// node files // node files
@ -41,6 +43,13 @@ module.exports = {
browser: false, browser: false,
node: true, node: true,
}, },
plugins: ['node'],
extends: ['plugin:node/recommended'],
rules: {
// this can be removed once the following is fixed
// https://github.com/mysticatea/eslint-plugin-node/issues/77
'node/no-unpublished-require': 'off',
},
}, },
], ],
}; };

224
ui/MODULE_REPORT.md Normal file
View File

@ -0,0 +1,224 @@
## Module Report
### Unknown Global
**Global**: `Ember.testing`
**Location**: `app/components/auth-jwt.js` at line 9
```js
/* eslint-disable ember/no-ember-testing-in-module-scope */
const WAIT_TIME = Ember.testing ? 0 : 500;
const ERROR_WINDOW_CLOSED =
'The provider window was closed before authentication was complete. Please click Sign In to try again.';
```
### Unknown Global
**Global**: `Ember.testing`
**Location**: `app/components/auth-jwt.js` at line 117
```js
exchangeOIDC: task(function*(event, oidcWindow) {
// in non-incognito mode we need to use a timeout because it takes time before oidcState is written to local storage.
let oidcState = Ember.testing
? event.storageArea.getItem('oidcState')
: (yield timeout(1000).then(() => event.storageArea.getItem('oidcState')));
```
### Unknown Global
**Global**: `Ember.testing`
**Location**: `app/routes/vault.js` at line 7
```js
import Ember from 'ember';
/* eslint-disable ember/no-ember-testing-in-module-scope */
const SPLASH_DELAY = Ember.testing ? 0 : 300;
export default Route.extend({
```
### Unknown Global
**Global**: `Ember.testing`
**Location**: `app/services/auth.js` at line 267
```js
checkShouldRenew: task(function*() {
while (true) {
if (Ember.testing) {
return;
}
```
### Unknown Global
**Global**: `Ember.testing`
**Location**: `lib/core/addon/components/ttl-form.js` at line 82
```js
this.set('time', parsedTime);
this.handleChange();
if (Ember.testing) {
return;
}
```
### Unknown Global
**Global**: `Ember.testing`
**Location**: `app/routes/vault/cluster.js` at line 78
```js
// when testing, the polling loop causes promises to never settle so acceptance tests hang
// to get around that, we just disable the poll in tests
if (Ember.testing) {
return;
}
```
### Unknown Global
**Global**: `Ember.onerror`
**Location**: `tests/helpers/wait-for-error.js` at line 5
```js
export default function waitForError(opts) {
const orig = Ember.onerror;
let error = null;
```
### Unknown Global
**Global**: `Ember.onerror`
**Location**: `tests/helpers/wait-for-error.js` at line 5
```js
export default function waitForError(opts) {
const orig = Ember.onerror;
let error = null;
```
### Unknown Global
**Global**: `Ember.onerror`
**Location**: `tests/helpers/wait-for-error.js` at line 8
```js
let error = null;
Ember.onerror = err => {
error = err;
};
```
### Unknown Global
**Global**: `Ember.onerror`
**Location**: `tests/helpers/wait-for-error.js` at line 13
```js
return waitUntil(() => error, opts).finally(() => {
Ember.onerror = orig;
});
}
```
### Unknown Global
**Global**: `Ember.Logger`
**Location**: `tests/acceptance/not-found-test.js` at line 15
```js
hooks.beforeEach(function() {
loggerError = Ember.Logger.error;
adapterException = Ember.Test.adapter.exception;
Ember.Test.adapter.exception = () => {};
```
### Unknown Global
**Global**: `Ember.Test`
**Location**: `tests/acceptance/not-found-test.js` at line 16
```js
hooks.beforeEach(function() {
loggerError = Ember.Logger.error;
adapterException = Ember.Test.adapter.exception;
Ember.Test.adapter.exception = () => {};
Ember.Logger.error = () => {};
```
### Unknown Global
**Global**: `Ember.Test`
**Location**: `tests/acceptance/not-found-test.js` at line 17
```js
loggerError = Ember.Logger.error;
adapterException = Ember.Test.adapter.exception;
Ember.Test.adapter.exception = () => {};
Ember.Logger.error = () => {};
return authPage.login();
```
### Unknown Global
**Global**: `Ember.Logger`
**Location**: `tests/acceptance/not-found-test.js` at line 18
```js
adapterException = Ember.Test.adapter.exception;
Ember.Test.adapter.exception = () => {};
Ember.Logger.error = () => {};
return authPage.login();
});
```
### Unknown Global
**Global**: `Ember.Test`
**Location**: `tests/acceptance/not-found-test.js` at line 23
```js
hooks.afterEach(function() {
Ember.Test.adapter.exception = adapterException;
Ember.Logger.error = loggerError;
return logout.visit();
```
### Unknown Global
**Global**: `Ember.Logger`
**Location**: `tests/acceptance/not-found-test.js` at line 24
```js
hooks.afterEach(function() {
Ember.Test.adapter.exception = adapterException;
Ember.Logger.error = loggerError;
return logout.visit();
});
```

View File

@ -1,16 +1,15 @@
import AdapterError from '@ember-data/adapter/error';
import RESTAdapter from '@ember-data/adapter/rest';
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import { assign } from '@ember/polyfills'; import { assign } from '@ember/polyfills';
import { set } from '@ember/object'; import { set } from '@ember/object';
import RSVP from 'rsvp'; import RSVP from 'rsvp';
import DS from 'ember-data';
import AdapterFetch from 'ember-fetch/mixins/adapter-fetch';
import fetch from 'fetch';
import config from '../config/environment'; import config from '../config/environment';
const { APP } = config; const { APP } = config;
const { POLLING_URLS, NAMESPACE_ROOT_URLS } = APP; const { POLLING_URLS, NAMESPACE_ROOT_URLS } = APP;
export default DS.RESTAdapter.extend(AdapterFetch, { export default RESTAdapter.extend({
auth: service(), auth: service(),
namespaceService: service('namespace'), namespaceService: service('namespace'),
controlGroup: service(), controlGroup: service(),
@ -32,7 +31,7 @@ export default DS.RESTAdapter.extend(AdapterFetch, {
}, },
addHeaders(url, options) { addHeaders(url, options) {
let token = options.clientToken || this.get('auth.currentToken'); let token = options.clientToken || this.auth.currentToken;
let headers = {}; let headers = {};
if (token && !options.unauthenticated) { if (token && !options.unauthenticated) {
headers['X-Vault-Token'] = token; headers['X-Vault-Token'] = token;
@ -40,8 +39,7 @@ export default DS.RESTAdapter.extend(AdapterFetch, {
if (options.wrapTTL) { if (options.wrapTTL) {
headers['X-Vault-Wrap-TTL'] = options.wrapTTL; headers['X-Vault-Wrap-TTL'] = options.wrapTTL;
} }
let namespace = let namespace = typeof options.namespace === 'undefined' ? this.namespaceService.path : options.namespace;
typeof options.namespace === 'undefined' ? this.get('namespaceService.path') : options.namespace;
if (namespace && !NAMESPACE_ROOT_URLS.some(str => url.includes(str))) { if (namespace && !NAMESPACE_ROOT_URLS.some(str => url.includes(str))) {
headers['X-Vault-Namespace'] = namespace; headers['X-Vault-Namespace'] = namespace;
} }
@ -62,7 +60,7 @@ export default DS.RESTAdapter.extend(AdapterFetch, {
let url = intendedUrl; let url = intendedUrl;
let type = method; let type = method;
let options = passedOptions; let options = passedOptions;
let controlGroup = this.get('controlGroup'); let controlGroup = this.controlGroup;
let controlGroupToken = controlGroup.tokenForUrl(url); let controlGroupToken = controlGroup.tokenForUrl(url);
// if we have a Control Group token that matches the intendedUrl, // if we have a Control Group token that matches the intendedUrl,
// then we want to unwrap it and return the unwrapped response as // then we want to unwrap it and return the unwrapped response as
@ -86,7 +84,7 @@ export default DS.RESTAdapter.extend(AdapterFetch, {
} }
const [resp] = args; const [resp] = args;
if (resp && resp.warnings) { if (resp && resp.warnings) {
let flash = this.get('flashMessages'); let flash = this.flashMessages;
resp.warnings.forEach(message => { resp.warnings.forEach(message => {
flash.info(message); flash.info(message);
}); });
@ -115,7 +113,7 @@ export default DS.RESTAdapter.extend(AdapterFetch, {
handleResponse(status, headers, payload, requestData) { handleResponse(status, headers, payload, requestData) {
const returnVal = this._super(...arguments); const returnVal = this._super(...arguments);
// ember data errors don't have the status code, so we add it here // ember data errors don't have the status code, so we add it here
if (returnVal instanceof DS.AdapterError) { if (returnVal instanceof AdapterError) {
set(returnVal, 'httpStatus', status); set(returnVal, 'httpStatus', status);
set(returnVal, 'path', requestData.url); set(returnVal, 'path', requestData.url);
} }

View File

@ -14,7 +14,7 @@ export default ApplicationAdapter.extend({
buildURL(modelName, id, snapshot) { buildURL(modelName, id, snapshot) {
const backendId = id ? id : snapshot.belongsTo('backend').id; const backendId = id ? id : snapshot.belongsTo('backend').id;
let url = `${this.get('namespace')}/${backendId}/config`; let url = `${this.namespace}/${backendId}/config`;
// aws has a lot more config endpoints // aws has a lot more config endpoints
if (modelName.includes('aws')) { if (modelName.includes('aws')) {
url = `${url}/${this.pathForType(modelName)}`; url = `${url}/${this.pathForType(modelName)}`;

View File

@ -1,7 +1,7 @@
import AdapterError from '@ember-data/adapter/error';
import { assign } from '@ember/polyfills'; import { assign } from '@ember/polyfills';
import { get, set } from '@ember/object'; import { get, set } from '@ember/object';
import ApplicationAdapter from './application'; import ApplicationAdapter from './application';
import DS from 'ember-data';
import { encodePath } from 'vault/utils/path-encoding-helpers'; import { encodePath } from 'vault/utils/path-encoding-helpers';
export default ApplicationAdapter.extend({ export default ApplicationAdapter.extend({
@ -34,7 +34,7 @@ export default ApplicationAdapter.extend({
}); });
} }
return this.ajax(this.url(), 'GET').catch(e => { return this.ajax(this.url(), 'GET').catch(e => {
if (e instanceof DS.AdapterError) { if (e instanceof AdapterError) {
set(e, 'policyPath', 'sys/auth'); set(e, 'policyPath', 'sys/auth');
} }
throw e; throw e;

View File

@ -1,6 +1,6 @@
import AdapterError from '@ember-data/adapter/error';
import { set } from '@ember/object'; import { set } from '@ember/object';
import ApplicationAdapter from './application'; import ApplicationAdapter from './application';
import DS from 'ember-data';
export default ApplicationAdapter.extend({ export default ApplicationAdapter.extend({
pathForType() { pathForType() {
@ -9,7 +9,7 @@ export default ApplicationAdapter.extend({
findRecord(store, type, id) { findRecord(store, type, id) {
return this.ajax(this.buildURL(type), 'POST', { data: { paths: [id] } }).catch(e => { return this.ajax(this.buildURL(type), 'POST', { data: { paths: [id] } }).catch(e => {
if (e instanceof DS.AdapterError) { if (e instanceof AdapterError) {
set(e, 'policyPath', 'sys/capabilities-self'); set(e, 'policyPath', 'sys/capabilities-self');
} }
throw e; throw e;

View File

@ -1,3 +1,4 @@
import AdapterError from '@ember-data/adapter/error';
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import { assign } from '@ember/polyfills'; import { assign } from '@ember/polyfills';
import { hash, resolve } from 'rsvp'; import { hash, resolve } from 'rsvp';
@ -5,9 +6,6 @@ import { assert } from '@ember/debug';
import { pluralize } from 'ember-inflector'; import { pluralize } from 'ember-inflector';
import ApplicationAdapter from './application'; import ApplicationAdapter from './application';
import DS from 'ember-data';
const { AdapterError } = DS;
const ENDPOINTS = [ const ENDPOINTS = [
'health', 'health',
@ -44,7 +42,7 @@ export default ApplicationAdapter.extend({
health: this.health(), health: this.health(),
sealStatus: this.sealStatus().catch(e => e), sealStatus: this.sealStatus().catch(e => e),
}; };
if (this.get('version.isEnterprise') && this.get('namespaceService.inRootNamespace')) { if (this.version.isEnterprise && this.namespaceService.inRootNamespace) {
fetches.replicationStatus = this.replicationStatus().catch(e => e); fetches.replicationStatus = this.replicationStatus().catch(e => e);
} }
return hash(fetches).then(({ health, sealStatus, replicationStatus }) => { return hash(fetches).then(({ health, sealStatus, replicationStatus }) => {

View File

@ -40,7 +40,7 @@ export default ApplicationAdapter.extend({
query(store, type, query) { query(store, type, query) {
return this.ajax(this.urlForQuery(query, type.modelName), 'GET').then(resp => { return this.ajax(this.urlForQuery(query, type.modelName), 'GET').then(resp => {
// remove pagination query items here // remove pagination query items here
const { size, page, responsePath, pageFilter, ...modelAttrs } = query; const { ...modelAttrs } = query;
resp._requestQuery = modelAttrs; resp._requestQuery = modelAttrs;
return resp; return resp;
}); });

View File

@ -1,8 +1,8 @@
import AdapterError from '@ember-data/adapter/error';
import { hash, resolve } from 'rsvp'; import { hash, resolve } from 'rsvp';
import { capitalize } from '@ember/string'; import { capitalize } from '@ember/string';
import { set } from '@ember/object'; import { set } from '@ember/object';
import ApplicationAdapter from './application'; import ApplicationAdapter from './application';
import DS from 'ember-data';
export default ApplicationAdapter.extend({ export default ApplicationAdapter.extend({
namespace: 'v1', namespace: 'v1',
@ -49,7 +49,7 @@ export default ApplicationAdapter.extend({
fetchSection(backendPath, section) { fetchSection(backendPath, section) {
const sections = ['cert', 'urls', 'crl', 'tidy']; const sections = ['cert', 'urls', 'crl', 'tidy'];
if (!section || !sections.includes(section)) { if (!section || !sections.includes(section)) {
const error = new DS.AdapterError(); const error = new AdapterError();
set(error, 'httpStatus', 404); set(error, 'httpStatus', 404);
throw error; throw error;
} }

View File

@ -1,8 +1,8 @@
/* eslint-disable */ /* eslint-disable */
import AdapterError from '@ember-data/adapter/error';
import { isEmpty } from '@ember/utils'; import { isEmpty } from '@ember/utils';
import { get } from '@ember/object'; import { get } from '@ember/object';
import ApplicationAdapter from './application'; import ApplicationAdapter from './application';
import DS from 'ember-data';
import { encodePath } from 'vault/utils/path-encoding-helpers'; import { encodePath } from 'vault/utils/path-encoding-helpers';
import ControlGroupError from 'vault/lib/control-group-error'; import ControlGroupError from 'vault/lib/control-group-error';
@ -30,7 +30,7 @@ export default ApplicationAdapter.extend({
return this._super(...arguments).catch(errorOrModel => { return this._super(...arguments).catch(errorOrModel => {
// if the response is a real 404 or if the secret is gated by a control group this will be an error, // if the response is a real 404 or if the secret is gated by a control group this will be an error,
// otherwise the response will be the body of a deleted / destroyed version // otherwise the response will be the body of a deleted / destroyed version
if (errorOrModel instanceof DS.AdapterError) { if (errorOrModel instanceof AdapterError) {
throw errorOrModel; throw errorOrModel;
} }
return errorOrModel; return errorOrModel;

View File

@ -8,14 +8,17 @@ export default ApplicationAdapter.extend({
createOrUpdate(store, type, snapshot, requestType) { createOrUpdate(store, type, snapshot, requestType) {
const serializer = store.serializerFor(type.modelName); const serializer = store.serializerFor(type.modelName);
const data = serializer.serialize(snapshot, requestType); const data = serializer.serialize(snapshot, requestType);
const { id } = snapshot; let name = snapshot.attr('name');
let url = this.urlForSecret(snapshot.record.get('backend'), id); let url = this.urlForSecret(snapshot.record.get('backend'), name);
if (requestType === 'update') { if (requestType === 'update') {
url = url + '/config'; url = url + '/config';
} }
return this.ajax(url, 'POST', { data }); return this.ajax(url, 'POST', { data }).then(resp => {
let response = resp || {};
response.id = name;
return response;
});
}, },
createRecord() { createRecord() {

View File

@ -1,19 +1,15 @@
import Application from '@ember/application'; import Application from '@ember/application';
import Resolver from './resolver'; import Resolver from 'ember-resolver';
import loadInitializers from 'ember-load-initializers'; import loadInitializers from 'ember-load-initializers';
import config from './config/environment'; import config from 'vault/config/environment';
import defineModifier from 'ember-concurrency-test-waiter/define-modifier'; import defineModifier from 'ember-concurrency-test-waiter/define-modifier';
defineModifier(); defineModifier();
export default class App extends Application {
let App; modulePrefix = config.modulePrefix;
podModulePrefix = config.podModulePrefix;
/* eslint-disable ember/avoid-leaking-state-in-ember-objects */ Resolver = Resolver;
App = Application.extend({ engines = {
modulePrefix: config.modulePrefix,
podModulePrefix: config.podModulePrefix,
Resolver,
engines: {
openApiExplorer: { openApiExplorer: {
dependencies: { dependencies: {
services: ['auth', 'flash-messages', 'namespace', 'router', 'version'], services: ['auth', 'flash-messages', 'namespace', 'router', 'version'],
@ -54,9 +50,7 @@ App = Application.extend({
}, },
}, },
}, },
}, };
}); }
loadInitializers(App, config.modulePrefix); loadInitializers(App, config.modulePrefix);
export default App;

View File

@ -1,7 +1,7 @@
import AdapterError from '@ember-data/adapter/error';
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import Component from '@ember/component'; import Component from '@ember/component';
import { task } from 'ember-concurrency'; import { task } from 'ember-concurrency';
import DS from 'ember-data';
/** /**
* @module AuthConfigForm/Config * @module AuthConfigForm/Config
@ -29,7 +29,7 @@ const AuthConfigBase = Component.extend({
} catch (err) { } catch (err) {
// AdapterErrors are handled by the error-message component // AdapterErrors are handled by the error-message component
// in the form // in the form
if (err instanceof DS.AdapterError === false) { if (err instanceof AdapterError === false) {
throw err; throw err;
} }
return; return;

View File

@ -1,7 +1,7 @@
import AdapterError from '@ember-data/adapter/error';
import AuthConfigComponent from './config'; import AuthConfigComponent from './config';
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import { task } from 'ember-concurrency'; import { task } from 'ember-concurrency';
import DS from 'ember-data';
/** /**
* @module AuthConfigForm/Options * @module AuthConfigForm/Options
@ -27,7 +27,7 @@ export default AuthConfigComponent.extend({
} catch (err) { } catch (err) {
// AdapterErrors are handled by the error-message component // AdapterErrors are handled by the error-message component
// in the form // in the form
if (err instanceof DS.AdapterError === false) { if (err instanceof AdapterError === false) {
throw err; throw err;
} }
// because we're not calling model.save the model never updates with // because we're not calling model.save the model never updates with

View File

@ -0,0 +1,3 @@
import Component from '@ember/component';
export default Component.extend({});

View File

@ -89,8 +89,8 @@ export default Component.extend(DEFAULTS, {
// set `with` to the first method // set `with` to the first method
if ( if (
!this.wrappedToken && !this.wrappedToken &&
((this.get('fetchMethods.isIdle') && firstMethod && !this.get('selectedAuth')) || ((this.fetchMethods.isIdle && firstMethod && !this.selectedAuth) ||
(this.get('selectedAuth') && !this.get('selectedAuthBackend'))) (this.selectedAuth && !this.selectedAuthBackend))
) { ) {
this.set('selectedAuth', firstMethod); this.set('selectedAuth', firstMethod);
} }
@ -98,7 +98,7 @@ export default Component.extend(DEFAULTS, {
}, },
firstMethod() { firstMethod() {
let firstMethod = this.get('methodsToShow.firstObject'); let firstMethod = this.methodsToShow.firstObject;
if (!firstMethod) return; if (!firstMethod) return;
// prefer backends with a path over those with a type // prefer backends with a path over those with a type
return get(firstMethod, 'path') || get(firstMethod, 'type'); return get(firstMethod, 'path') || get(firstMethod, 'type');
@ -127,8 +127,11 @@ export default Component.extend(DEFAULTS, {
} }
), ),
providerPartialName: computed('selectedAuthBackend', function() { providerPartialName: computed('selectedAuthBackend.type', function() {
let type = this.get('selectedAuthBackend.type') || 'token'; if (!this.selectedAuthBackend) {
return;
}
let type = this.selectedAuthBackend.type || 'token';
type = type.toLowerCase(); type = type.toLowerCase();
let templateName = dasherize(type); let templateName = dasherize(type);
return `partials/auth-form/${templateName}`; return `partials/auth-form/${templateName}`;
@ -139,16 +142,16 @@ export default Component.extend(DEFAULTS, {
cspErrorText: `This is a standby Vault node but can't communicate with the active node via request forwarding. Sign in at the active node to use the Vault UI.`, cspErrorText: `This is a standby Vault node but can't communicate with the active node via request forwarding. Sign in at the active node to use the Vault UI.`,
allSupportedMethods: computed('methodsToShow', 'hasMethodsWithPath', function() { allSupportedMethods: computed('methodsToShow', 'hasMethodsWithPath', function() {
let hasMethodsWithPath = this.get('hasMethodsWithPath'); let hasMethodsWithPath = this.hasMethodsWithPath;
let methodsToShow = this.get('methodsToShow'); let methodsToShow = this.methodsToShow;
return hasMethodsWithPath ? methodsToShow.concat(BACKENDS) : methodsToShow; return hasMethodsWithPath ? methodsToShow.concat(BACKENDS) : methodsToShow;
}), }),
hasMethodsWithPath: computed('methodsToShow', function() { hasMethodsWithPath: computed('methodsToShow', function() {
return this.get('methodsToShow').isAny('path'); return this.methodsToShow.isAny('path');
}), }),
methodsToShow: computed('methods', function() { methodsToShow: computed('methods', function() {
let methods = this.get('methods') || []; let methods = this.methods || [];
let shownMethods = methods.filter(m => let shownMethods = methods.filter(m =>
BACKENDS.find(b => get(b, 'type').toLowerCase() === get(m, 'type').toLowerCase()) BACKENDS.find(b => get(b, 'type').toLowerCase() === get(m, 'type').toLowerCase())
); );
@ -158,7 +161,7 @@ export default Component.extend(DEFAULTS, {
unwrapToken: task(function*(token) { unwrapToken: task(function*(token) {
// will be using the Token Auth Method, so set it here // will be using the Token Auth Method, so set it here
this.set('selectedAuth', 'token'); this.set('selectedAuth', 'token');
let adapter = this.get('store').adapterFor('tools'); let adapter = this.store.adapterFor('tools');
try { try {
let response = yield adapter.toolAction('unwrap', null, { clientToken: token }); let response = yield adapter.toolAction('unwrap', null, { clientToken: token });
this.set('token', response.auth.client_token); this.set('token', response.auth.client_token);
@ -169,7 +172,7 @@ export default Component.extend(DEFAULTS, {
}).withTestWaiter(), }).withTestWaiter(),
fetchMethods: task(function*() { fetchMethods: task(function*() {
let store = this.get('store'); let store = this.store;
try { try {
let methods = yield store.findAll('auth-method', { let methods = yield store.findAll('auth-method', {
adapterOptions: { adapterOptions: {
@ -249,7 +252,7 @@ export default Component.extend(DEFAULTS, {
this.setProperties({ this.setProperties({
error: null, error: null,
}); });
let backend = this.get('selectedAuthBackend') || {}; let backend = this.selectedAuthBackend || {};
let backendMeta = BACKENDS.find( let backendMeta = BACKENDS.find(
b => (get(b, 'type') || '').toLowerCase() === (get(backend, 'type') || '').toLowerCase() b => (get(b, 'type') || '').toLowerCase() === (get(backend, 'type') || '').toLowerCase()
); );
@ -259,8 +262,8 @@ export default Component.extend(DEFAULTS, {
if (passedData) { if (passedData) {
data = assign(data, passedData); data = assign(data, passedData);
} }
if (this.get('customPath') || get(backend, 'id')) { if (this.customPath || get(backend, 'id')) {
data.path = this.get('customPath') || get(backend, 'id'); data.path = this.customPath || get(backend, 'id');
} }
return this.authenticate.unlinked().perform(backend.type, data); return this.authenticate.unlinked().perform(backend.type, data);
}, },

View File

@ -1,8 +1,7 @@
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import { or } from '@ember/object/computed'; import { or, alias } from '@ember/object/computed';
import Component from '@ember/component'; import Component from '@ember/component';
import { run } from '@ember/runloop'; import { run } from '@ember/runloop';
import { computed } from '@ember/object';
export default Component.extend({ export default Component.extend({
auth: service(), auth: service(),
@ -11,35 +10,33 @@ export default Component.extend({
version: service(), version: service(),
transitionToRoute: function() { transitionToRoute: function() {
this.get('router').transitionTo(...arguments); this.router.transitionTo(...arguments);
}, },
classNames: 'user-menu auth-info', classNames: 'user-menu auth-info',
isRenewing: or('fakeRenew', 'auth.isRenewing'), isRenewing: or('fakeRenew', 'auth.isRenewing'),
canExpire: computed.alias('auth.allowExpiration'), canExpire: alias('auth.allowExpiration'),
isOSS: computed.alias('version.isOSS'), isOSS: alias('version.isOSS'),
actions: { actions: {
restartGuide() { restartGuide() {
this.get('wizard').restartGuide(); this.wizard.restartGuide();
}, },
renewToken() { renewToken() {
this.set('fakeRenew', true); this.set('fakeRenew', true);
run.later(() => { run.later(() => {
this.set('fakeRenew', false); this.set('fakeRenew', false);
this.get('auth').renew(); this.auth.renew();
}, 200); }, 200);
}, },
revokeToken() { revokeToken() {
this.get('auth') this.auth.revokeCurrentToken().then(() => {
.revokeCurrentToken() this.transitionToRoute('vault.cluster.logout');
.then(() => { });
this.transitionToRoute('vault.cluster.logout');
});
}, },
}, },
}); });

View File

@ -1,7 +1,7 @@
import { equal } from '@ember/object/computed'; import { equal } from '@ember/object/computed';
import { isBlank } from '@ember/utils'; import { isBlank } from '@ember/utils';
import Component from '@ember/component'; import Component from '@ember/component';
import { set, get, computed } from '@ember/object'; import { set, computed } from '@ember/object';
import { encodeString, decodeString } from 'vault/utils/b64'; import { encodeString, decodeString } from 'vault/utils/b64';
const B64 = 'base64'; const B64 = 'base64';
@ -83,40 +83,40 @@ export default Component.extend({
* @type boolean * @type boolean
*/ */
valuesMatch: computed('value', '_value', function() { valuesMatch: computed('value', '_value', function() {
const { value, _value } = this.getProperties('value', '_value'); const { value, _value } = this;
const anyBlank = isBlank(value) || isBlank(_value); const anyBlank = isBlank(value) || isBlank(_value);
return !anyBlank && value === _value; return !anyBlank && value === _value;
}), }),
init() { init() {
this._super(...arguments); this._super(...arguments);
const initial = get(this, 'initialEncoding'); const initial = this.initialEncoding;
set(this, 'currentEncoding', initial); set(this, 'currentEncoding', initial);
if (initial === B64) { if (initial === B64) {
set(this, '_value', get(this, 'value')); set(this, '_value', this.value);
set(this, 'lastEncoding', B64); set(this, 'lastEncoding', B64);
} }
}, },
didReceiveAttrs() { didReceiveAttrs() {
// if there's no value, reset encoding // if there's no value, reset encoding
if (get(this, 'value') === '') { if (this.value === '') {
set(this, 'currentEncoding', UTF8); set(this, 'currentEncoding', UTF8);
return; return;
} }
// the value has changed after we transformed it so we reset currentEncoding // the value has changed after we transformed it so we reset currentEncoding
if (get(this, 'isBase64') && !get(this, 'valuesMatch')) { if (this.isBase64 && !this.valuesMatch) {
set(this, 'currentEncoding', UTF8); set(this, 'currentEncoding', UTF8);
} }
// the value changed back to one we previously had transformed // the value changed back to one we previously had transformed
if (get(this, 'lastEncoding') === B64 && get(this, 'valuesMatch')) { if (this.lastEncoding === B64 && this.valuesMatch) {
set(this, 'currentEncoding', B64); set(this, 'currentEncoding', B64);
} }
}, },
click() { click() {
let val = get(this, 'value'); let val = this.value;
const isUTF8 = get(this, 'currentEncoding') === UTF8; const isUTF8 = this.currentEncoding === UTF8;
if (!val) { if (!val) {
return; return;
} }

View File

@ -68,7 +68,7 @@ export default Component.extend({
loading: false, loading: false,
willDestroy() { willDestroy() {
const ca = this.get('model'); const ca = this.model;
if (ca) { if (ca) {
ca.unloadRecord(); ca.unloadRecord();
} }
@ -76,9 +76,9 @@ export default Component.extend({
}, },
createOrReplaceModel(modelType) { createOrReplaceModel(modelType) {
const ca = this.get('model'); const ca = this.model;
const config = this.get('config'); const config = this.config;
const store = this.get('store'); const store = this.store;
const backend = config.get('backend'); const backend = config.get('backend');
if (ca) { if (ca) {
ca.unloadRecord(); ca.unloadRecord();
@ -101,8 +101,8 @@ export default Component.extend({
* *
*/ */
downloadHrefs: computed('config', 'config.{backend,pem,caChain,der}', function() { downloadHrefs: computed('config', 'config.{backend,pem,caChain,der}', function() {
const config = this.get('config'); const config = this.config;
const { backend, pem, caChain, der } = config.getProperties('backend', 'pem', 'caChain', 'der'); const { backend, pem, caChain, der } = config;
if (!pem) { if (!pem) {
return []; return [];
@ -135,17 +135,17 @@ export default Component.extend({
actions: { actions: {
saveCA(method) { saveCA(method) {
this.set('loading', true); this.set('loading', true);
const model = this.get('model'); const model = this.model;
const isUpload = this.get('model.uploadPemBundle'); const isUpload = this.model.uploadPemBundle;
model model
.save({ adapterOptions: { method } }) .save({ adapterOptions: { method } })
.then(m => { .then(m => {
if (method === 'setSignedIntermediate' || isUpload) { if (method === 'setSignedIntermediate' || isUpload) {
this.send('refresh'); this.send('refresh');
this.get('flashMessages').success('The certificate for this backend has been updated.'); this.flashMessages.success('The certificate for this backend has been updated.');
} else if (!m.get('certificate') && !m.get('csr')) { } else if (!m.get('certificate') && !m.get('csr')) {
// if there's no certificate, it wasn't generated and the generation was a noop // if there's no certificate, it wasn't generated and the generation was a noop
this.get('flashMessages').warning( this.flashMessages.warning(
'You tried to generate a new root CA, but one currently exists. To replace the existing one, delete it first and then generate again.' 'You tried to generate a new root CA, but one currently exists. To replace the existing one, delete it first and then generate again.'
); );
} }
@ -159,14 +159,14 @@ export default Component.extend({
}, },
deleteCA() { deleteCA() {
this.set('loading', true); this.set('loading', true);
const model = this.get('model'); const model = this.model;
const backend = model.get('backend'); const backend = model.get('backend');
//TODO Is there better way to do this? This forces the saved state so Ember Data will make a server call. //TODO Is there better way to do this? This forces the saved state so Ember Data will make a server call.
model.send('pushedData'); model.send('pushedData');
model model
.destroyRecord() .destroyRecord()
.then(() => { .then(() => {
this.get('flashMessages').success( this.flashMessages.success(
`The CA key for ${backend} has been deleted. The old CA certificate will still be accessible for reading until a new certificate/key are generated or uploaded.` `The CA key for ${backend} has been deleted. The old CA certificate will still be accessible for reading until a new certificate/key are generated or uploaded.`
); );
}) })
@ -182,10 +182,10 @@ export default Component.extend({
signIntermediate: false, signIntermediate: false,
replaceCA: false, replaceCA: false,
}); });
this.get('onRefresh')(); this.onRefresh();
}, },
toggleReplaceCA() { toggleReplaceCA() {
if (!this.get('replaceCA')) { if (!this.replaceCA) {
this.createOrReplaceModel(); this.createOrReplaceModel();
} }
this.toggleProperty('replaceCA'); this.toggleProperty('replaceCA');

View File

@ -39,7 +39,7 @@ export default Component.extend({
actions: { actions: {
save(section) { save(section) {
this.set('loading', true); this.set('loading', true);
const config = this.get('config'); const config = this.config;
config config
.save({ .save({
adapterOptions: { adapterOptions: {
@ -48,7 +48,7 @@ export default Component.extend({
}, },
}) })
.then(() => { .then(() => {
this.get('flashMessages').success(`The ${section} config for this backend has been updated.`); this.flashMessages.success(`The ${section} config for this backend has been updated.`);
// attrs aren't persistent for Tidy // attrs aren't persistent for Tidy
if (section === 'tidy') { if (section === 'tidy') {
config.rollbackAttributes(); config.rollbackAttributes();
@ -63,7 +63,7 @@ export default Component.extend({
}); });
}, },
refresh() { refresh() {
this.get('onRefresh')(); this.onRefresh();
}, },
}, },
}); });

View File

@ -14,18 +14,18 @@ export default Component.extend({
const keyCode = event.keyCode; const keyCode = event.keyCode;
switch (keyCode) { switch (keyCode) {
case keys.ENTER: case keys.ENTER:
this.get('onExecuteCommand')(event.target.value); this.onExecuteCommand(event.target.value);
break; break;
case keys.UP: case keys.UP:
case keys.DOWN: case keys.DOWN:
this.get('onShiftCommand')(keyCode); this.onShiftCommand(keyCode);
break; break;
default: default:
this.get('onValueUpdate')(event.target.value); this.onValueUpdate(event.target.value);
} }
}, },
fullscreen() { fullscreen() {
this.get('onFullscreen')(); this.onFullscreen();
}, },
}, },
}); });

View File

@ -0,0 +1,3 @@
import Component from '@ember/component';
export default Component.extend({});

View File

@ -1,9 +1,7 @@
import { reads } from '@ember/object/computed';
import Component from '@ember/component'; import Component from '@ember/component';
import { computed } from '@ember/object';
export default Component.extend({ export default Component.extend({
content: null, content: null,
list: computed('content', function() { list: reads('content.keys'),
return this.get('content').keys;
}),
}); });

View File

@ -16,7 +16,7 @@ export function stringifyObjectValues(data) {
export default Component.extend({ export default Component.extend({
content: null, content: null,
columns: computed('content', function() { columns: computed('content', function() {
let data = this.get('content'); let data = this.content;
stringifyObjectValues(data); stringifyObjectValues(data);
return columnify(data, { return columnify(data, {

View File

@ -25,7 +25,7 @@ export default Component.extend({
classNameBindings: ['isFullscreen:fullscreen'], classNameBindings: ['isFullscreen:fullscreen'],
isFullscreen: false, isFullscreen: false,
inputValue: null, inputValue: null,
log: alias('console.log'), cliLog: alias('console.log'),
didRender() { didRender() {
this._super(...arguments); this._super(...arguments);
@ -33,7 +33,7 @@ export default Component.extend({
}, },
logAndOutput(command, logContent) { logAndOutput(command, logContent) {
this.get('console').logAndOutput(command, logContent); this.console.logAndOutput(command, logContent);
run.schedule('afterRender', () => this.scrollToBottom()); run.schedule('afterRender', () => this.scrollToBottom());
}, },
@ -41,7 +41,7 @@ export default Component.extend({
executeCommand: task(function*(command, shouldThrow = false) { executeCommand: task(function*(command, shouldThrow = false) {
this.set('inputValue', ''); this.set('inputValue', '');
let service = this.get('console'); let service = this.console;
let serviceArgs; let serviceArgs;
if ( if (
@ -84,7 +84,7 @@ export default Component.extend({
this.logAndOutput(command, logFromResponse(resp, path, method, flags)); this.logAndOutput(command, logFromResponse(resp, path, method, flags));
} catch (error) { } catch (error) {
if (error instanceof ControlGroupError) { if (error instanceof ControlGroupError) {
return this.logAndOutput(command, this.get('controlGroup').logFromError(error)); return this.logAndOutput(command, this.controlGroup.logFromError(error));
} }
this.logAndOutput(command, logFromError(error, path, method)); this.logAndOutput(command, logFromError(error, path, method));
} }
@ -92,11 +92,11 @@ export default Component.extend({
refreshRoute: task(function*() { refreshRoute: task(function*() {
let owner = getOwner(this); let owner = getOwner(this);
let routeName = this.get('router.currentRouteName'); let routeName = this.router.currentRouteName;
let route = owner.lookup(`route:${routeName}`); let route = owner.lookup(`route:${routeName}`);
try { try {
this.get('store').clearAllDatasets(); this.store.clearAllDatasets();
yield route.refresh(); yield route.refresh();
this.logAndOutput(null, { type: 'success', content: 'The current screen has been refreshed!' }); this.logAndOutput(null, { type: 'success', content: 'The current screen has been refreshed!' });
} catch (error) { } catch (error) {
@ -128,7 +128,7 @@ export default Component.extend({
}), }),
shiftCommandIndex(keyCode) { shiftCommandIndex(keyCode) {
this.get('console').shiftCommandIndex(keyCode, val => { this.console.shiftCommandIndex(keyCode, val => {
this.set('inputValue', val); this.set('inputValue', val);
}); });
}, },
@ -145,7 +145,7 @@ export default Component.extend({
this.toggleProperty('isFullscreen'); this.toggleProperty('isFullscreen');
}, },
executeCommand(val) { executeCommand(val) {
this.get('executeCommand').perform(val, true); this.executeCommand.perform(val, true);
}, },
shiftCommandIndex(direction) { shiftCommandIndex(direction) {
this.shiftCommandIndex(direction); this.shiftCommandIndex(direction);

View File

@ -16,20 +16,20 @@ export default Component.extend({
unwrapData: null, unwrapData: null,
unwrap: task(function*(token) { unwrap: task(function*(token) {
let adapter = this.get('store').adapterFor('tools'); let adapter = this.store.adapterFor('tools');
this.set('error', null); this.set('error', null);
try { try {
let response = yield adapter.toolAction('unwrap', null, { clientToken: token }); let response = yield adapter.toolAction('unwrap', null, { clientToken: token });
this.set('unwrapData', response.auth || response.data); this.set('unwrapData', response.auth || response.data);
this.get('controlGroup').deleteControlGroupToken(this.get('model.id')); this.controlGroup.deleteControlGroupToken(this.model.id);
} catch (e) { } catch (e) {
this.set('error', `Token unwrap failed: ${e.errors[0]}`); this.set('error', `Token unwrap failed: ${e.errors[0]}`);
} }
}).drop(), }).drop(),
markAndNavigate: task(function*() { markAndNavigate: task(function*() {
this.get('controlGroup').markTokenForUnwrap(this.get('model.id')); this.controlGroup.markTokenForUnwrap(this.model.id);
let { url } = this.get('controlGroupResponse.uiParams'); let { url } = this.controlGroupResponse.uiParams;
yield this.get('router').transitionTo(url); yield this.router.transitionTo(url);
}).drop(), }).drop(),
}); });

View File

@ -14,27 +14,28 @@ export default Component.extend({
didReceiveAttrs() { didReceiveAttrs() {
this._super(...arguments); this._super(...arguments);
let accessor = this.get('model.id'); let accessor = this.model.id;
let data = this.get('controlGroup').wrapInfoForAccessor(accessor); let data = this.controlGroup.wrapInfoForAccessor(accessor);
this.set('controlGroupResponse', data); this.set('controlGroupResponse', data);
}, },
currentUserEntityId: alias('auth.authData.entity_id'), currentUserEntityId: alias('auth.authData.entity_id'),
currentUserIsRequesting: computed('currentUserEntityId', 'model.requestEntity.id', function() { currentUserIsRequesting: computed('currentUserEntityId', 'model.requestEntity.id', function() {
return this.get('currentUserEntityId') === this.get('model.requestEntity.id'); if (!this.model.requestEntity) return false;
return this.currentUserEntityId === this.model.requestEntity.id;
}), }),
currentUserHasAuthorized: computed('currentUserEntityId', 'model.authorizations.@each.id', function() { currentUserHasAuthorized: computed('currentUserEntityId', 'model.authorizations.@each.id', function() {
let authorizations = this.get('model.authorizations') || []; let authorizations = this.model.authorizations || [];
return Boolean(authorizations.findBy('id', this.get('currentUserEntityId'))); return Boolean(authorizations.findBy('id', this.currentUserEntityId));
}), }),
isSuccess: or('currentUserHasAuthorized', 'model.approved'), isSuccess: or('currentUserHasAuthorized', 'model.approved'),
requestorName: computed('currentUserIsRequesting', 'model.requestEntity', function() { requestorName: computed('currentUserIsRequesting', 'model.requestEntity', function() {
let entity = this.get('model.requestEntity'); let entity = this.model.requestEntity;
if (this.get('currentUserIsRequesting')) { if (this.currentUserIsRequesting) {
return 'You'; return 'You';
} }
if (entity && get(entity, 'name')) { if (entity && get(entity, 'name')) {
@ -44,21 +45,18 @@ export default Component.extend({
}), }),
bannerPrefix: computed('model.approved', 'currentUserHasAuthorized', function() { bannerPrefix: computed('model.approved', 'currentUserHasAuthorized', function() {
if (this.get('currentUserHasAuthorized')) { if (this.currentUserHasAuthorized) {
return 'Thanks!'; return 'Thanks!';
} }
if (this.get('model.approved')) { if (this.model.approved) {
return 'Success!'; return 'Success!';
} }
return 'Locked'; return 'Locked';
}), }),
bannerText: computed('model.approved', 'currentUserIsRequesting', 'currentUserHasAuthorized', function() { bannerText: computed('model.approved', 'currentUserIsRequesting', 'currentUserHasAuthorized', function() {
let isApproved = this.get('model.approved'); let isApproved = this.model.approved;
let { currentUserHasAuthorized, currentUserIsRequesting } = this.getProperties( let { currentUserHasAuthorized, currentUserIsRequesting } = this;
'currentUserIsRequesting',
'currentUserHasAuthorized'
);
if (currentUserHasAuthorized) { if (currentUserHasAuthorized) {
return 'You have given authorization'; return 'You have given authorization';
} }
@ -76,7 +74,7 @@ export default Component.extend({
refresh: task(function*() { refresh: task(function*() {
try { try {
yield this.get('model').reload(); yield this.model.reload();
} catch (e) { } catch (e) {
this.set('errors', e); this.set('errors', e);
} }
@ -84,8 +82,8 @@ export default Component.extend({
authorize: task(function*() { authorize: task(function*() {
try { try {
yield this.get('model').save(); yield this.model.save();
yield this.get('refresh').perform(); yield this.refresh.perform();
} catch (e) { } catch (e) {
this.set('errors', e); this.set('errors', e);
} }

View File

@ -1,4 +1,4 @@
import { getWithDefault, computed } from '@ember/object'; import { computed } from '@ember/object';
import FlashMessage from 'ember-cli-flash/components/flash-message'; import FlashMessage from 'ember-cli-flash/components/flash-message';
export default FlashMessage.extend({ export default FlashMessage.extend({
@ -6,7 +6,7 @@ export default FlashMessage.extend({
//https://github.com/poteto/ember-cli-flash/blob/master/addon/components/flash-message.js#L35 //https://github.com/poteto/ember-cli-flash/blob/master/addon/components/flash-message.js#L35
alertType: computed('flash.type', { alertType: computed('flash.type', {
get() { get() {
const flashType = getWithDefault(this, 'flash.type', ''); const flashType = this.flash.type || '';
let prefix = 'is-'; let prefix = 'is-';
return `${prefix}${flashType}`; return `${prefix}${flashType}`;

View File

@ -40,17 +40,17 @@ export default Component.extend({
emptyData: '{\n}', emptyData: '{\n}',
modelForType() { modelForType() {
const type = this.get('options'); const type = this.options;
if (type) { if (type) {
return type.model; return type.model;
} }
// if we don't have a mode for that type then redirect them back to the backend list // if we don't have a mode for that type then redirect them back to the backend list
this.get('router').transitionTo('vault.cluster.secrets.backend.list-root', this.get('backendPath')); this.router.transitionTo('vault.cluster.secrets.backend.list-root', this.backendPath);
}, },
options: computed('action', 'backendType', function() { options: computed('action', 'backendType', function() {
const action = this.get('action') || 'creds'; const action = this.action || 'creds';
return MODEL_TYPES[`${this.get('backendType')}-${action}`]; return MODEL_TYPES[`${this.backendType}-${action}`];
}), }),
init() { init() {
@ -59,25 +59,21 @@ export default Component.extend({
}, },
didReceiveAttrs() { didReceiveAttrs() {
if (this.get('wizard.featureState') === 'displayRole') { if (this.wizard.featureState === 'displayRole') {
this.get('wizard').transitionFeatureMachine( this.wizard.transitionFeatureMachine(this.wizard.featureState, 'CONTINUE', this.backendType);
this.get('wizard.featureState'),
'CONTINUE',
this.get('backendType')
);
} }
}, },
willDestroy() { willDestroy() {
this.get('model').unloadRecord(); this.model.unloadRecord();
this._super(...arguments); this._super(...arguments);
}, },
createOrReplaceModel() { createOrReplaceModel() {
const modelType = this.modelForType(); const modelType = this.modelForType();
const model = this.get('model'); const model = this.model;
const roleName = this.get('roleName'); const roleName = this.roleName;
const backendPath = this.get('backendPath'); const backendPath = this.backendPath;
if (!modelType) { if (!modelType) {
return; return;
} }
@ -91,23 +87,19 @@ export default Component.extend({
}, },
id: `${backendPath}-${roleName}`, id: `${backendPath}-${roleName}`,
}; };
const newModel = this.get('store').createRecord(modelType, attrs); const newModel = this.store.createRecord(modelType, attrs);
this.set('model', newModel); this.set('model', newModel);
}, },
actions: { actions: {
create() { create() {
let model = this.get('model'); let model = this.model;
this.set('loading', true); this.set('loading', true);
this.model this.model
.save() .save()
.catch(() => { .catch(() => {
if (this.get('wizard.featureState') === 'credentials') { if (this.wizard.featureState === 'credentials') {
this.get('wizard').transitionFeatureMachine( this.wizard.transitionFeatureMachine(this.wizard.featureState, 'ERROR', this.backendType);
this.get('wizard.featureState'),
'ERROR',
this.get('backendType')
);
} }
}) })
.finally(() => { .finally(() => {
@ -121,7 +113,7 @@ export default Component.extend({
const hasErrors = codemirror.state.lint.marked.length > 0; const hasErrors = codemirror.state.lint.marked.length > 0;
if (!hasErrors) { if (!hasErrors) {
set(this.get('model'), attr, JSON.parse(val)); set(this.model, attr, JSON.parse(val));
} }
}, },

View File

@ -1,8 +1,8 @@
import AdapterError from '@ember-data/adapter/error';
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import Component from '@ember/component'; import Component from '@ember/component';
import { computed } from '@ember/object'; import { computed } from '@ember/object';
import { task } from 'ember-concurrency'; import { task } from 'ember-concurrency';
import DS from 'ember-data';
/** /**
* @module GeneratedItem * @module GeneratedItem
@ -24,7 +24,7 @@ export default Component.extend({
itemType: null, itemType: null,
flashMessages: service(), flashMessages: service(),
router: service(), router: service(),
props: computed(function() { props: computed('model', function() {
return this.model.serialize(); return this.model.serialize();
}), }),
saveModel: task(function*() { saveModel: task(function*() {
@ -33,7 +33,7 @@ export default Component.extend({
} catch (err) { } catch (err) {
// AdapterErrors are handled by the error-message component // AdapterErrors are handled by the error-message component
// in the form // in the form
if (err instanceof DS.AdapterError === false) { if (err instanceof AdapterError === false) {
throw err; throw err;
} }
return; return;

View File

@ -24,6 +24,6 @@ export default Component.extend({
}), }),
computedClasses: computed('classNames', function() { computedClasses: computed('classNames', function() {
return this.get('classNames').join(' '); return this.classNames.join(' ');
}), }),
}); });

View File

@ -29,12 +29,12 @@ export default Component.extend({
let messageArgs = this.messageArgs(...args); let messageArgs = this.messageArgs(...args);
return this.transaction(...args) return this.transaction(...args)
.then(() => { .then(() => {
this.get('onSuccess')(); this.onSuccess();
this.get('flashMessages').success(this.successMessage(...messageArgs)); this.flashMessages.success(this.successMessage(...messageArgs));
}) })
.catch(e => { .catch(e => {
this.onError(...messageArgs); this.onError(...messageArgs);
this.get('flashMessages').success(this.errorMessage(e, ...messageArgs)); this.flashMessages.success(this.errorMessage(e, ...messageArgs));
}); });
}, },
}, },

View File

@ -59,8 +59,8 @@ export default Component.extend({
// err will display via model state // err will display via model state
return; return;
} }
this.get('flashMessages').success(message); this.flashMessages.success(message);
yield this.get('onSave')({ saveType: 'save', model }); yield this.onSave({ saveType: 'save', model });
}) })
.drop() .drop()
.withTestWaiter(), .withTestWaiter(),
@ -76,10 +76,10 @@ export default Component.extend({
actions: { actions: {
deleteItem(model) { deleteItem(model) {
let message = this.getMessage(model, true); let message = this.getMessage(model, true);
let flash = this.get('flashMessages'); let flash = this.flashMessages;
model.destroyRecord().then(() => { model.destroyRecord().then(() => {
flash.success(message); flash.success(message);
return this.get('onSave')({ saveType: 'delete', model }); return this.onSave({ saveType: 'delete', model });
}); });
}, },
}, },

View File

@ -0,0 +1,3 @@
import Component from '@ember/component';
export default Component.extend({});

View File

@ -11,10 +11,10 @@ export default Component.extend({
model model
.save() .save()
.then(() => { .then(() => {
this.get('flashMessages').success(`Successfully enabled entity: ${model.id}`); this.flashMessages.success(`Successfully enabled entity: ${model.id}`);
}) })
.catch(e => { .catch(e => {
this.get('flashMessages').success( this.flashMessages.success(
`There was a problem enabling the entity: ${model.id} - ${e.errors.join(' ') || e.message}` `There was a problem enabling the entity: ${model.id} - ${e.errors.join(' ') || e.message}`
); );
}); });

View File

@ -20,26 +20,20 @@ export default Component.extend({
init() { init() {
this._super(...arguments); this._super(...arguments);
this.get('store') this.store.findAll('auth-method').then(methods => {
.findAll('auth-method') this.set('authMethods', methods);
.then(methods => { this.set('aliasMountAccessor', methods.get('firstObject.accessor'));
this.set('authMethods', methods); });
this.set('aliasMountAccessor', methods.get('firstObject.accessor'));
});
}, },
adapter() { adapter() {
let type = this.get('type'); let type = this.type;
let store = this.get('store'); let store = this.store;
return store.adapterFor(`identity/${type}`); return store.adapterFor(`identity/${type}`);
}, },
data() { data() {
let { param, paramValue, aliasMountAccessor } = this.getProperties( let { param, paramValue, aliasMountAccessor } = this;
'param',
'paramValue',
'aliasMountAccessor'
);
let data = {}; let data = {};
data[underscore([param])] = paramValue; data[underscore([param])] = paramValue;
@ -50,10 +44,10 @@ export default Component.extend({
}, },
lookup: task(function*() { lookup: task(function*() {
let flash = this.get('flashMessages'); let flash = this.flashMessages;
let type = this.get('type'); let type = this.type;
let store = this.get('store'); let store = this.store;
let { param, paramValue } = this.getProperties('param', 'paramValue'); let { param, paramValue } = this;
let response; let response;
try { try {
response = yield this.adapter().lookup(store, this.data()); response = yield this.adapter().lookup(store, this.data());
@ -64,7 +58,7 @@ export default Component.extend({
return; return;
} }
if (response) { if (response) {
return this.get('router').transitionTo('vault.cluster.access.identity.show', response.id, 'details'); return this.router.transitionTo('vault.cluster.access.identity.show', response.id, 'details');
} else { } else {
flash.danger(`We were unable to find an identity ${type} with a "${param}" of "${paramValue}".`); flash.danger(`We were unable to find an identity ${type} with a "${param}" of "${paramValue}".`);
} }

View File

@ -6,11 +6,11 @@ export default Base.extend({
model: alias('params.firstObject'), model: alias('params.firstObject'),
groupArray: computed('params', function() { groupArray: computed('params', function() {
return this.get('params').objectAt(1); return this.params.objectAt(1);
}), }),
memberId: computed('params', function() { memberId: computed('params', function() {
return this.get('params').objectAt(2); return this.params.objectAt(2);
}), }),
messageArgs(/*model, groupArray, memberId*/) { messageArgs(/*model, groupArray, memberId*/) {

View File

@ -5,7 +5,7 @@ import Base from './_popup-base';
export default Base.extend({ export default Base.extend({
model: alias('params.firstObject'), model: alias('params.firstObject'),
policyName: computed('params', function() { policyName: computed('params', function() {
return this.get('params').objectAt(1); return this.params.objectAt(1);
}), }),
messageArgs(model, policyName) { messageArgs(model, policyName) {

View File

@ -16,7 +16,7 @@ const JSON_EDITOR_DEFAULTS = {
export default IvyCodemirrorComponent.extend({ export default IvyCodemirrorComponent.extend({
'data-test-component': 'json-editor', 'data-test-component': 'json-editor',
updateCodeMirrorOptions() { updateCodeMirrorOptions() {
const options = assign({}, JSON_EDITOR_DEFAULTS, this.get('options')); const options = assign({}, JSON_EDITOR_DEFAULTS, this.options);
if (options.autoHeight) { if (options.autoHeight) {
options.viewportMargin = Infinity; options.viewportMargin = Infinity;
delete options.autoHeight; delete options.autoHeight;

View File

@ -18,7 +18,7 @@ export default Component.extend({
init() { init() {
this._super(...arguments); this._super(...arguments);
const data = KVObject.create({ content: [] }).fromJSON(this.get('value')); const data = KVObject.create({ content: [] }).fromJSON(this.value);
this.set('kvData', data); this.set('kvData', data);
this.addRow(); this.addRow();
}, },
@ -26,20 +26,20 @@ export default Component.extend({
kvData: null, kvData: null,
kvDataAsJSON: computed('kvData', 'kvData.[]', function() { kvDataAsJSON: computed('kvData', 'kvData.[]', function() {
return this.get('kvData').toJSON(); return this.kvData.toJSON();
}), }),
kvDataIsAdvanced: computed('kvData', 'kvData.[]', function() { kvDataIsAdvanced: computed('kvData', 'kvData.[]', function() {
return this.get('kvData').isAdvanced(); return this.kvData.isAdvanced();
}), }),
kvHasDuplicateKeys: computed('kvData', 'kvData.@each.name', function() { kvHasDuplicateKeys: computed('kvData', 'kvData.@each.name', function() {
let data = this.get('kvData'); let data = this.kvData;
return data.uniqBy('name').length !== data.get('length'); return data.uniqBy('name').length !== data.get('length');
}), }),
addRow() { addRow() {
let data = this.get('kvData'); let data = this.kvData;
let newObj = { name: '', value: '' }; let newObj = { name: '', value: '' };
if (!isNone(data.findBy('name', ''))) { if (!isNone(data.findBy('name', ''))) {
return; return;
@ -53,17 +53,17 @@ export default Component.extend({
}, },
updateRow() { updateRow() {
let data = this.get('kvData'); let data = this.kvData;
this.get('onChange')(data.toJSON()); this.onChange(data.toJSON());
}, },
deleteRow(object, index) { deleteRow(object, index) {
let data = this.get('kvData'); let data = this.kvData;
let oldObj = data.objectAt(index); let oldObj = data.objectAt(index);
assert('object guids match', guidFor(oldObj) === guidFor(object)); assert('object guids match', guidFor(oldObj) === guidFor(object));
data.removeAt(index); data.removeAt(index);
this.get('onChange')(data.toJSON()); this.onChange(data.toJSON());
}, },
}, },
}); });

View File

@ -1,3 +1,4 @@
import { equal } from '@ember/object/computed';
import Component from '@ember/component'; import Component from '@ember/component';
import { allFeatures } from 'vault/helpers/all-features'; import { allFeatures } from 'vault/helpers/all-features';
import { computed } from '@ember/object'; import { computed } from '@ember/object';
@ -10,10 +11,8 @@ export default Component.extend({
model: null, model: null,
text: '', text: '',
showForm: false, showForm: false,
isTemporary: computed('licenseId', function() { isTemporary: equal('licenseId', 'temporary'),
return this.licenseId === 'temporary'; featuresInfo: computed('features', 'model.performanceStandbyCount', function() {
}),
featuresInfo: computed('model', 'features', function() {
return allFeatures().map(feature => { return allFeatures().map(feature => {
let active = this.features.includes(feature); let active = this.features.includes(feature);
if (active && feature === 'Performance Standby') { if (active && feature === 'Performance Standby') {

View File

@ -12,12 +12,12 @@ export default Component.extend({
init() { init() {
this._super(...arguments); this._super(...arguments);
this.get('authMethods').perform(); this.authMethods.perform();
}, },
authMethods: task(function*() { authMethods: task(function*() {
let methods = yield this.get('store').findAll('auth-method'); let methods = yield this.store.findAll('auth-method');
if (!this.get('value')) { if (!this.value) {
this.set('value', methods.get('firstObject.accessor')); this.set('value', methods.get('firstObject.accessor'));
} }
return methods; return methods;
@ -25,7 +25,7 @@ export default Component.extend({
actions: { actions: {
change(value) { change(value) {
this.get('onChange')(value); this.onChange(value);
}, },
}, },
}); });

View File

@ -51,12 +51,12 @@ export default Component.extend({
this.set('mountModel', model); this.set('mountModel', model);
}, },
mountTypes: computed('mountType', function() { mountTypes: computed('engines', 'mountType', function() {
return this.mountType === 'secret' ? this.engines : METHODS; return this.mountType === 'secret' ? this.engines : METHODS;
}), }),
engines: computed('version.features[]', function() { engines: computed('version.{features[],isEnterprise}', function() {
if (this.get('version.isEnterprise')) { if (this.version.isEnterprise) {
return ENGINES.concat([KMIP, TRANSFORM]); return ENGINES.concat([KMIP, TRANSFORM]);
} }
return ENGINES; return ENGINES;
@ -64,7 +64,7 @@ export default Component.extend({
willDestroy() { willDestroy() {
// if unsaved, we want to unload so it doesn't show up in the auth mount list // if unsaved, we want to unload so it doesn't show up in the auth mount list
this.get('mountModel').rollbackAttributes(); this.mountModel.rollbackAttributes();
}, },
checkPathChange(type) { checkPathChange(type) {
@ -81,7 +81,7 @@ export default Component.extend({
mountBackend: task(function*() { mountBackend: task(function*() {
const mountModel = this.mountModel; const mountModel = this.mountModel;
const { type, path } = mountModel.getProperties('type', 'path'); const { type, path } = mountModel;
try { try {
yield mountModel.save(); yield mountModel.save();
} catch (err) { } catch (err) {

View File

@ -13,13 +13,13 @@ export default Component.extend({
showLastSegment: false, showLastSegment: false,
normalizedNamespace: computed('targetNamespace', function() { normalizedNamespace: computed('targetNamespace', function() {
let ns = this.get('targetNamespace'); let ns = this.targetNamespace;
return (ns || '').replace(/\.+/g, '/').replace(/☃/g, '.'); return (ns || '').replace(/\.+/g, '/').replace(/☃/g, '.');
}), }),
namespaceDisplay: computed('normalizedNamespace', 'showLastSegment', function() { namespaceDisplay: computed('normalizedNamespace', 'showLastSegment', function() {
let ns = this.get('normalizedNamespace'); let ns = this.normalizedNamespace;
let showLastSegment = this.get('showLastSegment'); let showLastSegment = this.showLastSegment;
let parts = ns.split('/'); let parts = ns.split('/');
if (ns === '') { if (ns === '') {
return 'root'; return 'root';
@ -28,6 +28,6 @@ export default Component.extend({
}), }),
isCurrentNamespace: computed('targetNamespace', 'currentNamespace', function() { isCurrentNamespace: computed('targetNamespace', 'currentNamespace', function() {
return this.get('currentNamespace') === this.get('targetNamespace'); return this.currentNamespace === this.targetNamespace;
}), }),
}); });

View File

@ -21,17 +21,17 @@ export default Component.extend({
init() { init() {
this._super(...arguments); this._super(...arguments);
this.get('namespaceService.findNamespacesForUser').perform(); this.namespaceService?.findNamespacesForUser.perform();
}, },
didReceiveAttrs() { didReceiveAttrs() {
this._super(...arguments); this._super(...arguments);
let ns = this.get('namespace'); let ns = this.namespace;
let oldNS = this.get('oldNamespace'); let oldNS = this.oldNamespace;
if (!oldNS || ns !== oldNS) { if (!oldNS || ns !== oldNS) {
this.get('setForAnimation').perform(); this.setForAnimation.perform();
this.get('fetchListCapability').perform(); this.fetchListCapability.perform();
} }
this.set('oldNamespace', ns); this.set('oldNamespace', ns);
}, },
@ -48,8 +48,8 @@ export default Component.extend({
} }
}), }),
setForAnimation: task(function*() { setForAnimation: task(function*() {
let leaves = this.get('menuLeaves'); let leaves = this.menuLeaves;
let lastLeaves = this.get('lastMenuLeaves'); let lastLeaves = this.lastMenuLeaves;
if (!lastLeaves) { if (!lastLeaves) {
this.set('lastMenuLeaves', leaves); this.set('lastMenuLeaves', leaves);
yield timeout(0); yield timeout(0);
@ -82,7 +82,7 @@ export default Component.extend({
inRootNamespace: alias('namespaceService.inRootNamespace'), inRootNamespace: alias('namespaceService.inRootNamespace'),
namespaceTree: computed('accessibleNamespaces', function() { namespaceTree: computed('accessibleNamespaces', function() {
let nsList = this.get('accessibleNamespaces'); let nsList = this.accessibleNamespaces;
if (!nsList) { if (!nsList) {
return []; return [];
@ -91,7 +91,7 @@ export default Component.extend({
}), }),
maybeAddRoot(leaves) { maybeAddRoot(leaves) {
let userRoot = this.get('auth.authData.userRootNamespace'); let userRoot = this.auth.authData.userRootNamespace;
if (userRoot === '') { if (userRoot === '') {
leaves.unshift(''); leaves.unshift('');
} }
@ -123,8 +123,8 @@ export default Component.extend({
// to render the nodes of each leaf // to render the nodes of each leaf
// gets set as 'lastMenuLeaves' in the ember concurrency task above // gets set as 'lastMenuLeaves' in the ember concurrency task above
menuLeaves: computed('namespacePath', 'namespaceTree', function() { menuLeaves: computed('namespacePath', 'namespaceTree', 'pathToLeaf', function() {
let ns = this.get('namespacePath'); let ns = this.namespacePath;
ns = ns.replace(/^\//, ''); ns = ns.replace(/^\//, '');
let leaves = ancestorKeysForKey(ns); let leaves = ancestorKeysForKey(ns);
leaves.push(ns); leaves.push(ns);
@ -137,7 +137,7 @@ export default Component.extend({
// the nodes at the root of the namespace tree // the nodes at the root of the namespace tree
// these will get rendered as the bottom layer // these will get rendered as the bottom layer
rootLeaves: computed('namespaceTree', function() { rootLeaves: computed('namespaceTree', function() {
let tree = this.get('namespaceTree'); let tree = this.namespaceTree;
let leaves = Object.keys(tree); let leaves = Object.keys(tree);
return leaves; return leaves;
}), }),
@ -145,11 +145,11 @@ export default Component.extend({
currentLeaf: alias('lastMenuLeaves.lastObject'), currentLeaf: alias('lastMenuLeaves.lastObject'),
canAccessMultipleNamespaces: gt('accessibleNamespaces.length', 1), canAccessMultipleNamespaces: gt('accessibleNamespaces.length', 1),
isUserRootNamespace: computed('auth.authData.userRootNamespace', 'namespacePath', function() { isUserRootNamespace: computed('auth.authData.userRootNamespace', 'namespacePath', function() {
return this.get('auth.authData.userRootNamespace') === this.get('namespacePath'); return this.auth.authData.userRootNamespace === this.namespacePath;
}), }),
namespaceDisplay: computed('namespacePath', 'accessibleNamespaces', 'accessibleNamespaces.[]', function() { namespaceDisplay: computed('namespacePath', 'accessibleNamespaces', 'accessibleNamespaces.[]', function() {
let namespace = this.get('namespacePath'); let namespace = this.namespacePath;
if (namespace === '') { if (namespace === '') {
return ''; return '';
} }
@ -159,7 +159,7 @@ export default Component.extend({
actions: { actions: {
refreshNamespaceList() { refreshNamespaceList() {
this.get('namespaceService.findNamespacesForUser').perform(); this.namespaceService.findNamespacesForUser.perform();
}, },
}, },
}); });

View File

@ -50,7 +50,7 @@ export default Component.extend({
// If after decoding it's not b64, we want // If after decoding it's not b64, we want
// the original as it was only encoded when we used `readAsDataURL`. // the original as it was only encoded when we used `readAsDataURL`.
const fileData = decoded.match(BASE_64_REGEX) ? decoded : b64File; const fileData = decoded.match(BASE_64_REGEX) ? decoded : b64File;
yield this.get('onChange')(this.get('index'), { value: fileData, fileName: filename }); yield this.onChange(this.index, { value: fileData, fileName: filename });
}).withTestWaiter(), }).withTestWaiter(),
actions: { actions: {
@ -64,12 +64,12 @@ export default Component.extend({
} }
}, },
updateData(e) { updateData(e) {
const key = this.get('key'); const key = this.key;
set(key, 'value', e.target.value); set(key, 'value', e.target.value);
this.get('onChange')(this.get('index'), this.get('key')); this.onChange(this.index, this.key);
}, },
clearKey() { clearKey() {
this.get('onChange')(this.get('index'), { value: '' }); this.onChange(this.index, { value: '' });
}, },
}, },
}); });

View File

@ -3,7 +3,7 @@ import RoleEdit from './role-edit';
export default RoleEdit.extend({ export default RoleEdit.extend({
actions: { actions: {
delete() { delete() {
this.get('model').save({ adapterOptions: { method: 'revoke' } }); this.model.save({ adapterOptions: { method: 'revoke' } });
}, },
}, },
}); });

View File

@ -69,7 +69,9 @@ export default Component.extend({
} }
}), }),
showResultsWarning: computed('resultStart', 'resultEnd', function() { // We don't want the warning to show when inputs are being updated before query is made
/* eslint-disable-next-line ember/require-computed-property-dependencies */
showResultsWarning: computed('resultEnd', 'resultStart', function() {
if (!this.queryStart || !this.queryEnd || !this.resultStart || !this.resultEnd) { if (!this.queryStart || !this.queryEnd || !this.resultStart || !this.resultEnd) {
return false; return false;
} }
@ -96,7 +98,7 @@ export default Component.extend({
return false; return false;
}), }),
error: computed('end', 'start', function() { error: computed('end', 'endDate', 'retentionMonths', 'start', 'startDate', function() {
if (!this.startDate) { if (!this.startDate) {
return 'Start date is invalid. Please use format MM/YYYY'; return 'Start date is invalid. Please use format MM/YYYY';
} }

View File

@ -11,19 +11,19 @@ export default Component.extend({
strokeWidth: 1, strokeWidth: 1,
viewBox: computed('size', function() { viewBox: computed('size', function() {
let s = this.get('size'); let s = this.size;
return `0 0 ${s} ${s}`; return `0 0 ${s} ${s}`;
}), }),
centerValue: computed('size', function() { centerValue: computed('size', function() {
return this.get('size') / 2; return this.size / 2;
}), }),
r: computed('size', 'strokeWidth', function() { r: computed('size', 'strokeWidth', function() {
return (this.get('size') - this.get('strokeWidth')) / 2; return (this.size - this.strokeWidth) / 2;
}), }),
c: computed('r', function() { c: computed('r', function() {
return 2 * Math.PI * this.get('r'); return 2 * Math.PI * this.r;
}), }),
dashArrayOffset: computed('c', 'progressDecimal', function() { dashArrayOffset: computed('c', 'progressDecimal', function() {
return this.get('c') * (1 - this.get('progressDecimal')); return this.c * (1 - this.progressDecimal);
}), }),
}); });

View File

@ -1,5 +1,5 @@
import { isBlank } from '@ember/utils'; import { isBlank } from '@ember/utils';
import { set, get } from '@ember/object'; import { set } from '@ember/object';
import RoleEdit from './role-edit'; import RoleEdit from './role-edit';
const SHOW_ROUTE = 'vault.cluster.secrets.backend.show'; const SHOW_ROUTE = 'vault.cluster.secrets.backend.show';
@ -8,14 +8,13 @@ export default RoleEdit.extend({
createOrUpdate(type, event) { createOrUpdate(type, event) {
event.preventDefault(); event.preventDefault();
const modelId = this.get('model.id'); const modelId = this.model.id;
// prevent from submitting if there's no key // prevent from submitting if there's no key
// maybe do something fancier later // maybe do something fancier later
if (type === 'create' && isBlank(modelId)) { if (type === 'create' && isBlank(modelId)) {
return; return;
} }
var credential_type = this.model.credential_type;
var credential_type = get(this, 'model.credential_type');
if (credential_type == 'iam_user') { if (credential_type == 'iam_user') {
set(this, 'model.role_arns', []); set(this, 'model.role_arns', []);
} }
@ -27,7 +26,7 @@ export default RoleEdit.extend({
set(this, 'model.policy_arns', []); set(this, 'model.policy_arns', []);
} }
var policy_document = get(this, 'model.policy_document'); var policy_document = this.model.policy_document;
if (policy_document == '{}') { if (policy_document == '{}') {
set(this, 'model.policy_document', ''); set(this, 'model.policy_document', '');
} }
@ -43,7 +42,7 @@ export default RoleEdit.extend({
const hasErrors = codemirror.state.lint.marked.length > 0; const hasErrors = codemirror.state.lint.marked.length > 0;
if (!hasErrors) { if (!hasErrors) {
set(this.get('model'), attr, val); set(this.model, attr, val);
} }
}, },
}, },

View File

@ -24,21 +24,13 @@ export default Component.extend(FocusOnInsertMixin, {
didReceiveAttrs() { didReceiveAttrs() {
this._super(...arguments); this._super(...arguments);
if ( if (
(this.get('wizard.featureState') === 'details' && this.get('mode') === 'create') || (this.wizard.featureState === 'details' && this.mode === 'create') ||
(this.get('wizard.featureState') === 'role' && this.get('mode') === 'show') (this.wizard.featureState === 'role' && this.mode === 'show')
) { ) {
this.get('wizard').transitionFeatureMachine( this.wizard.transitionFeatureMachine(this.wizard.featureState, 'CONTINUE', this.backendType);
this.get('wizard.featureState'),
'CONTINUE',
this.get('backendType')
);
} }
if (this.get('wizard.featureState') === 'displayRole') { if (this.wizard.featureState === 'displayRole') {
this.get('wizard').transitionFeatureMachine( this.wizard.transitionFeatureMachine(this.wizard.featureState, 'NOOP', this.backendType);
this.get('wizard.featureState'),
'NOOP',
this.get('backendType')
);
} }
}, },
@ -59,26 +51,26 @@ export default Component.extend(FocusOnInsertMixin, {
.cancelOn('willDestroyElement'), .cancelOn('willDestroyElement'),
transitionToRoute() { transitionToRoute() {
this.get('router').transitionTo(...arguments); this.router.transitionTo(...arguments);
}, },
onEscape(e) { onEscape(e) {
if (e.keyCode !== keys.ESC || this.get('mode') !== 'show') { if (e.keyCode !== keys.ESC || this.mode !== 'show') {
return; return;
} }
this.transitionToRoute(LIST_ROOT_ROUTE); this.transitionToRoute(LIST_ROOT_ROUTE);
}, },
hasDataChanges() { hasDataChanges() {
get(this, 'onDataChange')(get(this, 'model.hasDirtyAttributes')); this.onDataChange(this.model.hasDirtyAttributes);
}, },
persist(method, successCallback) { persist(method, successCallback) {
const model = get(this, 'model'); const model = this.model;
return model[method]().then(() => { return model[method]().then(() => {
if (!get(model, 'isError')) { if (!get(model, 'isError')) {
if (this.get('wizard.featureState') === 'role') { if (this.wizard.featureState === 'role') {
this.get('wizard').transitionFeatureMachine('role', 'CONTINUE', this.get('backendType')); this.wizard.transitionFeatureMachine('role', 'CONTINUE', this.backendType);
} }
successCallback(model); successCallback(model);
} }
@ -89,7 +81,7 @@ export default Component.extend(FocusOnInsertMixin, {
createOrUpdate(type, event) { createOrUpdate(type, event) {
event.preventDefault(); event.preventDefault();
const modelId = this.get('model.id'); const modelId = this.model.id;
// prevent from submitting if there's no key // prevent from submitting if there's no key
// maybe do something fancier later // maybe do something fancier later
if (type === 'create' && isBlank(modelId)) { if (type === 'create' && isBlank(modelId)) {
@ -103,11 +95,11 @@ export default Component.extend(FocusOnInsertMixin, {
}, },
setValue(key, event) { setValue(key, event) {
set(get(this, 'model'), key, event.target.checked); set(this.model, key, event.target.checked);
}, },
refresh() { refresh() {
this.get('onRefresh')(); this.onRefresh();
}, },
delete() { delete() {
@ -122,7 +114,7 @@ export default Component.extend(FocusOnInsertMixin, {
const hasErrors = codemirror.state.lint.marked.length > 0; const hasErrors = codemirror.state.lint.marked.length > 0;
if (!hasErrors) { if (!hasErrors) {
set(this.get('model'), attr, JSON.parse(val)); set(this.model, attr, JSON.parse(val));
} }
}, },
}, },

View File

@ -8,7 +8,7 @@ export default RoleEdit.extend({
actions: { actions: {
updateTtl(path, val) { updateTtl(path, val) {
const model = this.get('model'); const model = this.model;
let valueToSet = val.enabled === true ? `${val.seconds}s` : undefined; let valueToSet = val.enabled === true ? `${val.seconds}s` : undefined;
model.set(path, valueToSet); model.set(path, valueToSet);
}, },

View File

@ -2,7 +2,7 @@ import { isBlank, isNone } from '@ember/utils';
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import Component from '@ember/component'; import Component from '@ember/component';
import { computed, set } from '@ember/object'; import { computed, set } from '@ember/object';
import { alias, or } from '@ember/object/computed'; import { alias, or, not } from '@ember/object/computed';
import { task, waitForEvent } from 'ember-concurrency'; import { task, waitForEvent } from 'ember-concurrency';
import FocusOnInsertMixin from 'vault/mixins/focus-on-insert'; import FocusOnInsertMixin from 'vault/mixins/focus-on-insert';
import WithNavToNearestAncestor from 'vault/mixins/with-nav-to-nearest-ancestor'; import WithNavToNearestAncestor from 'vault/mixins/with-nav-to-nearest-ancestor';
@ -35,7 +35,7 @@ export default Component.extend(FocusOnInsertMixin, WithNavToNearestAncestor, {
wrappedData: null, wrappedData: null,
isWrapping: false, isWrapping: false,
showWrapButton: computed.not('wrappedData'), showWrapButton: not('wrappedData'),
// called with a bool indicating if there's been a change in the secretData // called with a bool indicating if there's been a change in the secretData
onDataChange() {}, onDataChange() {},
@ -154,9 +154,7 @@ export default Component.extend(FocusOnInsertMixin, WithNavToNearestAncestor, {
return this.secretData.isAdvanced(); return this.secretData.isAdvanced();
}), }),
showAdvancedMode: computed('preferAdvancedEdit', 'secretDataIsAdvanced', 'lastChange', function() { showAdvancedMode: or('secretDataIsAdvanced', 'preferAdvancedEdit'),
return this.secretDataIsAdvanced || this.preferAdvancedEdit;
}),
isWriteWithoutRead: computed('model.failedServerRead', 'modelForData.failedServerRead', 'isV2', function() { isWriteWithoutRead: computed('model.failedServerRead', 'modelForData.failedServerRead', 'isV2', function() {
if (!this.model) return; if (!this.model) return;

View File

@ -31,7 +31,7 @@ export default Component.extend({
ariaLabel: null, ariaLabel: null,
linkParams: computed('mode', 'secret', 'queryParams', function() { linkParams: computed('mode', 'secret', 'queryParams', function() {
let data = this.getProperties('mode', 'secret', 'queryParams'); let data = { mode: this.mode, secret: this.secret, queryParams: this.queryParams };
return linkParams(data); return linkParams(data);
}), }),
}); });

View File

@ -6,7 +6,7 @@ export default Component.extend({
progress: null, progress: null,
classNames: ['shamir-progress'], classNames: ['shamir-progress'],
progressDecimal: computed('threshold', 'progress', function() { progressDecimal: computed('threshold', 'progress', function() {
const { threshold, progress } = this.getProperties('threshold', 'progress'); const { threshold, progress } = this;
if (threshold && progress) { if (threshold && progress) {
return progress / threshold; return progress / threshold;
} }

View File

@ -9,6 +9,6 @@ export default Component.extend({
tagName: '', tagName: '',
activeCluster: computed('auth.activeCluster', function() { activeCluster: computed('auth.activeCluster', function() {
return this.get('store').peekRecord('cluster', this.get('auth.activeCluster')); return this.store.peekRecord('cluster', this.auth.activeCluster);
}), }),
}); });

View File

@ -1,5 +1,5 @@
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import { alias } from '@ember/object/computed'; import { alias, reads } from '@ember/object/computed';
import Component from '@ember/component'; import Component from '@ember/component';
import { computed } from '@ember/object'; import { computed } from '@ember/object';
@ -23,9 +23,7 @@ export default Component.extend({
return glyphs[this.type]; return glyphs[this.type];
}), }),
activeCluster: computed('auth.activeCluster', function() { activeCluster: computed('auth.activeCluster', function() {
return this.get('store').peekRecord('cluster', this.get('auth.activeCluster')); return this.store.peekRecord('cluster', this.auth.activeCluster);
}),
currentToken: computed('auth.currentToken', function() {
return this.get('auth.currentToken');
}), }),
currentToken: reads('auth.currentToken'),
}); });

View File

@ -59,7 +59,7 @@ export default Component.extend({
}, },
setFile(contents, filename) { setFile(contents, filename) {
this.get('onChange')(this.get('index'), { value: contents, fileName: filename }); this.onChange(this.index, { value: contents, fileName: filename });
}, },
actions: { actions: {
@ -73,12 +73,12 @@ export default Component.extend({
} }
}, },
updateData(e) { updateData(e) {
const file = this.get('file'); const file = this.file;
set(file, 'value', e.target.value); set(file, 'value', e.target.value);
this.get('onChange')(this.get('index'), this.get('file')); this.onChange(this.index, this.file);
}, },
clearFile() { clearFile() {
this.get('onChange')(this.get('index'), { value: '' }); this.onChange(this.index, { value: '' });
}, },
}, },
}); });

View File

@ -2,7 +2,7 @@ import { match } from '@ember/object/computed';
import { assign } from '@ember/polyfills'; import { assign } from '@ember/polyfills';
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import Component from '@ember/component'; import Component from '@ember/component';
import { setProperties, computed, set, get } from '@ember/object'; import { setProperties, computed, set } from '@ember/object';
import { addSeconds } from 'date-fns'; import { addSeconds } from 'date-fns';
const DEFAULTS = { const DEFAULTS = {
@ -51,8 +51,8 @@ export default Component.extend(DEFAULTS, {
}, },
checkAction() { checkAction() {
const currentAction = get(this, 'selectedAction'); const currentAction = this.selectedAction;
const oldAction = get(this, 'oldSelectedAction'); const oldAction = this.oldSelectedAction;
if (currentAction !== oldAction) { if (currentAction !== oldAction) {
this.reset(); this.reset();
@ -63,7 +63,7 @@ export default Component.extend(DEFAULTS, {
dataIsEmpty: match('data', new RegExp(DEFAULTS.data)), dataIsEmpty: match('data', new RegExp(DEFAULTS.data)),
expirationDate: computed('creation_time', 'creation_ttl', function() { expirationDate: computed('creation_time', 'creation_ttl', function() {
const { creation_time, creation_ttl } = this.getProperties('creation_time', 'creation_ttl'); const { creation_time, creation_ttl } = this;
if (!(creation_time && creation_ttl)) { if (!(creation_time && creation_ttl)) {
return null; return null;
} }
@ -93,32 +93,30 @@ export default Component.extend(DEFAULTS, {
props = assign({}, props, { [keyName]: resp.wrap_info.token }); props = assign({}, props, { [keyName]: resp.wrap_info.token });
} }
if (props.token || props.rewrap_token || props.unwrap_data || action === 'lookup') { if (props.token || props.rewrap_token || props.unwrap_data || action === 'lookup') {
this.get('wizard').transitionFeatureMachine(this.get('wizard.featureState'), 'CONTINUE'); this.wizard.transitionFeatureMachine(this.wizard.featureState, 'CONTINUE');
} }
setProperties(this, props); setProperties(this, props);
}, },
getData() { getData() {
const action = get(this, 'selectedAction'); const action = this.selectedAction;
if (WRAPPING_ENDPOINTS.includes(action)) { if (WRAPPING_ENDPOINTS.includes(action)) {
return get(this, 'dataIsEmpty') return this.dataIsEmpty ? { token: (this.token || '').trim() } : JSON.parse(this.data);
? { token: (get(this, 'token') || '').trim() }
: JSON.parse(get(this, 'data'));
} }
if (action === 'random') { if (action === 'random') {
return this.getProperties('bytes', 'format'); return { bytes: this.bytes, format: this.format };
} }
if (action === 'hash') { if (action === 'hash') {
return this.getProperties('input', 'format', 'algorithm'); return { input: this.input, format: this.format, algorithm: this.algorithm };
} }
}, },
actions: { actions: {
doSubmit(evt) { doSubmit(evt) {
evt.preventDefault(); evt.preventDefault();
const action = get(this, 'selectedAction'); const action = this.selectedAction;
const wrapTTL = action === 'wrap' ? get(this, 'wrapTTL') : null; const wrapTTL = action === 'wrap' ? this.wrapTTL : null;
const data = this.getData(); const data = this.getData();
setProperties(this, { setProperties(this, {
errors: null, errors: null,
@ -127,7 +125,7 @@ export default Component.extend(DEFAULTS, {
creation_ttl: null, creation_ttl: null,
}); });
get(this, 'store') this.store
.adapterFor('tools') .adapterFor('tools')
.toolAction(action, data, { wrapTTL }) .toolAction(action, data, { wrapTTL })
.then(resp => this.handleSuccess(resp, action), (...errArgs) => this.handleError(...errArgs)); .then(resp => this.handleSuccess(resp, action), (...errArgs) => this.handleError(...errArgs));

View File

@ -2,7 +2,7 @@ import { inject as service } from '@ember/service';
import { or } from '@ember/object/computed'; import { or } from '@ember/object/computed';
import { isBlank } from '@ember/utils'; import { isBlank } from '@ember/utils';
import Component from '@ember/component'; import Component from '@ember/component';
import { set, get } from '@ember/object'; import { set } from '@ember/object';
import FocusOnInsertMixin from 'vault/mixins/focus-on-insert'; import FocusOnInsertMixin from 'vault/mixins/focus-on-insert';
const LIST_ROOT_ROUTE = 'vault.cluster.secrets.backend.list-root'; const LIST_ROOT_ROUTE = 'vault.cluster.secrets.backend.list-root';
@ -66,7 +66,7 @@ export default Component.extend(FocusOnInsertMixin, {
}, },
persist(method, successCallback) { persist(method, successCallback) {
const model = get(this, 'model'); const model = this.model;
return model[method]() return model[method]()
.then(() => { .then(() => {
successCallback(model); successCallback(model);
@ -78,18 +78,17 @@ export default Component.extend(FocusOnInsertMixin, {
}, },
applyDelete(callback = () => {}) { applyDelete(callback = () => {}) {
const tab = this.listTabFromType(this.get('model.constructor.modelName')); const tab = this.listTabFromType(this.model.constructor.modelName);
this.persist('destroyRecord', () => { this.persist('destroyRecord', () => {
this.hasDataChanges(); this.hasDataChanges();
callback(); callback();
// TODO: Investigate what is causing a console error after this point
this.transitionToRoute(LIST_ROOT_ROUTE, { queryParams: { tab } }); this.transitionToRoute(LIST_ROOT_ROUTE, { queryParams: { tab } });
}); });
}, },
applyChanges(type, callback = () => {}) { applyChanges(type, callback = () => {}) {
const modelId = this.get('model.id') || this.get('model.name'); // transform comes in as model.name const modelId = this.model.id || this.model.name; // transform comes in as model.name
const modelPrefix = this.modelPrefixFromType(this.get('model.constructor.modelName')); const modelPrefix = this.modelPrefixFromType(this.model.constructor.modelName);
// prevent from submitting if there's no key // prevent from submitting if there's no key
// maybe do something fancier later // maybe do something fancier later
if (type === 'create' && isBlank(modelId)) { if (type === 'create' && isBlank(modelId)) {
@ -115,11 +114,11 @@ export default Component.extend(FocusOnInsertMixin, {
}, },
setValue(key, event) { setValue(key, event) {
set(get(this, 'model'), key, event.target.checked); set(this.model, key, event.target.checked);
}, },
refresh() { refresh() {
this.get('onRefresh')(); this.onRefresh();
}, },
delete() { delete() {

View File

@ -21,7 +21,7 @@ export default Component.extend({
itemType: '', itemType: '',
isBuiltin: computed('item', 'itemType', function() { isBuiltin: computed('item', 'itemType', function() {
const item = this.get('item'); const item = this.item;
if (this.itemType === 'alphabet' || this.itemType === 'template') { if (this.itemType === 'alphabet' || this.itemType === 'template') {
return item.get('id').startsWith('builtin/'); return item.get('id').startsWith('builtin/');
} }

View File

@ -5,12 +5,12 @@ export default TransformBase.extend({
init() { init() {
this._super(...arguments); this._super(...arguments);
this.set('initialTransformations', this.get('model.transformations')); this.set('initialTransformations', this.model.transformations);
}, },
handleUpdateTransformations(updateTransformations, roleId, type = 'update') { handleUpdateTransformations(updateTransformations, roleId, type = 'update') {
if (!updateTransformations) return; if (!updateTransformations) return;
const backend = this.get('model.backend'); const backend = this.model.backend;
const promises = updateTransformations.map(transform => { const promises = updateTransformations.map(transform => {
return this.store return this.store
.queryRecord('transform', { .queryRecord('transform', {
@ -57,7 +57,7 @@ export default TransformBase.extend({
message = message =
'This role was edited to remove transformations, but this role was not removed from those transformations allowed_roles due to a lack of permissions.'; 'This role was edited to remove transformations, but this role was not removed from those transformations allowed_roles due to a lack of permissions.';
} }
this.get('flashMessages').stickyInfo(message); this.flashMessages.stickyInfo(message);
} }
}); });
}, },
@ -67,8 +67,8 @@ export default TransformBase.extend({
event.preventDefault(); event.preventDefault();
this.applyChanges('save', () => { this.applyChanges('save', () => {
const roleId = this.get('model.id'); const roleId = this.model.id;
const newModelTransformations = this.get('model.transformations'); const newModelTransformations = this.model.transformations;
if (!this.initialTransformations) { if (!this.initialTransformations) {
this.handleUpdateTransformations( this.handleUpdateTransformations(

View File

@ -5,7 +5,8 @@ export default TransformBase.extend({
init() { init() {
this._super(...arguments); this._super(...arguments);
this.set('initialRoles', this.get('model.allowed_roles')); if (!this.model) return;
this.set('initialRoles', this.model.allowed_roles);
}, },
updateOrCreateRole(role, transformationId, backend) { updateOrCreateRole(role, transformationId, backend) {
@ -59,7 +60,7 @@ export default TransformBase.extend({
handleUpdateRoles(updateRoles, transformationId) { handleUpdateRoles(updateRoles, transformationId) {
if (!updateRoles) return; if (!updateRoles) return;
const backend = this.get('model.backend'); const backend = this.model.backend;
const promises = updateRoles.map(r => this.updateOrCreateRole(r, transformationId, backend)); const promises = updateRoles.map(r => this.updateOrCreateRole(r, transformationId, backend));
Promise.all(promises).then(results => { Promise.all(promises).then(results => {
@ -73,7 +74,7 @@ export default TransformBase.extend({
// eg. trying to update a role with empty array as transformations // eg. trying to update a role with empty array as transformations
message = `You've edited the allowed_roles for this transformation. However, the corresponding edits to some roles' transformations were not made`; message = `You've edited the allowed_roles for this transformation. However, the corresponding edits to some roles' transformations were not made`;
} }
this.get('flashMessages').stickyInfo(message); this.flashMessages.stickyInfo(message);
} }
}); });
}, },
@ -93,12 +94,12 @@ export default TransformBase.extend({
event.preventDefault(); event.preventDefault();
this.applyChanges('save', () => { this.applyChanges('save', () => {
const transformationId = this.get('model.id'); const transformationId = this.model.id;
const newModelRoles = this.get('model.allowed_roles') || []; const newModelRoles = this.model.allowed_roles || [];
const initialRoles = this.get('initialRoles') || []; const initialRoles = this.initialRoles || [];
const updateRoles = [...newModelRoles, ...initialRoles] const updateRoles = [...newModelRoles, ...initialRoles]
.filter(r => !this.isWildcard(r)) // TODO: expand wildcards into included roles instead .filter(r => !this.isWildcard(r)) // CBS TODO: expand wildcards into included roles instead
.map(role => { .map(role => {
if (initialRoles.indexOf(role) < 0) { if (initialRoles.indexOf(role) < 0) {
return { return {

View File

@ -37,29 +37,29 @@ export default Component.extend(FocusOnInsertMixin, {
.cancelOn('willDestroyElement'), .cancelOn('willDestroyElement'),
transitionToRoute() { transitionToRoute() {
this.get('router').transitionTo(...arguments); this.router.transitionTo(...arguments);
}, },
onEscape(e) { onEscape(e) {
if (e.keyCode !== keys.ESC || this.get('mode') !== 'show') { if (e.keyCode !== keys.ESC || this.mode !== 'show') {
return; return;
} }
this.transitionToRoute(LIST_ROOT_ROUTE); this.transitionToRoute(LIST_ROOT_ROUTE);
}, },
hasDataChanges() { hasDataChanges() {
get(this, 'onDataChange')(get(this, 'key.hasDirtyAttributes')); this.onDataChange(this.key.hasDirtyAttributes);
}, },
persistKey(method, successCallback) { persistKey(method, successCallback) {
const key = get(this, 'key'); const key = this.key;
return key[method]().then(() => { return key[method]().then(() => {
if (!get(key, 'isError')) { if (!get(key, 'isError')) {
if (this.get('wizard.featureState') === 'secret') { if (this.wizard.featureState === 'secret') {
this.get('wizard').transitionFeatureMachine('secret', 'CONTINUE'); this.wizard.transitionFeatureMachine('secret', 'CONTINUE');
} else { } else {
if (this.get('wizard.featureState') === 'encryption') { if (this.wizard.featureState === 'encryption') {
this.get('wizard').transitionFeatureMachine('encryption', 'CONTINUE', 'transit'); this.wizard.transitionFeatureMachine('encryption', 'CONTINUE', 'transit');
} }
} }
successCallback(key); successCallback(key);
@ -71,7 +71,7 @@ export default Component.extend(FocusOnInsertMixin, {
createOrUpdateKey(type, event) { createOrUpdateKey(type, event) {
event.preventDefault(); event.preventDefault();
const keyId = this.get('key.id'); const keyId = this.key.id || this.key.name;
// prevent from submitting if there's no key // prevent from submitting if there's no key
// maybe do something fancier later // maybe do something fancier later
if (type === 'create' && isBlank(keyId)) { if (type === 'create' && isBlank(keyId)) {
@ -89,19 +89,19 @@ export default Component.extend(FocusOnInsertMixin, {
}, },
setValueOnKey(key, event) { setValueOnKey(key, event) {
set(get(this, 'key'), key, event.target.checked); set(this.key, key, event.target.checked);
}, },
derivedChange(val) { derivedChange(val) {
get(this, 'key').setDerived(val); this.key.setDerived(val);
}, },
convergentEncryptionChange(val) { convergentEncryptionChange(val) {
get(this, 'key').setConvergentEncryption(val); this.key.setConvergentEncryption(val);
}, },
refresh() { refresh() {
this.get('onRefresh')(); this.onRefresh();
}, },
deleteKey() { deleteKey() {

View File

@ -65,9 +65,12 @@ export default Component.extend(TRANSIT_PARAMS, {
onRefresh() {}, onRefresh() {},
init() { init() {
this._super(...arguments); this._super(...arguments);
// TODO figure out why get is needed here Ember Upgrade
// eslint-disable-next-line ember/no-get
if (get(this, 'selectedAction')) { if (get(this, 'selectedAction')) {
return; return;
} }
// eslint-disable-next-line ember/no-get
set(this, 'selectedAction', get(this, 'key.supportedActions.firstObject')); set(this, 'selectedAction', get(this, 'key.supportedActions.firstObject'));
assert('`key` is required for `' + this.toString() + '`.', this.getModelInfo()); assert('`key` is required for `' + this.toString() + '`.', this.getModelInfo());
}, },
@ -75,14 +78,14 @@ export default Component.extend(TRANSIT_PARAMS, {
didReceiveAttrs() { didReceiveAttrs() {
this._super(...arguments); this._super(...arguments);
this.checkAction(); this.checkAction();
if (get(this, 'selectedAction') === 'export') { if (this.selectedAction === 'export') {
this.setExportKeyDefaults(); this.setExportKeyDefaults();
} }
}, },
setExportKeyDefaults() { setExportKeyDefaults() {
const exportKeyType = get(this, 'key.exportKeyTypes.firstObject'); const exportKeyType = this.key.exportKeyTypes.firstObject;
const exportKeyVersion = get(this, 'key.validKeyVersions.lastObject'); const exportKeyVersion = this.key.validKeyVersions.lastObject;
this.setProperties({ this.setProperties({
exportKeyType, exportKeyType,
exportKeyVersion, exportKeyVersion,
@ -90,12 +93,12 @@ export default Component.extend(TRANSIT_PARAMS, {
}, },
keyIsRSA: computed('key.type', function() { keyIsRSA: computed('key.type', function() {
let type = get(this, 'key.type'); let type = this.key.type;
return type === 'rsa-2048' || type === 'rsa-3072' || type === 'rsa-4096'; return type === 'rsa-2048' || type === 'rsa-3072' || type === 'rsa-4096';
}), }),
getModelInfo() { getModelInfo() {
const model = get(this, 'key') || get(this, 'backend'); const model = this.key || this.backend;
if (!model) { if (!model) {
return null; return null;
} }
@ -109,8 +112,8 @@ export default Component.extend(TRANSIT_PARAMS, {
}, },
checkAction() { checkAction() {
const currentAction = get(this, 'selectedAction'); const currentAction = this.selectedAction;
const oldAction = get(this, 'oldSelectedAction'); const oldAction = this.oldSelectedAction;
this.resetParams(oldAction, currentAction); this.resetParams(oldAction, currentAction);
set(this, 'oldSelectedAction', currentAction); set(this, 'oldSelectedAction', currentAction);
@ -124,7 +127,7 @@ export default Component.extend(TRANSIT_PARAMS, {
// don't save values from datakey // don't save values from datakey
oldAction === 'datakey' || oldAction === 'datakey' ||
// can rewrap signatures — using that as a ciphertext later would be problematic // can rewrap signatures — using that as a ciphertext later would be problematic
(oldAction === 'rewrap' && !get(this, 'key.supportsEncryption')); (oldAction === 'rewrap' && !this.key.supportsEncryption);
if (!clearWithoutCheck && action) { if (!clearWithoutCheck && action) {
paramsToKeep = PARAMS_FOR_ACTION[action]; paramsToKeep = PARAMS_FOR_ACTION[action];
@ -152,7 +155,7 @@ export default Component.extend(TRANSIT_PARAMS, {
triggerSuccessMessage(action) { triggerSuccessMessage(action) {
const message = SUCCESS_MESSAGE_FOR_ACTION[action]; const message = SUCCESS_MESSAGE_FOR_ACTION[action];
if (!message) return; if (!message) return;
this.get('flashMessages').success(message); this.flashMessages.success(message);
}, },
handleSuccess(resp, options, action) { handleSuccess(resp, options, action) {
@ -170,13 +173,13 @@ export default Component.extend(TRANSIT_PARAMS, {
this.toggleProperty('isModalActive'); this.toggleProperty('isModalActive');
this.setProperties(props); this.setProperties(props);
if (action === 'rotate') { if (action === 'rotate') {
this.get('onRefresh')(); this.onRefresh();
} }
this.triggerSuccessMessage(action); this.triggerSuccessMessage(action);
}, },
compactData(data) { compactData(data) {
let type = get(this, 'key.type'); let type = this.key.type;
let isRSA = type === 'rsa-2048' || type === 'rsa-3072' || type === 'rsa-4096'; let isRSA = type === 'rsa-2048' || type === 'rsa-3072' || type === 'rsa-4096';
return Object.keys(data).reduce((result, key) => { return Object.keys(data).reduce((result, key) => {
if (key === 'signature_algorithm' && !isRSA) { if (key === 'signature_algorithm' && !isRSA) {
@ -196,7 +199,7 @@ export default Component.extend(TRANSIT_PARAMS, {
}, },
onClear() { onClear() {
this.resetParams(null, get(this, 'selectedAction')); this.resetParams(null, this.selectedAction);
}, },
clearParams(params) { clearParams(params) {
@ -206,14 +209,14 @@ export default Component.extend(TRANSIT_PARAMS, {
toggleModal(successMessage) { toggleModal(successMessage) {
if (!!successMessage && typeof successMessage === 'string') { if (!!successMessage && typeof successMessage === 'string') {
this.get('flashMessages').success(successMessage); this.flashMessages.success(successMessage);
} }
this.toggleProperty('isModalActive'); this.toggleProperty('isModalActive');
}, },
doSubmit(data, options = {}) { doSubmit(data, options = {}) {
const { backend, id } = this.getModelInfo(); const { backend, id } = this.getModelInfo();
const action = this.get('selectedAction'); const action = this.selectedAction;
const { encodedBase64, ...formData } = data || {}; const { encodedBase64, ...formData } = data || {};
if (!encodedBase64) { if (!encodedBase64) {
if (action === 'encrypt' && !!formData.plaintext) { if (action === 'encrypt' && !!formData.plaintext) {
@ -228,7 +231,7 @@ export default Component.extend(TRANSIT_PARAMS, {
errors: null, errors: null,
result: null, result: null,
}); });
this.get('store') this.store
.adapterFor('transit-key') .adapterFor('transit-key')
.keyAction(action, { backend, id, payload }, options) .keyAction(action, { backend, id, payload }, options)
.then( .then(

View File

@ -1,7 +1,6 @@
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import { alias } from '@ember/object/computed'; import { alias, or } from '@ember/object/computed';
import Component from '@ember/component'; import Component from '@ember/component';
import { computed } from '@ember/object';
import { matchesState } from 'xstate'; import { matchesState } from 'xstate';
export default Component.extend({ export default Component.extend({
@ -9,9 +8,7 @@ export default Component.extend({
wizard: service(), wizard: service(),
auth: service(), auth: service(),
shouldRender: computed('wizard.showWhenUnauthenticated', 'auth.currentToken', function() { shouldRender: or('auth.currentToken', 'wizard.showWhenUnauthenticated'),
return this.get('auth.currentToken') || this.get('wizard.showWhenUnauthenticated');
}),
currentState: alias('wizard.currentState'), currentState: alias('wizard.currentState'),
featureState: alias('wizard.featureState'), featureState: alias('wizard.featureState'),
featureComponent: alias('wizard.featureComponent'), featureComponent: alias('wizard.featureComponent'),
@ -22,41 +19,33 @@ export default Component.extend({
actions: { actions: {
dismissWizard() { dismissWizard() {
this.get('wizard').transitionTutorialMachine(this.get('currentState'), 'DISMISS'); this.wizard.transitionTutorialMachine(this.currentState, 'DISMISS');
}, },
advanceWizard() { advanceWizard() {
let inInit = matchesState('init', this.get('wizard.currentState')); let inInit = matchesState('init', this.wizard.currentState);
let event = inInit ? this.get('wizard.initEvent') || 'CONTINUE' : 'CONTINUE'; let event = inInit ? this.wizard.initEvent || 'CONTINUE' : 'CONTINUE';
this.get('wizard').transitionTutorialMachine(this.get('currentState'), event); this.wizard.transitionTutorialMachine(this.currentState, event);
}, },
advanceFeature() { advanceFeature() {
this.get('wizard').transitionFeatureMachine(this.get('featureState'), 'CONTINUE'); this.wizard.transitionFeatureMachine(this.featureState, 'CONTINUE');
}, },
finishFeature() { finishFeature() {
this.get('wizard').transitionFeatureMachine(this.get('featureState'), 'DONE'); this.wizard.transitionFeatureMachine(this.featureState, 'DONE');
}, },
repeatStep() { repeatStep() {
this.get('wizard').transitionFeatureMachine( this.wizard.transitionFeatureMachine(this.featureState, 'REPEAT', this.componentState);
this.get('featureState'),
'REPEAT',
this.get('componentState')
);
}, },
resetFeature() { resetFeature() {
this.get('wizard').transitionFeatureMachine( this.wizard.transitionFeatureMachine(this.featureState, 'RESET', this.componentState);
this.get('featureState'),
'RESET',
this.get('componentState')
);
}, },
pauseWizard() { pauseWizard() {
this.get('wizard').transitionTutorialMachine(this.get('currentState'), 'PAUSE'); this.wizard.transitionTutorialMachine(this.currentState, 'PAUSE');
}, },
}, },
}); });

View File

@ -1,3 +1,4 @@
import { alias, reads } from '@ember/object/computed';
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import Component from '@ember/component'; import Component from '@ember/component';
import { computed } from '@ember/object'; import { computed } from '@ember/object';
@ -10,24 +11,28 @@ export default Component.extend({
glyph: null, glyph: null,
headerText: null, headerText: null,
selectProgress: null, selectProgress: null,
currentMachine: computed.alias('wizard.currentMachine'), currentMachine: alias('wizard.currentMachine'),
tutorialState: computed.alias('wizard.currentState'), tutorialState: alias('wizard.currentState'),
tutorialComponent: computed.alias('wizard.tutorialComponent'), tutorialComponent: alias('wizard.tutorialComponent'),
showProgress: computed('wizard.featureComponent', 'tutorialState', function() { showProgress: computed(
return ( 'tutorialComponent',
this.tutorialComponent.includes('active') && 'tutorialState',
(this.tutorialState.includes('init.active') || 'wizard.{featureComponent,featureMachineHistory}',
(this.wizard.featureComponent && this.wizard.featureMachineHistory)) function() {
); if (!this.tutorialComponent) return;
}), return (
featureMachineHistory: computed.alias('wizard.featureMachineHistory'), this.tutorialComponent.includes('active') &&
totalFeatures: computed('wizard.featureList', function() { (this.tutorialState.includes('init.active') ||
return this.wizard.featureList.length; (this.wizard.featureComponent && this.wizard.featureMachineHistory))
}), );
}
),
featureMachineHistory: alias('wizard.featureMachineHistory'),
totalFeatures: reads('wizard.featureList.length'),
completedFeatures: computed('wizard.currentMachine', function() { completedFeatures: computed('wizard.currentMachine', function() {
return this.wizard.getCompletedFeatures(); return this.wizard.getCompletedFeatures();
}), }),
currentFeatureProgress: computed('featureMachineHistory.[]', function() { currentFeatureProgress: computed('currentMachine', 'featureMachineHistory.[]', 'tutorialState', function() {
if (this.tutorialState.includes('active.feature')) { if (this.tutorialState.includes('active.feature')) {
let totalSteps = FEATURE_MACHINE_STEPS[this.currentMachine]; let totalSteps = FEATURE_MACHINE_STEPS[this.currentMachine];
if (this.currentMachine === 'secrets') { if (this.currentMachine === 'secrets') {
@ -63,35 +68,43 @@ export default Component.extend({
} }
return null; return null;
}), }),
progressBar: computed('currentFeatureProgress', 'currentFeature', 'currentTutorialProgress', function() { progressBar: computed(
let bar = []; 'completedFeatures',
if (this.currentTutorialProgress) { 'currentFeature',
bar.push({ 'currentFeatureProgress.percentage',
style: htmlSafe(`width:${this.currentTutorialProgress.percentage}%;`), 'currentMachine',
completed: false, 'currentTutorialProgress.percentage',
showIcon: true, 'wizard.featureList',
}); function() {
} else { let bar = [];
if (this.currentFeatureProgress) { if (this.currentTutorialProgress) {
this.completedFeatures.forEach(feature => { bar.push({
bar.push({ style: htmlSafe('width:100%;'), completed: true, feature: feature, showIcon: true }); style: htmlSafe(`width:${this.currentTutorialProgress.percentage}%;`),
}); completed: false,
this.wizard.featureList.forEach(feature => { showIcon: true,
if (feature === this.currentMachine) {
bar.push({
style: htmlSafe(`width:${this.currentFeatureProgress.percentage}%;`),
completed: this.currentFeatureProgress.percentage == 100 ? true : false,
feature: feature,
showIcon: true,
});
} else {
bar.push({ style: htmlSafe('width:0%;'), completed: false, feature: feature, showIcon: true });
}
}); });
} else {
if (this.currentFeatureProgress) {
this.completedFeatures.forEach(feature => {
bar.push({ style: htmlSafe('width:100%;'), completed: true, feature: feature, showIcon: true });
});
this.wizard.featureList.forEach(feature => {
if (feature === this.currentMachine) {
bar.push({
style: htmlSafe(`width:${this.currentFeatureProgress.percentage}%;`),
completed: this.currentFeatureProgress.percentage == 100 ? true : false,
feature: feature,
showIcon: true,
});
} else {
bar.push({ style: htmlSafe('width:0%;'), completed: false, feature: feature, showIcon: true });
}
});
}
} }
return bar;
} }
return bar; ),
}),
actions: { actions: {
dismissWizard() { dismissWizard() {

View File

@ -1,3 +1,4 @@
import { or, not } from '@ember/object/computed';
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import Component from '@ember/component'; import Component from '@ember/component';
import { computed } from '@ember/object'; import { computed } from '@ember/object';
@ -15,13 +16,13 @@ export default Component.extend({
}, },
maybeHideFeatures() { maybeHideFeatures() {
let features = this.get('allFeatures'); let features = this.allFeatures;
features.forEach(feat => { features.forEach(feat => {
feat.disabled = this.doesNotHavePermission(feat.requiredPermissions); feat.disabled = this.doesNotHavePermission(feat.requiredPermissions);
}); });
if (this.get('showReplication') === false) { if (this.showReplication === false) {
let feature = this.get('allFeatures').findBy('key', 'replication'); let feature = this.allFeatures.findBy('key', 'replication');
feature.show = false; feature.show = false;
} }
}, },
@ -126,24 +127,18 @@ export default Component.extend({
]; ];
}), }),
showReplication: computed('version.{hasPerfReplication,hasDRReplication}', function() { showReplication: or('version.hasPerfReplication', 'version.hasDRReplication'),
return this.get('version.hasPerfReplication') || this.get('version.hasDRReplication');
}),
selectedFeatures: computed('allFeatures.@each.selected', function() { selectedFeatures: computed('allFeatures.@each.selected', function() {
return this.get('allFeatures') return this.allFeatures.filterBy('selected').mapBy('key');
.filterBy('selected')
.mapBy('key');
}), }),
cannotStartWizard: computed('selectedFeatures', function() { cannotStartWizard: not('selectedFeatures.length'),
return !this.get('selectedFeatures').length;
}),
actions: { actions: {
saveFeatures() { saveFeatures() {
let wizard = this.get('wizard'); let wizard = this.wizard;
wizard.saveFeatures(this.get('selectedFeatures')); wizard.saveFeatures(this.selectedFeatures);
wizard.transitionTutorialMachine('active.select', 'CONTINUE'); wizard.transitionTutorialMachine('active.select', 'CONTINUE');
}, },
}, },

View File

@ -1,5 +1,5 @@
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import { alias } from '@ember/object/computed'; import { alias, equal } from '@ember/object/computed';
import Component from '@ember/component'; import Component from '@ember/component';
import { computed } from '@ember/object'; import { computed } from '@ember/object';
import { engines } from 'vault/helpers/mountable-secret-engines'; import { engines } from 'vault/helpers/mountable-secret-engines';
@ -18,34 +18,32 @@ export default Component.extend({
fullNextStep: alias('wizard.nextStep'), fullNextStep: alias('wizard.nextStep'),
nextFeature: alias('wizard.nextFeature'), nextFeature: alias('wizard.nextFeature'),
nextStep: computed('fullNextStep', function() { nextStep: computed('fullNextStep', function() {
return this.get('fullNextStep').split('.').lastObject; return this.fullNextStep.split('.').lastObject;
}),
needsEncryption: computed('mountSubtype', function() {
return this.get('mountSubtype') === 'transit';
}), }),
needsEncryption: equal('mountSubtype', 'transit'),
stepComponent: alias('wizard.stepComponent'), stepComponent: alias('wizard.stepComponent'),
detailsComponent: computed('mountSubtype', function() { detailsComponent: computed('currentMachine', 'mountSubtype', function() {
let suffix = this.get('currentMachine') === 'secrets' ? 'engine' : 'method'; let suffix = this.currentMachine === 'secrets' ? 'engine' : 'method';
return this.get('mountSubtype') ? `wizard/${this.get('mountSubtype')}-${suffix}` : null; return this.mountSubtype ? `wizard/${this.mountSubtype}-${suffix}` : null;
}), }),
isSupported: computed('mountSubtype', function() { isSupported: computed('currentMachine', 'mountSubtype', function() {
if (this.get('currentMachine') === 'secrets') { if (this.currentMachine === 'secrets') {
return supportedSecrets.includes(this.get('mountSubtype')); return supportedSecrets.includes(this.mountSubtype);
} else { } else {
return supportedAuth.includes(this.get('mountSubtype')); return supportedAuth.includes(this.mountSubtype);
} }
}), }),
mountName: computed('mountSubtype', function() { mountName: computed('currentMachine', 'mountSubtype', function() {
if (this.get('currentMachine') === 'secrets') { if (this.currentMachine === 'secrets') {
var secret = engines().find(engine => { var secret = engines().find(engine => {
return engine.type === this.get('mountSubtype'); return engine.type === this.mountSubtype;
}); });
if (secret) { if (secret) {
return secret.displayName; return secret.displayName;
} }
} else { } else {
var auth = methods().find(method => { var auth = methods().find(method => {
return method.type === this.get('mountSubtype'); return method.type === this.mountSubtype;
}); });
if (auth) { if (auth) {
return auth.displayName; return auth.displayName;
@ -54,7 +52,7 @@ export default Component.extend({
return null; return null;
}), }),
actionText: computed('mountSubtype', function() { actionText: computed('mountSubtype', function() {
switch (this.get('mountSubtype')) { switch (this.mountSubtype) {
case 'aws': case 'aws':
return 'Generate credential'; return 'Generate credential';
case 'ssh': case 'ssh':

View File

@ -1,6 +1,6 @@
import { assert } from '@ember/debug'; import { assert } from '@ember/debug';
import Component from '@ember/component'; import Component from '@ember/component';
import { set, get, computed } from '@ember/object'; import { set, computed } from '@ember/object';
import hbs from 'htmlbars-inline-precompile'; import hbs from 'htmlbars-inline-precompile';
export default Component.extend({ export default Component.extend({
@ -11,18 +11,18 @@ export default Component.extend({
ttl: '30m', ttl: '30m',
wrapTTL: computed('wrapResponse', 'ttl', function() { wrapTTL: computed('wrapResponse', 'ttl', function() {
const { wrapResponse, ttl } = this.getProperties('wrapResponse', 'ttl'); const { wrapResponse, ttl } = this;
return wrapResponse ? ttl : null; return wrapResponse ? ttl : null;
}), }),
didRender() { didRender() {
this._super(...arguments); this._super(...arguments);
get(this, 'onChange')(get(this, 'wrapTTL')); this.onChange(this.wrapTTL);
}, },
init() { init() {
this._super(...arguments); this._super(...arguments);
assert('`onChange` handler is a required attr in `' + this.toString() + '`.', get(this, 'onChange')); assert('`onChange` handler is a required attr in `' + this.toString() + '`.', this.onChange);
}, },
layout: hbs` layout: hbs`
@ -43,7 +43,7 @@ export default Component.extend({
changedValue(ttlObj) { changedValue(ttlObj) {
set(this, 'wrapResponse', ttlObj.enabled); set(this, 'wrapResponse', ttlObj.enabled);
set(this, 'ttl', `${ttlObj.seconds}s`); set(this, 'ttl', `${ttlObj.seconds}s`);
get(this, 'onChange')(get(this, 'wrapTTL')); this.onChange(this.wrapTTL);
}, },
}, },
}); });

View File

@ -8,11 +8,11 @@ export default Controller.extend({
auth: service(), auth: service(),
store: service(), store: service(),
activeCluster: computed('auth.activeCluster', function() { activeCluster: computed('auth.activeCluster', function() {
let id = this.get('auth.activeCluster'); let id = this.auth.activeCluster;
return id ? this.get('store').peekRecord('cluster', id) : null; return id ? this.store.peekRecord('cluster', id) : null;
}), }),
activeClusterName: computed('activeCluster', function() { activeClusterName: computed('activeCluster', function() {
const activeCluster = this.get('activeCluster'); const activeCluster = this.activeCluster;
return activeCluster ? activeCluster.get('name') : null; return activeCluster ? activeCluster.get('name') : null;
}), }),
}); });

View File

@ -16,11 +16,11 @@ export default Controller.extend({
auth: service(), auth: service(),
store: service(), store: service(),
activeCluster: computed('auth.activeCluster', function() { activeCluster: computed('auth.activeCluster', function() {
let id = this.get('auth.activeCluster'); let id = this.auth.activeCluster;
return id ? this.get('store').peekRecord('cluster', id) : null; return id ? this.store.peekRecord('cluster', id) : null;
}), }),
activeClusterName: computed('activeCluster', function() { activeClusterName: computed('activeCluster', function() {
const activeCluster = this.get('activeCluster'); const activeCluster = this.activeCluster;
return activeCluster ? activeCluster.get('name') : null; return activeCluster ? activeCluster.get('name') : null;
}), }),
}); });

View File

@ -1,3 +1,4 @@
/* eslint-disable ember/no-observers */
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import { alias } from '@ember/object/computed'; import { alias } from '@ember/object/computed';
import Controller from '@ember/controller'; import Controller from '@ember/controller';
@ -24,19 +25,18 @@ export default Controller.extend({
namespaceQueryParam: '', namespaceQueryParam: '',
/* eslint-disable-next-line ember/no-observers */
onQPChange: observer('namespaceQueryParam', function() { onQPChange: observer('namespaceQueryParam', function() {
this.get('namespaceService').setNamespace(this.get('namespaceQueryParam')); this.namespaceService.setNamespace(this.namespaceQueryParam);
}), }),
consoleOpen: alias('console.isOpen'), consoleOpen: alias('console.isOpen'),
activeCluster: computed('auth.activeCluster', function() { activeCluster: computed('auth.activeCluster', function() {
return this.get('store').peekRecord('cluster', this.get('auth.activeCluster')); return this.store.peekRecord('cluster', this.auth.activeCluster);
}), }),
activeClusterName: computed('activeCluster', function() { activeClusterName: computed('activeCluster', function() {
const activeCluster = this.get('activeCluster'); const activeCluster = this.activeCluster;
return activeCluster ? activeCluster.get('name') : null; return activeCluster ? activeCluster.get('name') : null;
}), }),
@ -46,11 +46,7 @@ export default Controller.extend({
'auth.currentToken', 'auth.currentToken',
'activeCluster.{dr.isSecondary,needsInit,sealed}', 'activeCluster.{dr.isSecondary,needsInit,sealed}',
function() { function() {
if ( if (this.activeCluster.dr?.isSecondary || this.activeCluster.needsInit || this.activeCluster.sealed) {
this.get('activeCluster.dr.isSecondary') ||
this.get('activeCluster.needsInit') ||
this.get('activeCluster.sealed')
) {
return false; return false;
} }
if ( if (
@ -60,6 +56,7 @@ export default Controller.extend({
) { ) {
return true; return true;
} }
return;
} }
), ),

View File

@ -15,7 +15,7 @@ export default Controller.extend({
}; };
let routeName = listRoutes[type]; let routeName = listRoutes[type];
if (!isDelete) { if (!isDelete) {
yield this.transitionToRoute(this.get('showRoute'), model.id, this.get('showTab')); yield this.transitionToRoute(this.showRoute, model.id, this.showTab);
return; return;
} }
yield this.transitionToRoute(routeName); yield this.transitionToRoute(routeName);

View File

@ -13,10 +13,10 @@ export default Controller.extend(ListController, {
.destroyRecord() .destroyRecord()
.then(() => { .then(() => {
this.send('reload'); this.send('reload');
this.get('flashMessages').success(`Successfully deleted ${type}: ${id}`); this.flashMessages.success(`Successfully deleted ${type}: ${id}`);
}) })
.catch(e => { .catch(e => {
this.get('flashMessages').success( this.flashMessages.success(
`There was a problem deleting ${type}: ${id} - ${e.errors.join(' ') || e.message}` `There was a problem deleting ${type}: ${id} - ${e.errors.join(' ') || e.message}`
); );
}); });
@ -31,10 +31,10 @@ export default Controller.extend(ListController, {
model model
.save() .save()
.then(() => { .then(() => {
this.get('flashMessages').success(`Successfully ${action[0]} ${type}: ${id}`); this.flashMessages.success(`Successfully ${action[0]} ${type}: ${id}`);
}) })
.catch(e => { .catch(e => {
this.get('flashMessages').success( this.flashMessages.success(
`There was a problem ${action[1]} ${type}: ${id} - ${e.errors.join(' ') || e.message}` `There was a problem ${action[1]} ${type}: ${id} - ${e.errors.join(' ') || e.message}`
); );
}); });

View File

@ -9,23 +9,23 @@ export default Controller.extend(ListController, {
store: service(), store: service(),
clusterController: controller('vault.cluster'), clusterController: controller('vault.cluster'),
backendCrumb: computed(function() { backendCrumb: computed('clusterController.model.name', function() {
return { return {
label: 'leases', label: 'leases',
text: 'leases', text: 'leases',
path: 'vault.cluster.access.leases.list-root', path: 'vault.cluster.access.leases.list-root',
model: this.get('clusterController.model.name'), model: this.clusterController.model.name,
}; };
}), }),
isLoading: false, isLoading: false,
filterIsFolder: computed('filter', function() { filterIsFolder: computed('filter', function() {
return !!utils.keyIsFolder(this.get('filter')); return !!utils.keyIsFolder(this.filter);
}), }),
emptyTitle: computed('baseKey.id', 'filter', 'filterIsFolder', function() { emptyTitle: computed('baseKey.id', 'filter', 'filterIsFolder', function() {
let id = this.get('baseKey.id'); let id = this.baseKey.id;
let filter = this.filter; let filter = this.filter;
if (id === '') { if (id === '') {
return 'There are currently no leases.'; return 'There are currently no leases.';
@ -37,22 +37,23 @@ export default Controller.extend(ListController, {
return `We couldn't find a prefix matching &quot;${filter}&quot;.`; return `We couldn't find a prefix matching &quot;${filter}&quot;.`;
} }
} }
return '';
}), }),
actions: { actions: {
revokePrefix(prefix, isForce) { revokePrefix(prefix, isForce) {
const adapter = this.get('store').adapterFor('lease'); const adapter = this.store.adapterFor('lease');
const method = isForce ? 'forceRevokePrefix' : 'revokePrefix'; const method = isForce ? 'forceRevokePrefix' : 'revokePrefix';
const fn = adapter[method]; const fn = adapter[method];
fn.call(adapter, prefix) fn.call(adapter, prefix)
.then(() => { .then(() => {
return this.transitionToRoute('vault.cluster.access.leases.list-root').then(() => { return this.transitionToRoute('vault.cluster.access.leases.list-root').then(() => {
this.get('flashMessages').success(`All of the leases under ${prefix} will be revoked.`); this.flashMessages.success(`All of the leases under ${prefix} will be revoked.`);
}); });
}) })
.catch(e => { .catch(e => {
const errString = e.errors.join('.'); const errString = e.errors.join('.');
this.get('flashMessages').danger( this.flashMessages.danger(
`There was an error attempting to revoke the prefix: ${prefix}. ${errString}.` `There was an error attempting to revoke the prefix: ${prefix}. ${errString}.`
); );
}); });

View File

@ -6,12 +6,12 @@ import Controller, { inject as controller } from '@ember/controller';
export default Controller.extend({ export default Controller.extend({
clusterController: controller('vault.cluster'), clusterController: controller('vault.cluster'),
backendCrumb: computed(function() { backendCrumb: computed('clusterController.model.name', function() {
return { return {
label: 'leases', label: 'leases',
text: 'leases', text: 'leases',
path: 'vault.cluster.access.leases.list-root', path: 'vault.cluster.access.leases.list-root',
model: this.get('clusterController.model.name'), model: this.clusterController.model.name,
}; };
}), }),
@ -26,7 +26,7 @@ export default Controller.extend({
renewLease(model, interval) { renewLease(model, interval) {
const adapter = model.store.adapterFor('lease'); const adapter = model.store.adapterFor('lease');
const flash = this.get('flashMessages'); const flash = this.flashMessages;
adapter adapter
.renew(model.id, interval) .renew(model.id, interval)
.then(() => { .then(() => {

View File

@ -12,12 +12,12 @@ export default Controller.extend({
filter: null, filter: null,
disableMethod: task(function*(method) { disableMethod: task(function*(method) {
const { type, path } = method.getProperties('type', 'path'); const { type, path } = method;
try { try {
yield method.destroyRecord(); yield method.destroyRecord();
this.get('flashMessages').success(`The ${type} Auth Method at ${path} has been disabled.`); this.flashMessages.success(`The ${type} Auth Method at ${path} has been disabled.`);
} catch (err) { } catch (err) {
this.get('flashMessages').danger( this.flashMessages.danger(
`There was an error disabling Auth Method at ${path}: ${err.errors.join(' ')}.` `There was an error disabling Auth Method at ${path}: ${err.errors.join(' ')}.`
); );
} }

View File

@ -6,7 +6,7 @@ export default Controller.extend({
onSave({ saveType }) { onSave({ saveType }) {
if (saveType === 'save') { if (saveType === 'save') {
// fetch new namespaces for the namespace picker // fetch new namespaces for the namespace picker
this.get('namespaceService.findNamespacesForUser').perform(); this.namespaceService.findNamespacesForUser.perform();
return this.transitionToRoute('vault.cluster.access.namespaces.index'); return this.transitionToRoute('vault.cluster.access.namespaces.index');
} }
}, },

View File

@ -8,7 +8,7 @@ export default Controller.extend({
actions: { actions: {
refreshNamespaceList() { refreshNamespaceList() {
// fetch new namespaces for the namespace picker // fetch new namespaces for the namespace picker
this.get('namespaceService.findNamespacesForUser').perform(); this.namespaceService.findNamespacesForUser.perform();
}, },
}, },
}); });

View File

@ -16,7 +16,7 @@ export default Controller.extend({
updateNamespace: task(function*(value) { updateNamespace: task(function*(value) {
// debounce // debounce
yield timeout(500); yield timeout(500);
this.get('namespaceService').setNamespace(value, true); this.namespaceService.setNamespace(value, true);
this.set('namespaceQueryParam', value); this.set('namespaceQueryParam', value);
}).restartable(), }).restartable(),
}); });

View File

@ -22,8 +22,8 @@ export default Controller.extend(DEFAULTS, {
this.set('loading', false); this.set('loading', false);
this.set('keyData', resp); this.set('keyData', resp);
this.model.reload(); this.model.reload();
this.get('wizard').set('initEvent', 'SAVE'); this.wizard.set('initEvent', 'SAVE');
this.get('wizard').transitionTutorialMachine(this.get('wizard.currentState'), 'TOSAVE'); this.wizard.transitionTutorialMachine(this.wizard.currentState, 'TOSAVE');
}, },
initError(e) { initError(e) {
@ -36,7 +36,7 @@ export default Controller.extend(DEFAULTS, {
}, },
keyFilename: computed('model.name', function() { keyFilename: computed('model.name', function() {
return `vault-cluster-${this.get('model.name')}`; return `vault-cluster-${this.model.name}`;
}), }),
actions: { actions: {

View File

@ -8,7 +8,7 @@ export default Controller.extend(PolicyEditController, {
actions: { actions: {
setPolicyFromFile(index, fileInfo) { setPolicyFromFile(index, fileInfo) {
let { value, fileName } = fileInfo; let { value, fileName } = fileInfo;
let model = this.get('model'); let model = this.model;
model.set('policy', value); model.set('policy', value);
if (!model.get('name')) { if (!model.get('name')) {
let trimmedFileName = trimRight(fileName, ['.json', '.txt', '.hcl', '.policy']); let trimmedFileName = trimRight(fileName, ['.json', '.txt', '.hcl', '.policy']);

View File

@ -21,18 +21,18 @@ export default Controller.extend({
isLoading: false, isLoading: false,
filterMatchesKey: computed('filter', 'model', 'model.[]', function() { filterMatchesKey: computed('filter', 'model', 'model.[]', function() {
var filter = this.get('filter'); var filter = this.filter;
var content = this.get('model'); var content = this.model;
return !!(content && content.length && content.findBy('id', filter)); return !!(content && content.length && content.findBy('id', filter));
}), }),
firstPartialMatch: computed('filter', 'model', 'model.[]', 'filterMatchesKey', function() { firstPartialMatch: computed('filter', 'model', 'model.[]', 'filterMatchesKey', function() {
var filter = this.get('filter'); var filter = this.filter;
var content = this.get('model'); var content = this.model;
if (!content) { if (!content) {
return; return;
} }
var filterMatchesKey = this.get('filterMatchesKey'); var filterMatchesKey = this.filterMatchesKey;
var re = new RegExp('^' + filter); var re = new RegExp('^' + filter);
return filterMatchesKey return filterMatchesKey
? null ? null
@ -51,15 +51,15 @@ export default Controller.extend({
deletePolicy(model) { deletePolicy(model) {
let policyType = model.get('policyType'); let policyType = model.get('policyType');
let name = model.id; let name = model.id;
let flash = this.get('flashMessages'); let flash = this.flashMessages;
model model
.destroyRecord() .destroyRecord()
.then(() => { .then(() => {
// this will clear the dataset cache on the store // this will clear the dataset cache on the store
this.send('reload'); this.send('reload');
flash.success(`${policyType.toUpperCase()} policy "${name}" was successfully deleted.`); flash.success(`${policyType.toUpperCase()} policy "${name}" was successfully deleted.`);
if (this.get('wizard.featureState') === 'delete') { if (this.wizard.featureState === 'delete') {
this.get('wizard').transitionFeatureMachine('delete', 'CONTINUE', policyType); this.wizard.transitionFeatureMachine('delete', 'CONTINUE', policyType);
} }
}) })
.catch(e => { .catch(e => {

View File

@ -4,6 +4,6 @@ import Controller from '@ember/controller';
export default Controller.extend({ export default Controller.extend({
isConfigurable: computed('model.type', function() { isConfigurable: computed('model.type', function() {
const configurableEngines = ['aws', 'ssh', 'pki']; const configurableEngines = ['aws', 'ssh', 'pki'];
return configurableEngines.includes(this.get('model.type')); return configurableEngines.includes(this.model.type);
}), }),
}); });

View File

@ -14,7 +14,7 @@ export default Controller.extend(BackendCrumbMixin, {
}, },
toggleAdvancedEdit(bool) { toggleAdvancedEdit(bool) {
this.set('preferAdvancedEdit', bool); this.set('preferAdvancedEdit', bool);
this.get('backendController').set('preferAdvancedEdit', bool); this.backendController.set('preferAdvancedEdit', bool);
}, },
}, },
}); });

View File

@ -17,7 +17,7 @@ export default Controller.extend(BackendCrumbMixin, {
toggleAdvancedEdit(bool) { toggleAdvancedEdit(bool) {
this.set('preferAdvancedEdit', bool); this.set('preferAdvancedEdit', bool);
this.get('backendController').set('preferAdvancedEdit', bool); this.backendController.set('preferAdvancedEdit', bool);
}, },
}, },
}); });

View File

@ -1,3 +1,4 @@
import { or } from '@ember/object/computed';
import { computed } from '@ember/object'; import { computed } from '@ember/object';
import { inject as service } from '@ember/service'; import { inject as service } from '@ember/service';
import Controller from '@ember/controller'; import Controller from '@ember/controller';
@ -13,12 +14,10 @@ export default Controller.extend(ListController, BackendCrumbMixin, WithNavToNea
tab: '', tab: '',
filterIsFolder: computed('filter', function() { filterIsFolder: computed('filter', function() {
return !!utils.keyIsFolder(this.get('filter')); return !!utils.keyIsFolder(this.filter);
}), }),
isConfigurableTab: computed('isCertTab', 'isConfigure', function() { isConfigurableTab: or('isCertTab', 'isConfigure'),
return this.get('isCertTab') || this.get('isConfigure');
}),
actions: { actions: {
chooseAction(action) { chooseAction(action) {
@ -32,7 +31,7 @@ export default Controller.extend(ListController, BackendCrumbMixin, WithNavToNea
.saveZeroAddressConfig() .saveZeroAddressConfig()
.catch(e => { .catch(e => {
item.set('zeroAddress', false); item.set('zeroAddress', false);
this.get('flashMessages').danger(e.message); this.flashMessages.danger(e.message);
}) })
.finally(() => { .finally(() => {
this.set('loading-' + item.id, false); this.set('loading-' + item.id, false);
@ -42,7 +41,7 @@ export default Controller.extend(ListController, BackendCrumbMixin, WithNavToNea
delete(item, type) { delete(item, type) {
const name = item.id; const name = item.id;
item.destroyRecord().then(() => { item.destroyRecord().then(() => {
this.get('flashMessages').success(`${name} was successfully deleted.`); this.flashMessages.success(`${name} was successfully deleted.`);
this.send('reload'); this.send('reload');
if (type === 'secret') { if (type === 'secret') {
this.navToNearestAncestor.perform(name); this.navToNearestAncestor.perform(name);

View File

@ -19,7 +19,7 @@ export default Controller.extend(BackendCrumbMixin, {
toggleAdvancedEdit(bool) { toggleAdvancedEdit(bool) {
this.set('preferAdvancedEdit', bool); this.set('preferAdvancedEdit', bool);
this.get('backendController').set('preferAdvancedEdit', bool); this.backendController.set('preferAdvancedEdit', bool);
}, },
}, },
}); });

View File

@ -19,21 +19,21 @@ export default Controller.extend({
const hasErrors = codemirror.state.lint.marked.length > 0; const hasErrors = codemirror.state.lint.marked.length > 0;
if (!hasErrors) { if (!hasErrors) {
set(this.get('model'), attr, JSON.parse(val)); set(this.model, attr, JSON.parse(val));
} }
}, },
updateTtl(path, val) { updateTtl(path, val) {
const model = this.get('model'); const model = this.model;
let valueToSet = val.enabled === true ? `${val.seconds}s` : undefined; let valueToSet = val.enabled === true ? `${val.seconds}s` : undefined;
set(model, path, valueToSet); set(model, path, valueToSet);
}, },
newModel() { newModel() {
const model = this.get('model'); const model = this.model;
const roleModel = model.get('role'); const roleModel = model.get('role');
model.unloadRecord(); model.unloadRecord();
const newModel = this.get('store').createRecord('ssh-sign', { const newModel = this.store.createRecord('ssh-sign', {
role: roleModel, role: roleModel,
id: `${get(roleModel, 'backend')}-${get(roleModel, 'name')}`, id: `${get(roleModel, 'backend')}-${get(roleModel, 'name')}`,
}); });

View File

@ -9,7 +9,7 @@ export default Controller.extend({
displayableBackends: filterBy('model', 'shouldIncludeInList'), displayableBackends: filterBy('model', 'shouldIncludeInList'),
supportedBackends: computed('displayableBackends', 'displayableBackends.[]', function() { supportedBackends: computed('displayableBackends', 'displayableBackends.[]', function() {
return (this.get('displayableBackends') || []) return (this.displayableBackends || [])
.filter(backend => LINKED_BACKENDS.includes(backend.get('engineType'))) .filter(backend => LINKED_BACKENDS.includes(backend.get('engineType')))
.sortBy('id'); .sortBy('id');
}), }),
@ -20,9 +20,9 @@ export default Controller.extend({
'supportedBackends', 'supportedBackends',
'supportedBackends.[]', 'supportedBackends.[]',
function() { function() {
return (this.get('displayableBackends') || []) return (this.displayableBackends || [])
.slice() .slice()
.removeObjects(this.get('supportedBackends')) .removeObjects(this.supportedBackends)
.sortBy('id'); .sortBy('id');
} }
), ),
@ -31,9 +31,9 @@ export default Controller.extend({
const { engineType, path } = engine; const { engineType, path } = engine;
try { try {
yield engine.destroyRecord(); yield engine.destroyRecord();
this.get('flashMessages').success(`The ${engineType} Secrets Engine at ${path} has been disabled.`); this.flashMessages.success(`The ${engineType} Secrets Engine at ${path} has been disabled.`);
} catch (err) { } catch (err) {
this.get('flashMessages').danger( this.flashMessages.danger(
`There was an error disabling the ${engineType} Secrets Engine at ${path}: ${err.errors.join(' ')}.` `There was an error disabling the ${engineType} Secrets Engine at ${path}: ${err.errors.join(' ')}.`
); );
} }

View File

@ -20,26 +20,24 @@ export default Controller.extend(CONFIG_ATTRS, {
flashMessages: service(), flashMessages: service(),
loading: false, loading: false,
reset() { reset() {
this.get('model').rollbackAttributes(); this.model.rollbackAttributes();
this.setProperties(CONFIG_ATTRS); this.setProperties(CONFIG_ATTRS);
}, },
actions: { actions: {
saveConfig(options = { delete: false }) { saveConfig(options = { delete: false }) {
const isDelete = options.delete; const isDelete = options.delete;
if (this.get('model.type') === 'ssh') { if (this.model.type === 'ssh') {
this.set('loading', true); this.set('loading', true);
this.get('model') this.model.saveCA({ isDelete }).then(() => {
.saveCA({ isDelete }) this.set('loading', false);
.then(() => { this.send('refreshRoute');
this.set('loading', false); this.set('configured', !isDelete);
this.send('refreshRoute'); if (isDelete) {
this.set('configured', !isDelete); this.flashMessages.success('SSH Certificate Authority Configuration deleted!');
if (isDelete) { } else {
this.get('flashMessages').success('SSH Certificate Authority Configuration deleted!'); this.flashMessages.success('SSH Certificate Authority Configuration saved!');
} else { }
this.get('flashMessages').success('SSH Certificate Authority Configuration saved!'); });
}
});
} }
}, },
@ -51,7 +49,7 @@ export default Controller.extend(CONFIG_ATTRS, {
if (!hasData) { if (!hasData) {
return; return;
} }
this.get('model') this.model
.save({ .save({
adapterOptions: { adapterOptions: {
adapterMethod: method, adapterMethod: method,
@ -59,9 +57,9 @@ export default Controller.extend(CONFIG_ATTRS, {
}, },
}) })
.then(() => { .then(() => {
this.get('model').send('pushedData'); this.model.send('pushedData');
this.reset(); this.reset();
this.get('flashMessages').success('The backend configuration saved successfully!'); this.flashMessages.success('The backend configuration saved successfully!');
}) })
.finally(() => { .finally(() => {
this.set('loading', false); this.set('loading', false);

View File

@ -19,7 +19,7 @@ export default Controller.extend({
transition = this.transitionToRoute('vault.cluster.secrets.backends'); transition = this.transitionToRoute('vault.cluster.secrets.backends');
} }
return transition.followRedirects().then(() => { return transition.followRedirects().then(() => {
this.get('wizard').transitionFeatureMachine(this.get('wizard.featureState'), 'CONTINUE', type); this.wizard.transitionFeatureMachine(this.wizard.featureState, 'CONTINUE', type);
}); });
}, },
onConfigError: function(modelId) { onConfigError: function(modelId) {

View File

@ -11,7 +11,7 @@ export default Controller.extend({
.seal() .seal()
.then(() => { .then(() => {
this.model.cluster.get('leaderNode').set('sealed', true); this.model.cluster.get('leaderNode').set('sealed', true);
this.get('auth').deleteCurrentToken(); this.auth.deleteCurrentToken();
return this.transitionToRoute('vault.cluster.unseal'); return this.transitionToRoute('vault.cluster.unseal');
}); });
}, },

View File

@ -6,16 +6,14 @@ export default Controller.extend({
actions: { actions: {
transitionToCluster(resp) { transitionToCluster(resp) {
return this.get('model') return this.model.reload().then(() => {
.reload() this.wizard.transitionTutorialMachine(this.wizard.currentState, 'CONTINUE', resp);
.then(() => { return this.transitionToRoute('vault.cluster', this.model.name);
this.get('wizard').transitionTutorialMachine(this.get('wizard.currentState'), 'CONTINUE', resp); });
return this.transitionToRoute('vault.cluster', this.get('model.name'));
});
}, },
setUnsealState(resp) { setUnsealState(resp) {
this.get('wizard').set('componentState', resp); this.wizard.set('componentState', resp);
}, },
isUnsealed(data) { isUnsealed(data) {

View File

@ -1,12 +1,11 @@
import { run } from '@ember/runloop'; import { run } from '@ember/runloop';
import Helper from '@ember/component/helper'; import Helper from '@ember/component/helper';
import { get } from '@ember/object';
export default Helper.extend({ export default Helper.extend({
disableInterval: false, disableInterval: false,
compute(value, { interval }) { compute(value, { interval }) {
if (get(this, 'disableInterval')) { if (this.disableInterval) {
return; return;
} }

Some files were not shown because too many files have changed in this diff Show More