blob: e4682780f4a66e1e4233df88778deba6b5e93399 (
plain) (
blame)
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
|
package org.openslx.imagemaster.session;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;
import org.apache.log4j.Logger;
import org.openslx.imagemaster.thrift.iface.SessionData;
import org.openslx.imagemaster.util.Hash;
/**
* Class for managing active user sessions. This class and all its function are
* (supposed to be) thread-safe.
*/
public class SessionManager
{
private static Logger log = Logger.getLogger( SessionManager.class );
// Map of currently known sessions
private static final Map<String, Session> sessions = new LinkedHashMap<>();
private static final Thread gcThread;
public static SessionData addSession( Session session )
{
final String authToken = Hash.md5( UUID.randomUUID().toString() );
final String sessionId = Hash.sha256( UUID.randomUUID().toString() );
synchronized ( sessions ) {
sessions.put( authToken, session );
sessions.put( sessionId, session );
}
return new SessionData( sessionId, authToken, session.getSatelliteAddress() );
}
public static Session getSessionFromToken( String token )
{
if ( token == null || token.length() != 64 )
return null;
final Session session;
synchronized ( sessions ) {
session = sessions.get( token );
}
if ( session == null || session.timedOut() ) {
return null;
}
return session;
}
static {
gcThread = new Thread( new Runnable() {
@Override
public void run()
{
for ( ;; ) {
try {
Thread.sleep( 1800L * 1000L );
} catch ( InterruptedException e ) {
}
synchronized ( sessions ) {
Iterator<Session> it = sessions.values().iterator();
while ( it.hasNext() ) {
final Session s = it.next();
if ( s.timedOut() ) {
it.remove();
}
}
}
}
}
} );
gcThread.start();
}
public static Object getSessionFromSessionId( String sessionId )
{
if ( sessionId == null || sessionId.length() != 32 )
return null;
final Session session;
synchronized ( sessions ) {
session = sessions.get( sessionId );
}
if ( session == null || session.timedOut() ) {
return null;
}
return session;
}
}
|