001
014
015 package com.liferay.portal.servlet.filters.secure;
016
017 import com.liferay.portal.kernel.util.Digester;
018 import com.liferay.portal.kernel.util.DigesterUtil;
019 import com.liferay.portal.kernel.util.Time;
020 import com.liferay.portal.model.Company;
021 import com.liferay.portal.service.CompanyLocalServiceUtil;
022 import com.liferay.portal.util.PropsValues;
023
024 import java.util.concurrent.DelayQueue;
025 import java.util.concurrent.Delayed;
026 import java.util.concurrent.TimeUnit;
027
028
031 public class NonceUtil {
032
033 public static String generate(long companyId, String remoteAddress) {
034 String companyKey = null;
035
036 try {
037 Company company = CompanyLocalServiceUtil.getCompanyById(companyId);
038
039 companyKey = company.getKey();
040 }
041 catch (Exception e) {
042 throw new RuntimeException("Invalid companyId " + companyId, e);
043 }
044
045 long timestamp = System.currentTimeMillis();
046
047 String nonce = DigesterUtil.digestHex(
048 Digester.MD5, remoteAddress, String.valueOf(timestamp), companyKey);
049
050 _nonceDelayQueue.put(new NonceDelayed(nonce));
051
052 return nonce;
053 }
054
055 public static boolean verify(String nonce) {
056 _cleanUp();
057
058 return _nonceDelayQueue.contains(new NonceDelayed(nonce));
059 }
060
061 private static void _cleanUp() {
062 while (_nonceDelayQueue.poll() != null);
063 }
064
065 private static final long _NONCE_EXPIRATION =
066 PropsValues.WEBDAV_NONCE_EXPIRATION * Time.MINUTE;
067
068 private static DelayQueue<NonceDelayed> _nonceDelayQueue =
069 new DelayQueue<NonceDelayed>();
070
071 private static class NonceDelayed implements Delayed {
072
073 public NonceDelayed(String nonce) {
074 if (nonce == null) {
075 throw new NullPointerException("Nonce is null");
076 }
077
078 _nonce = nonce;
079 _createTime = System.currentTimeMillis();
080 }
081
082 public long getDelay(TimeUnit timeUnit) {
083 long leftDelayTime =
084 _NONCE_EXPIRATION + _createTime - System.currentTimeMillis();
085
086 return timeUnit.convert(leftDelayTime, TimeUnit.MILLISECONDS);
087 }
088
089 public int compareTo(Delayed delayed) {
090 NonceDelayed nonceDelayed = (NonceDelayed)delayed;
091
092 long result = _createTime - nonceDelayed._createTime;
093
094 if (result == 0) {
095 return 0;
096 }
097 else if (result > 0) {
098 return 1;
099 }
100 else {
101 return -1;
102 }
103 }
104
105 @Override
106 public boolean equals(Object obj) {
107 if (this == obj) {
108 return true;
109 }
110
111 if (!(obj instanceof NonceDelayed)) {
112 return false;
113 }
114
115 NonceDelayed nonceDelayed = (NonceDelayed)obj;
116
117 if (_nonce.equals(nonceDelayed._nonce)) {
118 return true;
119 }
120
121 return false;
122 }
123
124 @Override
125 public int hashCode() {
126 return _nonce.hashCode();
127 }
128
129 private final long _createTime;
130 private final String _nonce;
131
132 }
133
134 }