package net.theliveweb.facebook;
import java.io.IOException;
import javax.security.auth.login.FailedLoginException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import com.facebook.api.FacebookParam;
import com.facebook.api.FacebookXmlRestClient;
/**
* The servlet filter that makes sure that the user is logged in before
* letting the requests reach the application code.
* @author theliveweb.net
*
*/
public class FaceBookAuthFilter implements Filter {
private String _apiKey;
private String _secretKey;
public void init(final FilterConfig filterConfig){
_apiKey = filterConfig.getInitParameter("api_key");
_secretKey = filterConfig.getInitParameter("secret_key");
}
/**
* Verifies whether user is logged in. If not, sends user to the login page.
*/
public void doFilter(final ServletRequest request, final ServletResponse response, FilterChain chain) throws IOException, ServletException {
HttpServletRequest httpReq = (HttpServletRequest) request;
HttpServletResponse httpRes = (HttpServletResponse) response;
PrintWriter oo = httpRes.getWriter();
oo.println("Inside of Filter
");
try {
oo.println("Filter: auth_token is " + httpReq.getParameter("auth_token") + "
");
oo.println("Filter: session key is " + httpReq.getParameter(FacebookParam.SESSION_KEY.toString()) + "
");
FacebookXmlRestClient authClient = FaceBookAuthHandler.getAuthenticatedClient(httpReq, _apiKey, _secretKey);
request.setAttribute("facebook.client", authClient);
chain.doFilter(request, response);
String auth = httpReq.getParameter("auth_token");
oo.println("Filter: Authorization is " + auth + "
");
oo.println("Filter: User ID is " + authClient.auth_getUserId(auth) + "
");
auth = authClient.auth_createToken();
oo.println("Filter: Authorization is " + auth + "
");
String ses = authClient.auth_getSession(auth);
oo.println("Filter: Session is " + ses+ "
");
int uID = authClient.auth_getUserId(auth);
oo.println("Filter: User id is " + uID + "
");
request.setAttribute("myauth", auth);
request.setAttribute("mysession", ses);
oo.flush();
} catch (FailedLoginException fle) {
//user not logged in
forceLogin(httpRes);
} catch (Exception e) {
//handle exception
}
}
/**
* Sends user to login page
* @param response
*/
private void forceLogin(HttpServletResponse response) {
try {
response.sendRedirect ("http://www.facebook.com/login.php?api_key=" + _apiKey + "&v=1.0");
} catch (IOException ioe) {
//handle exception
}
}
public void destroy() {
}
}