Skip to content

Commit

Permalink
KEYCLOAK-2501: Add-user should prompt user for password if not set
Browse files Browse the repository at this point in the history
  • Loading branch information
Bruno Oliveira committed Feb 19, 2016
1 parent d5a57a2 commit 34a16f0
Showing 1 changed file with 29 additions and 4 deletions.
Expand Up @@ -36,6 +36,7 @@
import org.keycloak.representations.idm.UserRepresentation;
import org.keycloak.util.JsonSerialization;

import java.io.Console;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
Expand Down Expand Up @@ -73,12 +74,16 @@ public static void main(String[] args) throws Exception {
printHelp(command);
} else {
try {
String password = command.getPassword();
checkRequired(command, "user");
checkRequired(command, "password");

if(isEmpty(command, "password")){
password = promptForInput();
}

File addUserFile = getAddUserFile(command);

createUser(addUserFile, command.getRealm(), command.getUser(), command.getPassword(), command.getRoles(), command.getIterations());
createUser(addUserFile, command.getRealm(), command.getUser(), password, command.getRoles(), command.getIterations());
} catch (Exception e) {
System.err.println(e.getMessage());
System.exit(1);
Expand Down Expand Up @@ -207,8 +212,7 @@ private static void createUser(File addUserFile, String realmName, String userNa
}

private static void checkRequired(Command command, String field) throws Exception {
Method m = command.getClass().getMethod("get" + Character.toUpperCase(field.charAt(0)) + field.substring(1));
if (m.invoke(command) == null) {
if (isEmpty(command, field)) {
Option option = command.getClass().getDeclaredField(field).getAnnotation(Option.class);
String optionName;
if (option != null && option.shortName() != '\u0000') {
Expand All @@ -220,6 +224,27 @@ private static void checkRequired(Command command, String field) throws Exceptio
}
}

private static Boolean isEmpty(Command command, String field) throws Exception {
Method m = command.getClass().getMethod("get" + Character.toUpperCase(field.charAt(0)) + field.substring(1));
if (m.invoke(command) == null) {
return true;
}
return false;
}

private static String promptForInput() throws Exception {
Console console = System.console();
if (console == null) {
throw new Exception("Couldn't get Console instance");
}
console.printf("Press ctrl-d (Unix) or ctrl-z (Windows) to exit\n");
char passwordArray[] = console.readPassword("Password: ");

if(passwordArray == null) System.exit(0);

return new String(passwordArray);
}

private static void printHelp(Command command) throws CommandNotFoundException {
CommandRegistry registry = new AeshCommandRegistryBuilder().command(command).create();
CommandContainer commandContainer = registry.getCommand(command.getClass().getAnnotation(CommandDefinition.class).name(), null);
Expand Down

0 comments on commit 34a16f0

Please sign in to comment.