run method

  1. @override
Future<void> run()
override

Runs this command.

The return value is wrapped in a Future if necessary and returned by CommandRunner.runCommand.

Implementation

@override
Future<void> run() async {
  final args = argResults!;
  final rest = args.rest;
  if (rest.isEmpty) {
    throw CliError('usage: grant add <principal> --role operator');
  }
  final roles = args['role'] as List<String>;
  if (roles.isEmpty) {
    throw CliError(
      'name at least one --role (viewer, operator, admin, node) — a '
      'credential that may do nothing is not a credential',
    );
  }

  final client = _apiClientFrom(args);
  try {
    final grant =
        await client.post('/grants', {
              'principal': rest.first,
              'roles': roles,
              'note': args['note'] ?? '',
            })
            as Map;

    stdout
      ..writeln('principal: ${grant['principal']}')
      ..writeln('roles:     ${(grant['roles'] as List).join(', ')}')
      ..writeln('grant id:  ${grant['id']}   (revoke it with this)')
      ..writeln('')
      ..writeln('token:     ${grant['token']}')
      ..writeln('')
      // Said out loud, because a Hub that stores a hash genuinely cannot show
      // it again — and an operator who assumes otherwise finds out too late.
      ..writeln(
        'This is the only time the token is shown: the Hub keeps a hash of '
        'it, not the token.',
      );
  } finally {
    client.close();
  }
}