001
014
015 package com.liferay.portal.security.auth;
016
017 import com.liferay.portal.kernel.uuid.PortalUUIDUtil;
018
019 import java.util.Collections;
020 import java.util.Iterator;
021 import java.util.Map;
022 import java.util.Set;
023 import java.util.SortedMap;
024 import java.util.TreeMap;
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 _tokens.put(expireTime, token);
069
070 return token;
071 }
072
073 private static void _expungeExpiredToken(long currentTime) {
074 SortedMap<Long, String> headMap = _tokens.headMap(currentTime);
075
076 headMap.clear();
077 }
078
079 private static final SortedMap<Long, String> _tokens =
080 Collections.synchronizedSortedMap(new TreeMap<Long, String>());
081
082 }