001
014
015 package com.liferay.portal.security.auth;
016
017 import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
018
019 import java.util.Iterator;
020 import java.util.Map;
021 import java.util.Set;
022 import java.util.SortedMap;
023 import java.util.concurrent.ConcurrentNavigableMap;
024 import java.util.concurrent.ConcurrentSkipListMap;
025
026
029 public class TransientTokenUtil {
030
031 public static boolean checkToken(String token) {
032 long currentTime = System.currentTimeMillis();
033
034 _expungeExpiredToken(currentTime);
035
036 Set<Map.Entry<Long, String>> tokens = _tokens.entrySet();
037
038 Iterator<Map.Entry<Long, String>> itr = tokens.iterator();
039
040 while (itr.hasNext()) {
041 Map.Entry<Long, String> entry = itr.next();
042
043 String curToken = entry.getValue();
044
045 if (token.equals(curToken)) {
046 itr.remove();
047
048 return true;
049 }
050 }
051
052 return false;
053 }
054
055 public static void clearAll() {
056 _tokens.clear();
057 }
058
059 public static String createToken(long timeTolive) {
060 long currentTime = System.currentTimeMillis();
061
062 long expireTime = currentTime + timeTolive;
063
064 _expungeExpiredToken(currentTime);
065
066 String token = PortalUUIDUtil.generate();
067
068 while (_tokens.putIfAbsent(expireTime, token) != null) {
069 expireTime++;
070 }
071
072 return token;
073 }
074
075 private static void _expungeExpiredToken(long currentTime) {
076 SortedMap<Long, String> headMap = _tokens.headMap(currentTime);
077
078 headMap.clear();
079 }
080
081 private static final ConcurrentNavigableMap<Long, String> _tokens =
082 new ConcurrentSkipListMap<Long, String>();
083
084 }