/
EventHandler.java
328 lines (289 loc) · 11.9 KB
/
EventHandler.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
/*
* Copyright 2006-2018 University of Dundee. All rights reserved.
* Use is subject to license terms supplied in LICENSE.txt
*/
package ome.security.basic;
import java.util.ArrayList;
import java.util.List;
import ome.api.StatefulServiceInterface;
import ome.conditions.ApiUsageException;
import ome.conditions.InternalException;
import ome.conditions.SessionTimeoutException;
import ome.model.meta.Event;
import ome.model.meta.EventLog;
import ome.services.messages.ContextMessage;
import ome.services.util.ReadOnlyStatus;
import ome.system.EventContext;
import ome.tools.hibernate.SessionFactory;
import ome.util.SqlAction;
import org.aopalliance.intercept.MethodInterceptor;
import org.aopalliance.intercept.MethodInvocation;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.hibernate.Session;
import org.springframework.context.ApplicationListener;
import org.springframework.orm.hibernate3.HibernateTemplate;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAttribute;
import org.springframework.transaction.interceptor.TransactionAttributeSource;
/**
* method interceptor responsible for login and creation of Events. Calls are
* made to the {@link BasicSecuritySystem} provided in the
* {@link EventHandler#EventHandler(SqlAction, BasicSecuritySystem, SessionFactory, TransactionAttributeSource, ReadOnlyStatus)
* constructor}.
*
* After the method is {@link MethodInterceptor#invoke(MethodInvocation)
* invoked} various cleanup actions are performed and finally all credentials
* all {@link BasicSecuritySystem#invalidateEventContext() cleared} from the
* {@link Thread}.
*
*
*
* @author Josh Moore <a
* href="mailto:josh.moore@gmx.de">josh.moore@gmx.de</a>
* @since 3.0
*/
public class EventHandler implements MethodInterceptor, ApplicationListener<ContextMessage>{
private static Logger log = LoggerFactory.getLogger(EventHandler.class);
protected final TransactionAttributeSource txSource;
protected final BasicSecuritySystem secSys;
protected final SessionFactory factory;
protected final SqlAction sql;
protected final boolean readOnly;
/**
* only public constructor, used for dependency injection. Requires an
* active {@link HibernateTemplate} and {@link BasicSecuritySystem}.
*
* @param sql the SQL action
* @param securitySystem the security system
* @param factory the Hibernate session factory
* @param txSource the Spring transaction attribute source
*/
@Deprecated
public EventHandler(SqlAction sql,
BasicSecuritySystem securitySystem, SessionFactory factory,
TransactionAttributeSource txSource) {
this(sql, securitySystem, factory, txSource, null);
}
public EventHandler(SqlAction sql,
BasicSecuritySystem securitySystem, SessionFactory factory,
TransactionAttributeSource txSource, ReadOnlyStatus readOnly) {
this.secSys = securitySystem;
this.txSource = txSource;
this.factory = factory;
this.sql = sql;
this.readOnly = readOnly == null ? false : readOnly.isReadOnlyDb();
}
/**
* If a {@link ContextMessage} is received then we need to either add a
* {@link ome.services.messages.ContextMessage.Push} login to the stack or
* {@link ome.services.messages.ContextMessage.Pop} remove one.
*/
@Override
public void onApplicationEvent(ContextMessage msg) {
final CurrentDetails cd = secSys.cd;
final Session session = factory.getSession();
if (msg instanceof ContextMessage.Pop){
secSys.disableReadFilter(session); // Disable old name
cd.logout();
secSys.enableReadFilter(session); // With old context
} else if (msg instanceof ContextMessage.Push) {
// We assume don't close and use the current readOnly setting
final EventContext curr = cd.getCurrentEventContext();
final boolean readOnly = curr.isReadOnly();
final boolean isClose = false;
// here we try to reproduce what's done in invoke
// with the addition of having a call context
// ourselves
secSys.disableReadFilter(session); // Disable old name
cd.login(cd.getLast()); // Login with same principal
cd.setContext(msg.context);
if (!doLogin(readOnly, isClose)) {
throw new InternalException("Failed to login on Push: " +
msg.context);
}
secSys.enableReadFilter(session); // With new context
}
}
/**
* Invocation interceptor for preparing this {@link Thread} for execution
* and subsequently resetting it.
*
* @see org.aopalliance.intercept.MethodInterceptor#invoke(org.aopalliance.intercept.MethodInvocation)
*/
public Object invoke(MethodInvocation arg0) throws Throwable {
boolean readOnly = checkReadOnly(arg0);
boolean stateful = StatefulServiceInterface.class.isAssignableFrom(arg0
.getThis().getClass());
boolean isClose = stateful && "close".equals(arg0.getMethod().getName());
if (!readOnly && this.readOnly) {
throw new ApiUsageException("This instance is read-only");
}
// ticket:1254
// and ticket:1266
final Session session = factory.getSession();
if (!readOnly) {
sql.deferConstraints();
}
if (!doLogin(readOnly, isClose)) {
return null;
}
boolean failure = false;
Object retVal = null;
try {
secSys.enableReadFilter(session);
retVal = arg0.proceed();
saveLogs(readOnly, session);
secSys.cd.loadPermissions(session);
return retVal;
} catch (Throwable ex) {
failure = true;
throw ex;
} finally {
try {
// on failure, we want to make sure that no one attempts
// any further changes.
if (failure) {
// TODO we should probably do some forced clean up here.
}
// stateful services should NOT be flushed, because that's part
// of the state that should hang around.
else if (stateful) {
// we don't want to do anything, really.
}
// read-only sessions should not have anything changed.
else if (readOnly) {
if (session.isDirty()) {
if (log.isDebugEnabled()) {
log.debug("Clearing dirty session.");
}
session.clear();
}
}
// stateless services, don't keep their sesssions about.
else {
session.flush();
if (session.isDirty()) {
throw new InternalException(
"Session is dirty. Cannot properly "
+ "reset security system. Must rollback.\n Session="
+ session);
}
secSys.disableReadFilter(session);
session.clear();
}
} finally {
secSys.disableReadFilter(session);
secSys.invalidateEventContext();
}
}
}
public boolean doLogin(boolean readOnly, boolean isClose) {
try {
secSys.loadEventContext(readOnly, isClose);
} catch (SessionTimeoutException ste) {
// If this is a CloseOnNoSessionContext then we skip all handling
// since almost any action by the close() method will try to load
// the context and will fail. This assumes that EventHandler is
// the most inner handler. If this changes, then this logic may
// need to be pushed down further.
if (ste.sessionContext instanceof
BasicSecurityWiring.CloseOnNoSessionContext) {
log.debug("CloseOnNoSessionContext. Skipping");
return false;
}
throw ste;
}
// now the user can be considered to be logged in.
EventContext ec = secSys.getEventContext();
if (!readOnly) {
sql.prepareSession(
ec.getCurrentEventId(),
ec.getCurrentUserId(),
ec.getCurrentGroupId());
}
if (log.isInfoEnabled()) {
StringBuilder sb = new StringBuilder();
sb.append(" Auth:\tuser=");
sb.append(ec.getCurrentUserId());
sb.append(",group=");
sb.append(ec.getCurrentGroupId());
sb.append(",event=");
sb.append(ec.getCurrentEventId());
sb.append("(");
sb.append(ec.getCurrentEventType());
sb.append("),sess=");
sb.append(ec.getCurrentSessionUuid());
Long shareId = ec.getCurrentShareId();
if (shareId != null) {
sb.append(",share=");
sb.append(shareId);
}
log.info(sb.toString());
}
return true;
}
/**
* checks method (and as a fallback the class) for the Spring
* {@link Transactional} annotation.
*
* @param mi
* Non-null method invocation.
* @return true if the {@link Transactional} annotation lists this method as
* read-only, or if no annotation is found.
*/
boolean checkReadOnly(MethodInvocation mi) {
TransactionAttribute ta = txSource.getTransactionAttribute(mi
.getMethod(), mi.getThis().getClass());
return ta == null ? true : ta.isReadOnly();
}
/**
* Calling clearLogs posits that these EventLogs were successfully saved,
* and so this method may raise an event signalling such. This could
* eventually be reworked to be fully within the security system.
*/
void saveLogs(boolean readOnly, Session session) {
// Grabbing a copy to prevent ConcurrentModificationEx
final List<EventLog> logs = new ArrayList<EventLog>(secSys.getLogs());
secSys.clearLogs();
if (logs == null || logs.size() == 0) {
return; // EARLY EXIT
}
if (readOnly) {
// If we reach here, we have logs when we shouldn't.
StringBuilder sb = new StringBuilder();
sb.append("EventLogs in readOnly transaction:\n");
for (EventLog eventLog : logs) {
sb.append(eventLog.getAction());
sb.append(" ");
sb.append(eventLog);
sb.append(eventLog.getEntityType());
sb.append(" ");
sb.append(eventLog.getEntityId());
sb.append("\b");
}
throw new InternalException(sb.toString());
}
try {
long lastValue = sql.nextValue("seq_eventlog", logs.size());
long id = lastValue - logs.size() + 1;
List<Object[]> batchData = new ArrayList<Object[]>();
for (EventLog l : logs) {
Event e = l.getEvent();
if (e.getId() == null) {
throw new RuntimeException("Transient event");
}
batchData
.add(new Object[] { id++, -35L, l.getEntityId(),
l.getEntityType(), l.getAction(),
l.getEvent().getId() });
}
sql.insertLogs(batchData);
} catch (Exception ex) {
log.error("Error saving event logs: " + logs, ex);
}
if (secSys.getLogs().size() > 0) {
throw new InternalException("More logs present after saveLogs()");
}
}
}