Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[ui] Token management interface on policy pages #15435

Merged
merged 18 commits into from
Dec 15, 2022
Merged
Show file tree
Hide file tree
Changes from 15 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions ui/app/abilities/token.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
import AbstractAbility from './abstract';
import { alias } from '@ember/object/computed';

export default class extends AbstractAbility {
@alias('selfTokenIsManagement') canRead;
@alias('selfTokenIsManagement') canList;
@alias('selfTokenIsManagement') canWrite;
@alias('selfTokenIsManagement') canUpdate;
@alias('selfTokenIsManagement') canDestroy;
philrenaud marked this conversation as resolved.
Show resolved Hide resolved
}
12 changes: 12 additions & 0 deletions ui/app/adapters/token.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,13 +2,25 @@ import { inject as service } from '@ember/service';
import { default as ApplicationAdapter, namespace } from './application';
import OTTExchangeError from '../utils/ott-exchange-error';
import classic from 'ember-classic-decorator';
import { singularize } from 'ember-inflector';

@classic
export default class TokenAdapter extends ApplicationAdapter {
@service store;

namespace = namespace + '/acl';

createRecord(_store, type, snapshot) {
let data = this.serialize(snapshot);
data.Policies = data.PolicyIDs;
return this.ajax(`${this.buildURL()}/token`, 'POST', { data });
}

// Delete at /token instead of /tokens
urlForDeleteRecord(identifier, modelName) {
return `${this.buildURL()}/${singularize(modelName)}/${identifier}`;
}

findSelf() {
return this.ajax(`${this.buildURL()}/token/self`, 'GET').then((token) => {
const store = this.store;
Expand Down
18 changes: 13 additions & 5 deletions ui/app/components/policy-editor.js
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,18 @@ export default class PolicyEditorComponent extends Component {
try {
const nameRegex = '^[a-zA-Z0-9-]{1,128}$';
if (!this.policy.name?.match(nameRegex)) {
throw new Error(
'Policy name must be 1-128 characters long and can only contain letters, numbers, and dashes.'
);
throw {
errors: [
{
detail:
'Policy name must be 1-128 characters long and can only contain letters, numbers, and dashes.',
},
],
};
}

const shouldRedirectAfterSave = this.policy.isNew;
philrenaud marked this conversation as resolved.
Show resolved Hide resolved

if (
this.policy.isNew &&
this.store.peekRecord('policy', this.policy.name)
Expand All @@ -47,9 +54,10 @@ export default class PolicyEditorComponent extends Component {
timeout: 5000,
});

this.router.transitionTo('policies');
if (shouldRedirectAfterSave) {
this.router.transitionTo('policies.policy', this.policy.id);
}
} catch (error) {
console.log('error and its', error);
this.flashMessages.add({
title: `Error creating Policy ${this.policy.name}`,
message: messageForError(error),
Expand Down
2 changes: 1 addition & 1 deletion ui/app/components/tooltip.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@ import Component from '@glimmer/component';

export default class Tooltip extends Component {
get text() {
const inputText = this.args.text;
const inputText = this.args.text?.toString();
if (!inputText || inputText.length < 30) {
return inputText;
}
Expand Down
2 changes: 1 addition & 1 deletion ui/app/controllers/policies/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ export default class PoliciesIndexController extends Controller {
@service router;
get policies() {
return this.model.policies.map((policy) => {
policy.tokens = this.model.tokens.filter((token) => {
policy.tokens = (this.model.tokens || []).filter((token) => {
return token.policies.includes(policy);
});
return policy;
Expand Down
83 changes: 80 additions & 3 deletions ui/app/controllers/policies/policy.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,26 @@ import Controller from '@ember/controller';
import { action } from '@ember/object';
import { inject as service } from '@ember/service';
import { tracked } from '@glimmer/tracking';
import { alias } from '@ember/object/computed';
import { task } from 'ember-concurrency';

export default class PoliciesPolicyController extends Controller {
@service flashMessages;
@service router;
@service store;

@alias('model.policy') policy;
@alias('model.tokens') tokens;

@tracked
error = null;

@tracked isDeleting = false;

get newTokenString() {
return `nomad acl token create -name="<TOKEN_NAME>" -policy="${this.policy.name}" -type=client -ttl=<8h>`;
}

@action
onDeletePrompt() {
this.isDeleting = true;
Expand All @@ -23,8 +35,8 @@ export default class PoliciesPolicyController extends Controller {

@task(function* () {
try {
yield this.model.deleteRecord();
yield this.model.save();
yield this.policy.deleteRecord();
yield this.policy.save();
this.flashMessages.add({
title: 'Policy Deleted',
type: 'success',
Expand All @@ -34,7 +46,7 @@ export default class PoliciesPolicyController extends Controller {
this.router.transitionTo('policies');
} catch (err) {
this.flashMessages.add({
title: `Error deleting Policy ${this.model.name}`,
title: `Error deleting Policy ${this.policy.name}`,
message: err,
type: 'error',
destroyOnClick: false,
Expand All @@ -43,4 +55,69 @@ export default class PoliciesPolicyController extends Controller {
}
})
deletePolicy;

async refreshTokens() {
this.tokens = this.store
.peekAll('token')
.filter((token) =>
token.policyNames?.includes(decodeURIComponent(this.policy.name))
);
}

@task(function* () {
try {
const newToken = this.store.createRecord('token', {
name: `Example Token for ${this.policy.name}`,
policies: [this.policy],
// New date 10 minutes into the future
expirationTime: new Date(Date.now() + 10 * 60 * 1000),
type: 'client',
});
yield newToken.save();
this.refreshTokens();
philrenaud marked this conversation as resolved.
Show resolved Hide resolved
this.flashMessages.add({
title: 'Example Token Created',
message: `${newToken.accessor}`,
type: 'success',
destroyOnClick: false,
timeout: 30000,
customAction: {
label: 'Copy to Clipboard',
action: () => {
navigator.clipboard.writeText(newToken.accessor);
},
},
});
} catch (err) {
this.error = {
title: 'Error creating new token',
description: err,
};

throw err;
}
})
createTestToken;

@task(function* (token) {
try {
yield token.deleteRecord();
yield token.save();
this.refreshTokens();
this.flashMessages.add({
title: 'Token successfully deleted',
type: 'success',
destroyOnClick: false,
timeout: 5000,
});
} catch (err) {
this.error = {
title: 'Error deleting token',
description: err,
};

throw err;
}
})
deleteToken;
}
4 changes: 3 additions & 1 deletion ui/app/routes/policies.js
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,9 @@ export default class PoliciesRoute extends Route.extend(
async model() {
return await hash({
policies: this.store.query('policy', { reload: true }),
tokens: this.store.query('token', { reload: true }),
tokens:
this.can.can('list tokens') &&
this.store.query('token', { reload: true }),
});
}
}
14 changes: 11 additions & 3 deletions ui/app/routes/policies/policy.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,23 @@ import Route from '@ember/routing/route';
import withForbiddenState from 'nomad-ui/mixins/with-forbidden-state';
import WithModelErrorHandling from 'nomad-ui/mixins/with-model-error-handling';
import { inject as service } from '@ember/service';
import { hash } from 'rsvp';

export default class PoliciesPolicyRoute extends Route.extend(
withForbiddenState,
WithModelErrorHandling
) {
@service store;
model(params) {
return this.store.findRecord('policy', decodeURIComponent(params.name), {
reload: true,
async model(params) {
return await hash({
policy: this.store.findRecord('policy', decodeURIComponent(params.name), {
reload: true,
}),
tokens: this.store
.peekAll('token')
.filter((token) =>
token.policyNames?.includes(decodeURIComponent(params.name))
),
});
}
philrenaud marked this conversation as resolved.
Show resolved Hide resolved
}
45 changes: 45 additions & 0 deletions ui/app/styles/components/policies.scss
Original file line number Diff line number Diff line change
Expand Up @@ -25,3 +25,48 @@ table.policies {
margin-bottom: 1rem;
}
}

.token-operations {
margin-bottom: 3rem;
display: grid;
grid-auto-flow: column;
grid-template-columns: repeat(auto-fit, 50%);
grid-auto-rows: minmax(100px, auto);
gap: 1rem;

.boxed-section {
padding: 0;
margin: 0;
display: grid;
grid-template-rows: auto 1fr;

.external-link svg {
position: relative;
top: 3px;
}

button.create-test-token, pre {
margin-top: 1rem;
}

pre {
display: grid;
grid-template-columns: 1fr auto;
align-content: flex-start;
white-space: normal;
overflow: visible;
}
}
}

@media #{$mq-hidden-gutter} {
.token-operations {
grid-auto-flow: row;
grid-template-columns: 1fr;
}
}
Comment on lines +62 to +67
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

De-columnizes things if you're on a narrow screen
image



table.tokens {
margin-bottom: 3rem;
}
22 changes: 13 additions & 9 deletions ui/app/templates/policies/index.hbs
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,9 @@
@class="policies no-mobile-condense" as |t|>
<t.head>
<th>Policy Name</th>
<th>Tokens</th>
{{#if (can "list token")}}
<th>Tokens</th>
{{/if}}
</t.head>
<t.body as |row|>
<tr data-test-policy-row {{on "click" (action "openPolicy" row.model)}}
Expand All @@ -43,14 +45,16 @@
<td data-test-policy-name>
<LinkTo @route="policies.policy" @model={{row.model.name}}>{{row.model.name}}</LinkTo>
</td>
<td data-test-policy-token-count>
<span>
{{row.model.tokens.length}}
{{#if (filter-by "isExpired" row.model.tokens)}}
<span class="number-expired">({{get (filter-by "isExpired" row.model.tokens) "length"}} expired)</span>
{{/if}}
</span>
</td>
{{#if (can "list token")}}
<td data-test-policy-token-count>
<span>
<span data-test-policy-total-tokens>{{row.model.tokens.length}}</span>
{{#if (filter-by "isExpired" row.model.tokens)}}
<span data-test-policy-expired-tokens class="number-expired">({{get (filter-by "isExpired" row.model.tokens) "length"}} expired)</span>
{{/if}}
</span>
</td>
{{/if}}
</tr>
</t.body>
</ListTable>
Expand Down
Loading