View Javadoc
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  
12  package org.eclipse.jgit.console;
13  
14  import java.io.Console;
15  import java.net.Authenticator;
16  import java.net.PasswordAuthentication;
17  import java.text.MessageFormat;
18  
19  import org.eclipse.jgit.pgm.internal.CLIText;
20  import org.eclipse.jgit.util.CachedAuthenticator;
21  
22  /**
23   * Basic network prompt for username/password when using the console.
24   *
25   * @since 4.0
26   */
27  public class ConsoleAuthenticator extends CachedAuthenticator {
28  	/**
29  	 * Install this authenticator implementation into the JVM.
30  	 */
31  	public static void install() {
32  		final ConsoleAuthenticatornticator.html#ConsoleAuthenticator">ConsoleAuthenticator c = new ConsoleAuthenticator();
33  		if (c.cons == null)
34  			throw new NoClassDefFoundError(
35  					CLIText.get().noSystemConsoleAvailable);
36  		Authenticator.setDefault(c);
37  	}
38  
39  	private final Console cons = System.console();
40  
41  	/** {@inheritDoc} */
42  	@Override
43  	protected PasswordAuthentication promptPasswordAuthentication() {
44  		final String realm = formatRealm();
45  		String username = cons.readLine(MessageFormat.format(
46  				CLIText.get().usernameFor + " ", realm)); //$NON-NLS-1$
47  		if (username == null || username.isEmpty()) {
48  			return null;
49  		}
50  		char[] password = cons.readPassword(CLIText.get().password + " "); //$NON-NLS-1$
51  		if (password == null) {
52  			password = new char[0];
53  		}
54  		return new PasswordAuthentication(username, password);
55  	}
56  
57  	private String formatRealm() {
58  		final StringBuilder realm = new StringBuilder();
59  		if (getRequestorType() == RequestorType.PROXY) {
60  			realm.append(getRequestorType());
61  			realm.append(" "); //$NON-NLS-1$
62  			realm.append(getRequestingHost());
63  			if (getRequestingPort() > 0) {
64  				realm.append(":"); //$NON-NLS-1$
65  				realm.append(getRequestingPort());
66  			}
67  		} else {
68  			realm.append(getRequestingURL());
69  		}
70  		return realm.toString();
71  	}
72  }