api-key generate: Display a descriptive error when the generation fails due to a stale JWT

Change-type: patch
This commit is contained in:
Thodoris Greasidis 2024-11-04 20:36:02 +02:00
parent 2887ab8200
commit e0f081623b
3 changed files with 21 additions and 0 deletions

1
npm-shrinkwrap.json generated
View File

@ -52,6 +52,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",

View File

@ -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",

View File

@ -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.
@ -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.