Mentawai Web Framework

Compare Revisions

Ignore whitespace Rev 351 → Rev 352

/trunk/src/main/java/org/mentawai/filter/RestAuthenticationFilter.java
New file
0,0 → 1,69
package org.mentawai.filter;
 
import org.mentawai.core.Action;
import org.mentawai.core.Filter;
import org.mentawai.core.FilterException;
import org.mentawai.core.Input;
import org.mentawai.core.InvocationChain;
import org.mentawai.util.StringUtils;
 
public abstract class RestAuthenticationFilter implements Filter {
@Override
public String filter(InvocationChain chain) throws Exception {
Action action = chain.getAction();
if (action instanceof AuthenticationFree) {
return chain.invoke();
}
Input input = action.getInput();
String a = input.getHeader("Authorization");
if (a == null || a.equals("")) return Action.LOGIN;
if (!a.startsWith("Basic ")) {
throw new FilterException("Authentication method not supported: " + a);
}
a = a.substring("Basic ".length());
String s = StringUtils.decodeBase64(a);
String[] t = s.split("\\:");
String username, password;
if (t.length == 1) {
throw new FilterException("Bad basic authentication value: " + a);
} else if (t.length == 2) {
username = t[0];
password = t[1];
} else {
// password has ':'
username = t[0];
password = "";
for(int i = 1; i < t.length; i++) {
if (i != 1) password += ":";
password += t[i];
}
}
Object sessionUser = authenticate(username, password);
if (sessionUser == null) return Action.LOGIN;
action.getSession().setAttribute("sessionUser", sessionUser);
return chain.invoke();
}
protected abstract Object authenticate(String username, String password);
@Override
public void destroy() {
}
}
/trunk/src/main/java/org/mentawai/util/StringUtils.java
26,6 → 26,7
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
import org.apache.commons.codec.binary.Base64;
import org.mentawai.i18n.LocaleManager;
 
public class StringUtils {
40,6 → 41,13
return s != null && s.length() > 0;
}
public static String decodeBase64(String s) {
return org.apache.commons.codec.binary.StringUtils.newStringUtf8(Base64.decodeBase64(s));
}
public static String encodeBase64(String s) {
return Base64.encodeBase64String(org.apache.commons.codec.binary.StringUtils.getBytesUtf8(s));
}
/**
* Checks if String is null or empty.
* @param str String
/trunk/pom.xml
173,6 → 173,13
</dependency>
 
<dependency>
<groupId>commons-codec</groupId>
<artifactId>commons-codec</artifactId>
<version>1.8</version>
</dependency>
 
 
<dependency>
<groupId>commons-io</groupId>
<artifactId>commons-io</artifactId>
<version>1.3.2</version>