diff --git a/src/commands/create-apikey.ts b/src/commands/create-apikey.ts new file mode 100644 index 0000000..8ec7013 --- /dev/null +++ b/src/commands/create-apikey.ts @@ -0,0 +1,63 @@ +import {BaseCommand} from '../lib' +import {getEnvironment} from '../lib/environments' +import {flags} from '@oclif/command' +import fetch from 'node-fetch' +import {cli} from 'cli-ux' + +export default class CreateApikey extends BaseCommand { + static description = 'Create an API key for a Backend by id' + static hidden = true + + static examples = [ + '$ slash-graphql create-apikey "0xid"', + ] + + static flags = { + ...BaseCommand.commonFlags, + name: flags.string({char: 'n', description: 'Client name', default: 'slash-graphql-cli'}), + role: flags.string({char: 'r', description: 'Client role', default: 'client', options: ['admin', 'client']}) + } + + static args = [{name: 'id', description: 'Backend id', required: true}] + + async run() { + const opts = this.parse(CreateApikey) + const {apiServer, authFile} = getEnvironment(opts.flags.environment) + + const id = opts.args.id + + if (!id.match(/0x[0-9a-f]+/)) { + this.error(`Invalid id ${id}`) + } + + const token = await this.getAccessToken(apiServer, authFile) + if (!token) { + this.error('Please login with `slash-graphql login`') + } + + const backend = this.findBackendByUid(apiServer, token, id) + + if (!backend) { + this.error('Cannot find the backend that you are trying to create an API key for. Please run `slash-graphql list-backends` to get a list of backends') + } + + const response = await fetch(`${apiServer}/deployment/${id}/api-keys`, { + method: 'POST', + headers: { + Authorization: `Bearer ${token}`, + }, + body: JSON.stringify({ + name: opts.args.name, + role: opts.args.role + }) + }) + if (response.status !== 200) { + this.error(`Unable to create API key. Try logging in again\n${await response.text()}`) + } + const apiKey = await response.json() as APIKey + + if (!opts.flags.quiet) { + this.log(apiKey.key) + } + } +} diff --git a/src/types.d.ts b/src/types.d.ts index a19bf0a..88775ff 100644 --- a/src/types.d.ts +++ b/src/types.d.ts @@ -7,6 +7,13 @@ interface APIBackend { owner: string; } +interface APIKey { + key: string; + name: string; + role: string; + uid: string; +} + interface AuthConfig { apiTime: number; access_token: string;