forked from spring-projects/spring-framework
/
DefaultUserDestinationResolver.java
332 lines (286 loc) · 11.1 KB
/
DefaultUserDestinationResolver.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
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
/*
* Copyright 2002-2018 the original author or authors.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.springframework.messaging.simp.user;
import java.security.Principal;
import java.util.Collections;
import java.util.HashSet;
import java.util.Set;
import org.apache.commons.logging.Log;
import org.springframework.lang.Nullable;
import org.springframework.messaging.Message;
import org.springframework.messaging.MessageHeaders;
import org.springframework.messaging.simp.SimpLogging;
import org.springframework.messaging.simp.SimpMessageHeaderAccessor;
import org.springframework.messaging.simp.SimpMessageType;
import org.springframework.util.Assert;
import org.springframework.util.PathMatcher;
import org.springframework.util.Base64Utils;
/**
* A default implementation of {@code UserDestinationResolver} that relies
* on a {@link SimpUserRegistry} to find active sessions for a user.
*
* <p>When a user attempts to subscribe, e.g. to "/user/queue/position-updates",
* the "/user" prefix is removed and a unique suffix added based on the session
* id, e.g. "/queue/position-updates-useri9oqdfzo" to ensure different users can
* subscribe to the same logical destination without colliding.
*
* <p>When sending to a user, e.g. "/user/{username}/queue/position-updates", the
* "/user/{username}" prefix is removed and a suffix based on active session id's
* is added, e.g. "/queue/position-updates-useri9oqdfzo".
*
* @author Rossen Stoyanchev
* @author Brian Clozel
* @since 4.0
*/
public class DefaultUserDestinationResolver implements UserDestinationResolver {
private static final Log logger = SimpLogging.forLogName(DefaultUserDestinationResolver.class);
private final SimpUserRegistry userRegistry;
private String prefix = "/user/";
private boolean removeLeadingSlash = false;
/**
* Create an instance that will access user session id information through
* the provided registry.
* @param userRegistry the registry, never {@code null}
*/
public DefaultUserDestinationResolver(SimpUserRegistry userRegistry) {
Assert.notNull(userRegistry, "SimpUserRegistry must not be null");
this.userRegistry = userRegistry;
}
/**
* Return the configured {@link SimpUserRegistry}.
*/
public SimpUserRegistry getSimpUserRegistry() {
return this.userRegistry;
}
/**
* The prefix used to identify user destinations. Any destinations that do not
* start with the given prefix are not be resolved.
* <p>The default prefix is "/user/".
* @param prefix the prefix to use
*/
public void setUserDestinationPrefix(String prefix) {
Assert.hasText(prefix, "Prefix must not be empty");
this.prefix = (prefix.endsWith("/") ? prefix : prefix + "/");
}
/**
* Return the configured prefix for user destinations.
*/
public String getDestinationPrefix() {
return this.prefix;
}
/**
* Use this property to indicate whether the leading slash from translated
* user destinations should be removed or not. This depends on the
* destination prefixes the message broker is configured with.
* <p>By default this is set to {@code false}, i.e.
* "do not change the target destination", although
* {@link org.springframework.messaging.simp.config.AbstractMessageBrokerConfiguration
* AbstractMessageBrokerConfiguration} may change that to {@code true}
* if the configured destinations do not have a leading slash.
* @param remove whether to remove the leading slash
* @since 4.3.14
*/
public void setRemoveLeadingSlash(boolean remove) {
this.removeLeadingSlash = remove;
}
/**
* Whether to remove the leading slash from target destinations.
* @since 4.3.14
*/
public boolean isRemoveLeadingSlash() {
return this.removeLeadingSlash;
}
/**
* Provide the {@code PathMatcher} in use for working with destinations
* which in turn helps to determine whether the leading slash should be
* kept in actual destinations after removing the
* {@link #setUserDestinationPrefix userDestinationPrefix}.
* <p>By default actual destinations have a leading slash, e.g.
* {@code /queue/position-updates} which makes sense with brokers that
* support destinations with slash as separator. When a {@code PathMatcher}
* is provided that supports an alternative separator, then resulting
* destinations won't have a leading slash, e.g. {@code
* jms.queue.position-updates}.
* @param pathMatcher the PathMatcher used to work with destinations
* @since 4.3
* @deprecated as of 4.3.14 this property is no longer used and is replaced
* by {@link #setRemoveLeadingSlash(boolean)} that indicates more explicitly
* whether to keep the leading slash which may or may not be the case
* regardless of how the {@code PathMatcher} is configured.
*/
@Deprecated
public void setPathMatcher(@Nullable PathMatcher pathMatcher) {
// Do nothing
}
@Override
@Nullable
public UserDestinationResult resolveDestination(Message<?> message) {
ParseResult parseResult = parse(message);
if (parseResult == null) {
return null;
}
String user = parseResult.getUser();
String sourceDestination = parseResult.getSourceDestination();
Set<String> targetSet = new HashSet<>();
for (String sessionId : parseResult.getSessionIds()) {
String actualDestination = parseResult.getActualDestination();
String targetDestination = getTargetDestination(
sourceDestination, actualDestination, sessionId, user);
if (targetDestination != null) {
targetSet.add(targetDestination);
}
}
String subscribeDestination = parseResult.getSubscribeDestination();
return new UserDestinationResult(sourceDestination, targetSet, subscribeDestination, user);
}
@Nullable
private ParseResult parse(Message<?> message) {
MessageHeaders headers = message.getHeaders();
String sourceDestination = SimpMessageHeaderAccessor.getDestination(headers);
if (sourceDestination == null || !checkDestination(sourceDestination, this.prefix)) {
return null;
}
SimpMessageType messageType = SimpMessageHeaderAccessor.getMessageType(headers);
if (messageType != null) {
switch (messageType) {
case SUBSCRIBE:
case UNSUBSCRIBE:
return parseSubscriptionMessage(message, sourceDestination);
case MESSAGE:
return parseMessage(headers, sourceDestination);
}
}
return null;
}
@Nullable
private ParseResult parseSubscriptionMessage(Message<?> message, String sourceDestination) {
MessageHeaders headers = message.getHeaders();
String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
if (sessionId == null) {
logger.error("No session id. Ignoring " + message);
return null;
}
int prefixEnd = this.prefix.length() - 1;
String actualDestination = sourceDestination.substring(prefixEnd);
if (isRemoveLeadingSlash()) {
actualDestination = actualDestination.substring(1);
}
Principal principal = SimpMessageHeaderAccessor.getUser(headers);
String user = (principal != null ? principal.getName() : null);
Set<String> sessionIds = Collections.singleton(sessionId);
return new ParseResult(sourceDestination, actualDestination, sourceDestination, sessionIds, user);
}
private ParseResult parseMessage(MessageHeaders headers, String sourceDest) {
int prefixEnd = this.prefix.length();
int userEnd = sourceDest.indexOf('/', prefixEnd);
Assert.isTrue(userEnd > 0, "Expected destination pattern \"/user/{userId}/**\"");
String actualDest = sourceDest.substring(userEnd);
String subscribeDest = this.prefix.substring(0, prefixEnd - 1) + actualDest;
String userName = sourceDest.substring(prefixEnd, userEnd);
if (userName.startsWith("B64:"))
userName = new String(Base64Utils.decodeFromUrlSafeString(userName.split("B64:")[1]));
String sessionId = SimpMessageHeaderAccessor.getSessionId(headers);
Set<String> sessionIds;
if (userName.equals(sessionId)) {
userName = null;
sessionIds = Collections.singleton(sessionId);
}
else {
sessionIds = getSessionIdsByUser(userName, sessionId);
}
if (isRemoveLeadingSlash()) {
actualDest = actualDest.substring(1);
}
return new ParseResult(sourceDest, actualDest, subscribeDest, sessionIds, userName);
}
private Set<String> getSessionIdsByUser(String userName, @Nullable String sessionId) {
Set<String> sessionIds;
SimpUser user = this.userRegistry.getUser(userName);
if (user != null) {
if (sessionId != null && user.getSession(sessionId) != null) {
sessionIds = Collections.singleton(sessionId);
}
else {
Set<SimpSession> sessions = user.getSessions();
sessionIds = new HashSet<>(sessions.size());
for (SimpSession session : sessions) {
sessionIds.add(session.getId());
}
}
}
else {
sessionIds = Collections.emptySet();
}
return sessionIds;
}
protected boolean checkDestination(String destination, String requiredPrefix) {
return destination.startsWith(requiredPrefix);
}
/**
* This method determines how to translate the source "user" destination to an
* actual target destination for the given active user session.
* @param sourceDestination the source destination from the input message.
* @param actualDestination a subset of the destination without any user prefix.
* @param sessionId the id of an active user session, never {@code null}.
* @param user the target user, possibly {@code null}, e.g if not authenticated.
* @return a target destination, or {@code null} if none
*/
@SuppressWarnings("unused")
@Nullable
protected String getTargetDestination(String sourceDestination, String actualDestination,
String sessionId, @Nullable String user) {
return actualDestination + "-user" + sessionId;
}
@Override
public String toString() {
return "DefaultUserDestinationResolver[prefix=" + this.prefix + "]";
}
/**
* A temporary placeholder for a parsed source "user" destination.
*/
private static class ParseResult {
private final String sourceDestination;
private final String actualDestination;
private final String subscribeDestination;
private final Set<String> sessionIds;
@Nullable
private final String user;
public ParseResult(String sourceDest, String actualDest, String subscribeDest,
Set<String> sessionIds, @Nullable String user) {
this.sourceDestination = sourceDest;
this.actualDestination = actualDest;
this.subscribeDestination = subscribeDest;
this.sessionIds = sessionIds;
this.user = user;
}
public String getSourceDestination() {
return this.sourceDestination;
}
public String getActualDestination() {
return this.actualDestination;
}
public String getSubscribeDestination() {
return this.subscribeDestination;
}
public Set<String> getSessionIds() {
return this.sessionIds;
}
@Nullable
public String getUser() {
return this.user;
}
}
}