diff --git a/npm-shrinkwrap.json b/npm-shrinkwrap.json index ed51c23b..3ad3f08f 100644 --- a/npm-shrinkwrap.json +++ b/npm-shrinkwrap.json @@ -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", diff --git a/package.json b/package.json index bfbd53e2..13cfb6f4 100644 --- a/package.json +++ b/package.json @@ -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", diff --git a/src/commands/api-key/generate.ts b/src/commands/api-key/generate.ts index 1eb381de..fcdeba0c 100644 --- a/src/commands/api-key/generate.ts +++ b/src/commands/api-key/generate.ts @@ -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.