Skip to content

Commit

Permalink
Merge pull request #2885 from balena-io/non-sudo-api-keys
Browse files Browse the repository at this point in the history
api-key generate: Display a descriptive error when the generation fails due to a stale JWT
  • Loading branch information
flowzone-app[bot] authored Nov 5, 2024
2 parents 2887ab8 + 8577bb6 commit b4cff78
Show file tree
Hide file tree
Showing 3 changed files with 37 additions and 17 deletions.
34 changes: 17 additions & 17 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 { default: 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 b4cff78

Please sign in to comment.