1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20 package eu.ehri.project.commands;
21
22 import com.tinkerpop.frames.FramedGraph;
23 import eu.ehri.project.core.GraphManager;
24 import eu.ehri.project.core.GraphManagerFactory;
25 import eu.ehri.project.definitions.EventTypes;
26 import eu.ehri.project.exceptions.DeserializationError;
27 import eu.ehri.project.exceptions.ItemNotFound;
28 import eu.ehri.project.exceptions.PermissionDenied;
29 import eu.ehri.project.exceptions.ValidationError;
30 import eu.ehri.project.models.EntityClass;
31 import eu.ehri.project.models.Group;
32 import eu.ehri.project.models.UserProfile;
33 import eu.ehri.project.models.base.Actioner;
34 import eu.ehri.project.persistence.ActionManager;
35 import eu.ehri.project.persistence.ActionManager.EventContext;
36 import org.apache.commons.cli.CommandLine;
37 import org.apache.commons.cli.Option;
38 import org.apache.commons.cli.Options;
39
40
41
42
43 public class UserMod extends BaseCommand {
44
45 final static String NAME = "usermod";
46
47 @Override
48 protected void setCustomOptions(Options options) {
49 options.addOption(Option.builder()
50 .longOpt("group")
51 .hasArg()
52 .type(String.class)
53 .desc("A group to add the user to")
54 .build());
55 options.addOption(Option.builder()
56 .longOpt("user")
57 .hasArg()
58 .required()
59 .type(String.class)
60 .hasArg().desc("Identifier of user taking action")
61 .build());
62 options.addOption(Option.builder()
63 .longOpt("log")
64 .hasArg()
65 .type(String.class)
66 .desc("Log message for update action.")
67 .build());
68 }
69
70 @Override
71 public String getUsage() {
72 return String.format("%s [OPTIONS] <user-identifier>", NAME);
73 }
74
75 @Override
76 public String getHelp() {
77 return "Add an existing user to a group";
78 }
79
80 @Override
81 public int execWithOptions(FramedGraph<?> graph,
82 CommandLine cmdLine) throws ItemNotFound, ValidationError,
83 PermissionDenied, DeserializationError {
84
85 GraphManager manager = GraphManagerFactory.getInstance(graph);
86 String logMessage = cmdLine.getOptionValue("c",
87 "Adding user to groups");
88
89 if (cmdLine.getArgList().size() < 1)
90 throw new RuntimeException(getUsage());
91
92
93 Actioner admin = manager.getEntity(cmdLine.getOptionValue("user"), Actioner.class);
94
95 String userId = cmdLine.getArgList().get(0);
96
97 String[] groups = {};
98 if (cmdLine.hasOption("group")) {
99 groups = cmdLine.getOptionValues("group");
100 }
101
102 UserProfile user = manager.getEntity(userId,
103 EntityClass.USER_PROFILE, UserProfile.class);
104
105 EventContext actionCtx = new ActionManager(graph).newEventContext(
106 user, admin, EventTypes.modification,
107 getLogMessage(logMessage));
108
109 for (String groupId : groups) {
110 Group group = manager.getEntity(groupId, EntityClass.GROUP,
111 Group.class);
112 group.addMember(user);
113 actionCtx.addSubjects(group);
114 }
115 actionCtx.commit();
116
117 return 0;
118 }
119 }