You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

ConsoleAuthenticator.java 2.1KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. /*
  2. * Copyright (C) 2009, Google Inc.
  3. * Copyright (C) 2008, Shawn O. Pearce <spearce@spearce.org> and others
  4. *
  5. * This program and the accompanying materials are made available under the
  6. * terms of the Eclipse Distribution License v. 1.0 which is available at
  7. * https://www.eclipse.org/org/documents/edl-v10.php.
  8. *
  9. * SPDX-License-Identifier: BSD-3-Clause
  10. */
  11. package org.eclipse.jgit.console;
  12. import java.io.Console;
  13. import java.net.Authenticator;
  14. import java.net.PasswordAuthentication;
  15. import java.text.MessageFormat;
  16. import org.eclipse.jgit.pgm.internal.CLIText;
  17. import org.eclipse.jgit.util.CachedAuthenticator;
  18. /**
  19. * Basic network prompt for username/password when using the console.
  20. *
  21. * @since 4.0
  22. */
  23. public class ConsoleAuthenticator extends CachedAuthenticator {
  24. /**
  25. * Install this authenticator implementation into the JVM.
  26. */
  27. public static void install() {
  28. final ConsoleAuthenticator c = new ConsoleAuthenticator();
  29. if (c.cons == null)
  30. throw new NoClassDefFoundError(
  31. CLIText.get().noSystemConsoleAvailable);
  32. Authenticator.setDefault(c);
  33. }
  34. private final Console cons = System.console();
  35. /** {@inheritDoc} */
  36. @Override
  37. protected PasswordAuthentication promptPasswordAuthentication() {
  38. final String realm = formatRealm();
  39. String username = cons.readLine(MessageFormat.format(
  40. CLIText.get().usernameFor + " ", realm)); //$NON-NLS-1$
  41. if (username == null || username.isEmpty()) {
  42. return null;
  43. }
  44. char[] password = cons.readPassword(CLIText.get().password + " "); //$NON-NLS-1$
  45. if (password == null) {
  46. password = new char[0];
  47. }
  48. return new PasswordAuthentication(username, password);
  49. }
  50. private String formatRealm() {
  51. final StringBuilder realm = new StringBuilder();
  52. if (getRequestorType() == RequestorType.PROXY) {
  53. realm.append(getRequestorType());
  54. realm.append(" "); //$NON-NLS-1$
  55. realm.append(getRequestingHost());
  56. if (getRequestingPort() > 0) {
  57. realm.append(":"); //$NON-NLS-1$
  58. realm.append(getRequestingPort());
  59. }
  60. } else {
  61. realm.append(getRequestingURL());
  62. }
  63. return realm.toString();
  64. }
  65. }