source: josm/trunk/src/org/openstreetmap/josm/gui/JosmUserIdentityManager.java@ 11810

Last change on this file since 11810 was 11746, checked in by Don-vip, 7 years ago

PMD - Strict Exceptions

  • Property svn:eol-style set to native
File size: 11.7 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.gui;
3
4import static org.openstreetmap.josm.tools.I18n.tr;
5
6import java.text.MessageFormat;
7
8import org.openstreetmap.josm.Main;
9import org.openstreetmap.josm.data.Preferences.PreferenceChangeEvent;
10import org.openstreetmap.josm.data.Preferences.PreferenceChangedListener;
11import org.openstreetmap.josm.data.osm.User;
12import org.openstreetmap.josm.data.osm.UserInfo;
13import org.openstreetmap.josm.data.preferences.StringSetting;
14import org.openstreetmap.josm.gui.preferences.server.OAuthAccessTokenHolder;
15import org.openstreetmap.josm.gui.progress.NullProgressMonitor;
16import org.openstreetmap.josm.io.OnlineResource;
17import org.openstreetmap.josm.io.OsmApi;
18import org.openstreetmap.josm.io.OsmServerUserInfoReader;
19import org.openstreetmap.josm.io.OsmTransferException;
20import org.openstreetmap.josm.io.auth.CredentialsManager;
21import org.openstreetmap.josm.tools.CheckParameterUtil;
22import org.openstreetmap.josm.tools.JosmRuntimeException;
23
24/**
25 * JosmUserIdentityManager is a global object which keeps track of what JOSM knows about
26 * the identity of the current user.
27 *
28 * JOSM can be operated anonymously provided the current user never invokes an operation
29 * on the OSM server which required authentication. In this case JOSM neither knows
30 * the user name of the OSM account of the current user nor its unique id. Perhaps the
31 * user doesn't have one.
32 *
33 * If the current user supplies a user name and a password in the JOSM preferences JOSM
34 * can partially identify the user.
35 *
36 * The current user is fully identified if JOSM knows both the user name and the unique
37 * id of the users OSM account. The latter is retrieved from the OSM server with a
38 * <tt>GET /api/0.6/user/details</tt> request, submitted with the user name and password
39 * of the current user.
40 *
41 * The global JosmUserIdentityManager listens to {@link PreferenceChangeEvent}s and keeps track
42 * of what the current JOSM instance knows about the current user. Other subsystems can
43 * let the global JosmUserIdentityManager know in case they fully identify the current user, see
44 * {@link #setFullyIdentified}.
45 *
46 * The information kept by the JosmUserIdentityManager can be used to
47 * <ul>
48 * <li>safely query changesets owned by the current user based on its user id, not on its user name</li>
49 * <li>safely search for objects last touched by the current user based on its user id, not on its user name</li>
50 * </ul>
51 *
52 */
53public final class JosmUserIdentityManager implements PreferenceChangedListener {
54
55 private static JosmUserIdentityManager instance;
56
57 /**
58 * Replies the unique instance of the JOSM user identity manager
59 *
60 * @return the unique instance of the JOSM user identity manager
61 */
62 public static synchronized JosmUserIdentityManager getInstance() {
63 if (instance == null) {
64 instance = new JosmUserIdentityManager();
65 if (OsmApi.isUsingOAuth() && OAuthAccessTokenHolder.getInstance().containsAccessToken() &&
66 !Main.isOffline(OnlineResource.OSM_API)) {
67 try {
68 instance.initFromOAuth();
69 } catch (JosmRuntimeException | IllegalArgumentException | IllegalStateException e) {
70 Main.error(e);
71 // Fall back to preferences if OAuth identification fails for any reason
72 instance.initFromPreferences();
73 }
74 } else {
75 instance.initFromPreferences();
76 }
77 Main.pref.addPreferenceChangeListener(instance);
78 }
79 return instance;
80 }
81
82 private String userName;
83 private UserInfo userInfo;
84 private boolean accessTokenKeyChanged;
85 private boolean accessTokenSecretChanged;
86
87 private JosmUserIdentityManager() {
88 }
89
90 /**
91 * Remembers the fact that the current JOSM user is anonymous.
92 */
93 public void setAnonymous() {
94 userName = null;
95 userInfo = null;
96 }
97
98 /**
99 * Remebers the fact that the current JOSM user is partially identified
100 * by the user name of its OSM account.
101 *
102 * @param userName the user name. Must not be null. Must not be empty (whitespace only).
103 * @throws IllegalArgumentException if userName is null
104 * @throws IllegalArgumentException if userName is empty
105 */
106 public void setPartiallyIdentified(String userName) {
107 CheckParameterUtil.ensureParameterNotNull(userName, "userName");
108 if (userName.trim().isEmpty())
109 throw new IllegalArgumentException(
110 MessageFormat.format("Expected non-empty value for parameter ''{0}'', got ''{1}''", "userName", userName));
111 this.userName = userName;
112 userInfo = null;
113 }
114
115 /**
116 * Remembers the fact that the current JOSM user is fully identified with a
117 * verified pair of user name and user id.
118 *
119 * @param username the user name. Must not be null. Must not be empty.
120 * @param userinfo additional information about the user, retrieved from the OSM server and including the user id
121 * @throws IllegalArgumentException if userName is null
122 * @throws IllegalArgumentException if userName is empty
123 * @throws IllegalArgumentException if userinfo is null
124 */
125 public void setFullyIdentified(String username, UserInfo userinfo) {
126 CheckParameterUtil.ensureParameterNotNull(username, "username");
127 if (username.trim().isEmpty())
128 throw new IllegalArgumentException(tr("Expected non-empty value for parameter ''{0}'', got ''{1}''", "userName", userName));
129 CheckParameterUtil.ensureParameterNotNull(userinfo, "userinfo");
130 this.userName = username;
131 this.userInfo = userinfo;
132 }
133
134 /**
135 * Replies true if the current JOSM user is anonymous.
136 *
137 * @return {@code true} if the current user is anonymous.
138 */
139 public boolean isAnonymous() {
140 return userName == null && userInfo == null;
141 }
142
143 /**
144 * Replies true if the current JOSM user is partially identified.
145 *
146 * @return true if the current JOSM user is partially identified.
147 */
148 public boolean isPartiallyIdentified() {
149 return userName != null && userInfo == null;
150 }
151
152 /**
153 * Replies true if the current JOSM user is fully identified.
154 *
155 * @return true if the current JOSM user is fully identified.
156 */
157 public boolean isFullyIdentified() {
158 return userName != null && userInfo != null;
159 }
160
161 /**
162 * Replies the user name of the current JOSM user. null, if {@link #isAnonymous()} is true.
163 *
164 * @return the user name of the current JOSM user
165 */
166 public String getUserName() {
167 return userName;
168 }
169
170 /**
171 * Replies the user id of the current JOSM user. 0, if {@link #isAnonymous()} or
172 * {@link #isPartiallyIdentified()} is true.
173 *
174 * @return the user id of the current JOSM user
175 */
176 public int getUserId() {
177 if (userInfo == null) return 0;
178 return userInfo.getId();
179 }
180
181 /**
182 * Replies verified additional information about the current user if the user is
183 * {@link #isFullyIdentified()}.
184 *
185 * @return verified additional information about the current user
186 */
187 public UserInfo getUserInfo() {
188 return userInfo;
189 }
190
191 /**
192 * Returns the identity as a {@link User} object
193 *
194 * @return the identity as user, or {@link User#getAnonymous()} if {@link #isAnonymous()}
195 */
196 public User asUser() {
197 return isAnonymous() ? User.getAnonymous() : User.createOsmUser(userInfo != null ? userInfo.getId() : 0, userName);
198 }
199
200 /**
201 * Initializes the user identity manager from Basic Authentication values in the {@link org.openstreetmap.josm.data.Preferences}
202 * This method should be called if {@code osm-server.auth-method} is set to {@code basic}.
203 * @see #initFromOAuth
204 */
205 public void initFromPreferences() {
206 String userName = CredentialsManager.getInstance().getUsername();
207 if (isAnonymous()) {
208 if (userName != null && !userName.trim().isEmpty()) {
209 setPartiallyIdentified(userName);
210 }
211 } else {
212 if (userName != null && !userName.equals(this.userName)) {
213 setPartiallyIdentified(userName);
214 }
215 // else: same name in the preferences as JOSM already knows about.
216 // keep the state, be it partially or fully identified
217 }
218 }
219
220 /**
221 * Initializes the user identity manager from OAuth request of user details.
222 * This method should be called if {@code osm-server.auth-method} is set to {@code oauth}.
223 * @see #initFromPreferences
224 * @since 5434
225 */
226 public void initFromOAuth() {
227 try {
228 UserInfo info = new OsmServerUserInfoReader().fetchUserInfo(NullProgressMonitor.INSTANCE);
229 setFullyIdentified(info.getDisplayName(), info);
230 } catch (IllegalArgumentException | OsmTransferException e) {
231 Main.error(e);
232 }
233 }
234
235 /**
236 * Replies true if the user with name <code>username</code> is the current user
237 *
238 * @param username the user name
239 * @return true if the user with name <code>username</code> is the current user
240 */
241 public boolean isCurrentUser(String username) {
242 return this.userName != null && this.userName.equals(username);
243 }
244
245 /**
246 * Replies true if the current user is {@link #isFullyIdentified() fully identified} and the {@link #getUserId() user ids} match,
247 * or if the current user is not {@link #isFullyIdentified() fully identified} and the {@link #userName user names} match.
248 *
249 * @param user the user to test
250 * @return true if given user is the current user
251 */
252 public boolean isCurrentUser(User user) {
253 if (user == null) {
254 return false;
255 } else if (isFullyIdentified()) {
256 return getUserId() == user.getId();
257 } else {
258 return isCurrentUser(user.getName());
259 }
260 }
261
262 /* ------------------------------------------------------------------- */
263 /* interface PreferenceChangeListener */
264 /* ------------------------------------------------------------------- */
265 @Override
266 public void preferenceChanged(PreferenceChangeEvent evt) {
267 switch (evt.getKey()) {
268 case "osm-server.username":
269 String newUserName = null;
270 if (evt.getNewValue() instanceof StringSetting) {
271 newUserName = ((StringSetting) evt.getNewValue()).getValue();
272 }
273 if (newUserName == null || newUserName.trim().isEmpty()) {
274 setAnonymous();
275 } else {
276 if (!newUserName.equals(userName)) {
277 setPartiallyIdentified(newUserName);
278 }
279 }
280 return;
281 case "osm-server.url":
282 String newUrl = null;
283 if (evt.getNewValue() instanceof StringSetting) {
284 newUrl = ((StringSetting) evt.getNewValue()).getValue();
285 }
286 if (newUrl == null || newUrl.trim().isEmpty()) {
287 setAnonymous();
288 } else if (isFullyIdentified()) {
289 setPartiallyIdentified(getUserName());
290 }
291 break;
292 case "oauth.access-token.key":
293 accessTokenKeyChanged = true;
294 break;
295 case "oauth.access-token.secret":
296 accessTokenSecretChanged = true;
297 break;
298 default: // Do nothing
299 }
300
301 if (accessTokenKeyChanged && accessTokenSecretChanged) {
302 accessTokenKeyChanged = false;
303 accessTokenSecretChanged = false;
304 if (OsmApi.isUsingOAuth()) {
305 getInstance().initFromOAuth();
306 }
307 }
308 }
309}
Note: See TracBrowser for help on using the repository browser.