-
Notifications
You must be signed in to change notification settings - Fork 2.3k
/
UsersCommand.java
241 lines (220 loc) · 9.25 KB
/
UsersCommand.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
/*
* Copyright (c) 2002-2016 "Neo Technology,"
* Network Engine for Objects in Lund AB [http://neotechnology.com]
*
* This file is part of Neo4j.
*
* Neo4j is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.neo4j.commandline.admin.security;
import java.nio.file.FileSystem;
import java.nio.file.Path;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import org.neo4j.commandline.admin.AdminCommand;
import org.neo4j.commandline.admin.CommandFailed;
import org.neo4j.commandline.admin.IncorrectUsage;
import org.neo4j.commandline.admin.OutsideWorld;
import org.neo4j.dbms.DatabaseManagementSystemSettings;
import org.neo4j.graphdb.factory.GraphDatabaseSettings;
import org.neo4j.helpers.Args;
import org.neo4j.io.fs.DefaultFileSystemAbstraction;
import org.neo4j.io.fs.DelegateFileSystemAbstraction;
import org.neo4j.kernel.configuration.Config;
import org.neo4j.logging.NullLogProvider;
import org.neo4j.server.configuration.ConfigLoader;
import org.neo4j.server.security.auth.BasicAuthManager;
import org.neo4j.server.security.auth.BasicAuthManagerFactory;
import org.neo4j.server.security.auth.BasicPasswordPolicy;
import org.neo4j.server.security.auth.FileUserRepository;
import org.neo4j.server.security.auth.PasswordPolicy;
import org.neo4j.time.Clocks;
public class UsersCommand implements AdminCommand
{
public static class Provider extends AdminCommand.Provider
{
public Provider()
{
super( "users" );
}
@Override
public Optional<String> arguments()
{
return Optional.of( "<subcommand> [<username>] [<password>] [--requires-password-change]" );
}
@Override
public String description()
{
return "Runs several possible sub-commands for managing the native users repository: 'list', 'create', " +
"'delete' and 'set-password'. When creating a new user, it is created with a requirement to " +
"change password on first login. Use the option --requires-password-change=false to disable this. " +
"Passing a username to the 'list' command will do a case-insensitive substring search.";
}
@Override
public AdminCommand create( Path homeDir, Path configDir, OutsideWorld outsideWorld )
{
return new UsersCommand( homeDir, configDir, outsideWorld );
}
}
private final Path homeDir;
private final Path configDir;
private OutsideWorld outsideWorld;
public UsersCommand( Path homeDir, Path configDir, OutsideWorld outsideWorld )
{
this.homeDir = homeDir;
this.configDir = configDir;
this.outsideWorld = outsideWorld;
}
@Override
public void execute( String[] args ) throws IncorrectUsage, CommandFailed
{
Args parsedArgs = Args.parse( args );
if ( parsedArgs.orphans().size() < 1 )
{
throw new IncorrectUsage(
"Missing arguments: expected at least one sub-command as argument: list, create, delete or " +
"set-password" );
}
String command = parsedArgs.orphans().size() > 0 ? parsedArgs.orphans().get( 0 ) : null;
String username = parsedArgs.orphans().size() > 1 ? parsedArgs.orphans().get( 1 ) : null;
String password = parsedArgs.orphans().size() > 2 ? parsedArgs.orphans().get( 2 ) : null;
boolean requiresPasswordChange = !hasFlagWithValue( parsedArgs, "requires-password-change", "false" );
try
{
switch ( command.trim().toLowerCase() )
{
case "list":
listUsers( username );
break;
case "set-password":
if ( username == null || password == null )
{
throw new IncorrectUsage(
"Missing arguments: 'users set-password' expects username and password arguments" );
}
setPassword( username, password, requiresPasswordChange );
break;
case "create":
if ( username == null || password == null )
{
throw new IncorrectUsage(
"Missing arguments: 'users create' expects username and password arguments" );
}
createUser( username, password, requiresPasswordChange );
break;
case "delete":
if ( username == null )
{
throw new IncorrectUsage( "Missing arguments: 'users delete' expects username argument" );
}
deleteUser( username );
break;
default:
throw new IncorrectUsage( "Unknown users command: " + command );
}
}
catch ( IncorrectUsage e )
{
throw e;
}
catch ( Exception e )
{
throw new CommandFailed( "Failed run 'users " + command + "' on '" + username + "': " + e.getMessage(), e );
}
catch ( Throwable t )
{
throw new CommandFailed( "Failed run 'users " + command + "' on '" + username + "': " + t.getMessage(),
new RuntimeException( t.getMessage() ) );
}
}
private boolean hasFlagWithValue( Args parsedArgs, String key, String expectedValue )
{
Map<String,String> argsMap = parsedArgs.asMap();
return argsMap.containsKey( key ) && (argsMap.get( key ).trim().toLowerCase().equals( expectedValue ));
}
private void listUsers( String contains ) throws Throwable
{
getAuthManager(); // ensure defaults are created
FileUserRepository userRepository = getUserRepository();
for ( String username : userRepository.getAllUsernames() )
{
if ( contains == null || username.toLowerCase().contains( contains.toLowerCase() ) )
{
outsideWorld.stdOutLine( username );
}
}
}
private void createUser( String username, String password, boolean requiresPasswordChange ) throws Throwable
{
BasicAuthManager authManager = getAuthManager();
authManager.newUser( username, password, requiresPasswordChange );
outsideWorld.stdOutLine( "Created new user '" + username + "'" );
}
private void deleteUser( String username ) throws Throwable
{
BasicAuthManager authManager = getAuthManager();
authManager.getUser( username ); // Will throw error on missing user
if ( authManager.getAllUsernames().size() == 1 )
{
throw new IllegalArgumentException( "Deleting the only remaining user '" + username + "' is not allowed" );
}
if ( authManager.deleteUser( username ) )
{
outsideWorld.stdOutLine( "Deleted user '" + username + "'" );
}
else
{
outsideWorld.stdErrLine( "Failed to delete user '" + username + "'" );
}
}
private void setPassword( String username, String password, boolean requirePasswordChange ) throws Throwable
{
BasicAuthManager authManager = getAuthManager();
authManager.setUserPassword( username, password, requirePasswordChange );
outsideWorld.stdOutLine( "Changed password for user '" + username + "'" );
}
private static Config loadNeo4jConfig( Path homeDir, Path configDir )
{
ConfigLoader configLoader = new ConfigLoader( settings() );
return configLoader.loadConfig(
Optional.of( homeDir.toFile() ),
Optional.of( configDir.resolve( "neo4j.conf" ).toFile() ) );
}
private static List<Class<?>> settings()
{
List<Class<?>> settings = new ArrayList<>();
settings.add( GraphDatabaseSettings.class );
settings.add( DatabaseManagementSystemSettings.class );
return settings;
}
private FileUserRepository getUserRepository() throws Throwable
{
Config config = loadNeo4jConfig( homeDir, configDir );
FileUserRepository userRepository =
BasicAuthManagerFactory.getUserRepository( config,
NullLogProvider.getInstance(), outsideWorld.fileSystem() );
userRepository.start();
return userRepository;
}
private BasicAuthManager getAuthManager() throws Throwable
{
FileUserRepository userRepository = getUserRepository();
PasswordPolicy passwordPolicy = new BasicPasswordPolicy();
BasicAuthManager authManager = new BasicAuthManager( userRepository, passwordPolicy, Clocks.systemClock() );
authManager.start(); // required to setup default users
return authManager;
}
}