Skip to content

Commit

Permalink
api-key generate: Display a descriptive error when the generation fai…
Browse files Browse the repository at this point in the history
…les due to a stale JWT

Change-type: patch
  • Loading branch information
thgreasi committed Nov 4, 2024
1 parent 2887ab8 commit 12897fa
Show file tree
Hide file tree
Showing 3 changed files with 32 additions and 3 deletions.
15 changes: 12 additions & 3 deletions npm-shrinkwrap.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -231,6 +231,7 @@
"is-root": "^2.1.0",
"js-yaml": "^4.1.0",
"JSONStream": "^1.0.3",
"jwt-decode": "^3.1.2",
"livepush": "^3.5.1",
"lodash": "^4.17.21",
"mime": "^2.4.6",
Expand Down
19 changes: 19 additions & 0 deletions src/commands/api-key/generate.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,18 @@ import { Args, Command } from '@oclif/core';
import { ExpectedError } from '../../errors';
import { getBalenaSdk, stripIndent } from '../../utils/lazy';

async function isLoggedInWithJwt() {
const balena = getBalenaSdk();
try {
const token = await balena.auth.getToken();
const { jwtDecode } = await import('jwt-decode');
jwtDecode(token);
return true;
} catch {
return false;
}
}

export default class GenerateCmd extends Command {
public static description = stripIndent`
Generate a new balenaCloud API key.
Expand Down Expand Up @@ -48,6 +60,13 @@ export default class GenerateCmd extends Command {
key = await getBalenaSdk().models.apiKey.create(params.name);
} catch (e) {
if (e.name === 'BalenaNotLoggedIn') {
if (await isLoggedInWithJwt()) {
throw new ExpectedError(stripIndent`
This command requires you to have been recently authenticated.
Please login again with 'balena login'.
In case you are using the Web authorization method, you need to logout and re-login to the dashboard first.
`);
}
throw new ExpectedError(stripIndent`
This command cannot be run when logged in with an API key.
Please login again with 'balena login' and select an alternative method.
Expand Down

0 comments on commit 12897fa

Please sign in to comment.