FB Authentication • User clicks on the FB button on home page • the user is redirected to https://graph.facebook.com/oauth/authorize with these parameters: client_id FB App Id type web_server display Popup redirect_uri/myServices/connectToFBCallback response_type Token auth_type Reauthenticate state Test scope Email • Note that is set up in the FB App at developers.facebook.com • after the user logs successfully into FB, the callback URL ( /myServices/connectToFBCallback) is invoked by FB we are interested in the 2 parameters that are passed into the callback URL. 1) code 2) state • if code is null or empty, we assume the user is not authorized by FB and send the user to registration • state should be same as the one we passed with the URL https://graph.facebook.com/oauth/authorize • if state is null or empty, we assume the user is not authorized by FB and send the user to registration • Note: if the callback URL is never invoked by FB, there is nothing that we can do to inform the user about the status of their login • the next step is to get the access token • the URL is https://graph.facebook.com/oauth/access_token • parameters: client_id code type web_server client_secret • open the URL connection is https://graph.facebook.com/oauth/access_token using HTTPS protocol and read the input. We are interested in the access token that could be read in the input as access_token=xyz... • Save the access token in the Database • We then need to get the FB username of the user • open HTTPS URL connection to https://graph.facebook.com/me • with parameter access_token= • the response from FB is read into a Gson object • the username and email are parsed and stored in the Gson object • we then look up the Account table using the email of Gson object 1) if the account is found, we log the user in and we are done 2) if the account is not found, we send the user to registration Logging in FB User • We redirect the user to myWebsite/loginFB.action with the following parameters: 1) email (ex:abc@abc.com) 2) profilePic (ex: https://graph.facebook.com/ /picture) • The loginFB method will store the profile pic in Account.profile_pic. • For example: https://graph.facebook.com/gandikotam/picture will be the value stored in the Account.profile_pic for the FB user with username gandikotam • To retrieve the image, the ProfilePicController needs to be modified to download the image using HTTPS protocol.
Monday, January 19, 2015
FB Authentication
Sample mobile JSP
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%@ taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<title><%= myappProperties.sitePageTitle() %> Action Menu</title>
<s:head />
<jsp:include page="/mobile/mobileScriptsAndStyles.jsp"></jsp:include>
<style type="text/css">
p img {
max-width: 100%;
}
</style>
<script type="text/javascript" src="js/mobile/scaleImage.js"></script>
<script type="text/javascript">
$("div[data-role='page']").live("pageshow", function(event, ui) {
<s:if test="account.profilePic != null && account.profilePic != ''">
scaleImage("profile/${account.accountId}/${account.profilePic}", "profilePicture2", 60, 60);
</s:if>
<s:elseif test="genderOfPhoneBookEntry == \"F\"">
scaleImage("img/noImageFemale.png", "profilePicture2", 60, 60);
</s:elseif>
<s:else>
scaleImage("img/noImageMale.png", "profilePicture2", 60, 60);
</s:else>
});
</script>
</head>
<body>
<div data-role="page" data-theme="c">
<div data-role="content" style="background-color:#FFFFFF;">
<!-- Menu button -->
<div id="toggleButton" onclick="toggleMenu();" style="width: 26px; height: 26px; background: url(img/mobile/list.png) 0 0 no-repeat; cursor: pointer; float: left;"></div>
<!-- Menu overlay -->
<div id="menuClickOverlay">
<%@ include file="/mobile/logo.jsp" %><br />
<div data-role="content">
<%@ include file="/mobile/popupCommon.jsp" %>
<div id="agentProfile" style="width: 100%; min-width: 0px; line-height:auto; margin-top:0px;">
${account.profilePageHtml}
</div>
</div>
</div>
<!-- /Menu overlay -->
<!-- Menu -->
<%@ include file="/mobile/mobileMenu.jsp" %>
<!-- /Menu -->
</div>
<jsp:include page="/mobile/navbar.jsp"></jsp:include>
</div>
</body>
</html>
mobileScriptsAndStyles.jsp
<%@page import="net.mycom.myapp.misc.myappProperties" %>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<meta name="format-detection" content="telephone=yes">
<link rel="apple-touch-icon-precomposed" href="img/mobile/apple-touch-icon.png" />
<link rel="apple-touch-startup-image" href="img/mobile/apple-touch-startup-image.png" />
<link rel="stylesheet" href="css/mobile/jquery.mobile-1.2.0.min.css" />
<link rel="stylesheet" href="css/mobile/jquery.mobile-1.1.0.c_mycom.css" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.8.2/jquery.min.js"></script>
<script type="text/javascript">
$(document).bind("mobileinit", function() {
$.mobile.ajaxEnabled = false;
$.mobile.hashListeningEnabled = false;
});
</script>
<script type="text/javascript" src="js/mobile/jquery.mobile-1.2.0.min.js"></script>
<link href="css/style.css" rel="stylesheet" type="text/css" />
<link href="css/<%= myappProperties.siteTheme() %>.css" rel="stylesheet" type="text/css" />
<style type="text/css">
/* Menu
*/
.ui-btn-text,
.ui-btn input, .ui-btn button,
.ui-checkbox, .ui-radio,
.ui-checkbox input, .ui-radio input,
.ui-checkbox .ui-btn, .ui-radio .ui-btn,
.ui-select .ui-btn select {
z-index: 0;
}
/* Counters on menu */
.ui-li-count {
display: none;
}
/* /Menu
*/
/* prevent zooming */
.ui-select .ui-btn select{font-size: 50px;}
</style>
<jsp:include page="/analytics.jsp" />
Sample Ajax call using Jquery
function getNewAccountsHtml() {
$.ajax({
type: 'GET',
cache: false,
async: false,
url: 'getXXX?hours=' + <%= Integer.parseInt(Properties.Hours())%>,
data: $("#id").serialize(),
success: function(data) {
$("#newAccountsHtml").html(data.xyz); //the java method sets html.put("xyz", "value") and struts.xml has the action configured
$("#newAccountsHtml").css("display", "block");
$("#newAccountsUpdateTime").html(getCurrentTimestamp());
},
error: function(XMLHttpRequest, textStatus, errorThrown) {
alert("Server Unavailable");
},
dataType: "json"
});
}
Prestruts filter
import java.io.IOException;
import net.mycom.myapp.misc.myappProperties;
import org.apache.log4j.Logger;
import org.apache.log4j.MDC;
import org.apache.struts2.dispatcher.ng.filter.*;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class PreStrutsFilter implememycom Filter {
private static Logger logger = Logger.getLogger(PreStrutsFilter.class);
Filter strutsFilter = new StrutsPrepareAndExecuteFilter();
private String bypassStrutsExp;
private String bypassStrutsExpMobile;
private String bypassVaadin;
private ServletContext ctx;
@Override
public void destroy() {
strutsFilter.destroy();
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {
if(req instanceof HttpServletRequest){
HttpServletRequest httpReq = (HttpServletRequest)req;
String uri = httpReq.getRequestURI();
String ctxRoot = this.ctx.getContextPath();
uri = uri.replace(ctxRoot, "");
if(!uri.matches(bypassStrutsExp) &&
!uri.matches(bypassStrutsExpMobile) &&
!uri.matches(bypassVaadin)
){
// Browser cache images
int dot = uri.lastIndexOf(".");
if ((dot > 0) &&
(uri.substring(dot).equalsIgnoreCase(".jpg") ||
uri.substring(dot).equalsIgnoreCase(".jpeg") ||
uri.substring(dot).equalsIgnoreCase(".gif") ||
uri.substring(dot).equalsIgnoreCase(".png"))) {
try {
((HttpServletResponse)res).setHeader("Cache-Control", "max-age=" + myappProperties.getCacheControlMaxAge());
}
catch (Exception e) {
((HttpServletResponse)res).setHeader("Cache-Control", "max-age=120");
logger.error("Error retrieving cacheControlMaxAge", e);
}
}
putMDC(httpReq); // Log user
strutsFilter.doFilter(req, res, chain);
MDC.clear(); // Remove from Mapped Diagnostic Context
}
else{
chain.doFilter(req, res);
}
}
else{
chain.doFilter(req, res);
}
}
@Override
public void init(FilterConfig cfg) throws ServletException {
strutsFilter.init(cfg);
this.bypassStrutsExp = cfg.getInitParameter("struts_bypass_expression");
this.bypassStrutsExpMobile = cfg.getInitParameter("struts_bypass_expression_mobile");
this.bypassVaadin = cfg.getInitParameter("struts_bypass_vaadin");
this.ctx = cfg.getServletContext();
}
private void putMDC(HttpServletRequest request) {
Long accountId = (Long)request.getSession().getAttribute("accountId");
String sessionId = request.getSession().getId();
// If parameter exist put into Mapped Diagnostic Context
if (accountId != null) { MDC.put("accountId", accountId); }
if (sessionId != null) { MDC.put("sessionId", sessionId); }
}
}
Vaadin app
package net.mycom.vaadin;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.mycom.myapp.domain.Account;
import net.mycom.myapp.misc.myappProperties;
import net.mycom.myapp.util.HibernateUtil;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import org.hibernate.Session;
import org.hibernate.Transaction;
import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.HttpServletRequestListener;
import com.vaadin.ui.Button;
import com.vaadin.ui.Button.ClickEvent;
import com.vaadin.ui.Button.ClickListener;
import com.vaadin.ui.RichTextArea;
import com.vaadin.ui.VerticalLayout;
import com.vaadin.ui.Window;
import com.vaadin.ui.Window.CloseEvent;
public class mycomVaadinApplication extends Application implememycom HttpServletRequestListener {
private static final long serialVersionUID = 1L;
private static final String ERR_NITEFLIRT = "err_niteflirt";
private static final String ERR_SCRIPT = "err_script";
private static final String ERR_NONE = "err_none";
private static final String ERR_NOACCOUNTID = "err_noAccountId";
private static final String ERR_MAXSIZE = "err_maxsize";
private static final String ERR_UNKNOWN = "err_unknown";
private static ThreadLocal threadLocal = new ThreadLocal();
public static Logger logger = Logger.getRootLogger();
private static Integer dbProfilePageHtmlSize;
Long accountId=0L;
private transient HttpServletResponse response;
private transient HttpServletRequest request;
@Override
public void init() {
if (accountId == null || accountId == 0L) {
try {
String req = request.getRequestURI();
response.sendRedirect(req.substring(0, req.indexOf("/VAADIN")) + "/home");
} catch (IOException io) {
}
return;
}
String req = request.getRequestURL().toString();
req = req.substring(0, req.indexOf("/VAADIN"));
Window mainWindow = new Window("My Profile " + accountId);
final RichTextArea ta = new RichTextArea();
ta.setHeight("500");
ta.setWidth("800");
ta.setValue(getTextAreaContent());
VerticalLayout layout=new VerticalLayout();
Button saveButton = new Button();
saveButton.addListener(new ClickListener() {
@Override
public void buttonClick(ClickEvent event) {
switch(saveTextAreaContent((String)ta.getValue())) {
case ERR_NONE:
logger.info("saving rich text area content=" + ta.getValue());
getMainWindow().showNotification("Content saved");
break;
case ERR_SCRIPT:
getMainWindow().showNotification("Not Saved. Cannot use script or javascript tags");
break;
case ERR_NITEFLIRT:
getMainWindow().showNotification("Not Saved. Cannot use NITEFLIRT");
break;
case ERR_MAXSIZE:
getMainWindow().showNotification("Not Saved. Content size exceeded maximum size. Reduce and try again");
break;
case ERR_UNKNOWN:
getMainWindow().showNotification("Not Saved. Unknown error; please contact system administrator");
break;
default:
getMainWindow().showNotification("Not Saved. No account Id...could not save");
}
}
});
saveButton.setStyleName("vaadinButton");
layout.addComponent(ta);
layout.addComponent(saveButton);
mainWindow.addComponent(layout);
// Close the application if the main window is closed.
mainWindow.addListener(new Window.CloseListener(){
@Override
public void windowClose(CloseEvent e) {
logger.info("Closing the application");
close();
}
});
setMainWindow(mainWindow);
}
@Override
public void onRequestStart(HttpServletRequest request, HttpServletResponse response) {
accountId = (Long) request.getSession().getAttribute("accountId");
this.response = response;
this.request = request;
mycomVaadinApplication.setInstance(this);
}
@Override
public void onRequestEnd(HttpServletRequest request, HttpServletResponse response) {
threadLocal.remove();
}
// Set the current application instance
public static void setInstance(mycomVaadinApplication application) {
threadLocal.set(application);
}
// @return the current application instance
public static mycomVaadinApplication getInstance() {
return threadLocal.get();
}
private String getTextAreaContent() {
if ((Long)request.getSession().getAttribute("accountId") == null) {
logger.info("no account id");
return null;
}
logger.info("Retrieving html for accountId=" + (Long)request.getSession().getAttribute("accountId"));
Session session = HibernateUtil.getCurremycomession();
Account myAcc = (Account)session.get(Account.class, (Long)request.getSession().getAttribute("accountId"));
session.close();
return myAcc.getProfilePageHtml() == null ? "" : myAcc.getProfilePageHtml();
}
private String saveTextAreaContent(String html) {
if ((Long)request.getSession().getAttribute("accountId") == null) {
logger.info("no account id");
return ERR_NOACCOUNTID;
}
try {
if (!StringUtils.isEmpty(html) && html.length() > getDbProfilePageHtmlSize()) {
logger.info("profile page too large");
return ERR_MAXSIZE;
}
} catch (Exception e) {
logger.error("max size property", e);
return ERR_UNKNOWN;
}
String htmlNoWhiteSpaces = StringUtils.deleteWhitespace(html);
if (htmlNoWhiteSpaces.toLowerCase().indexOf("javascript") > -1 ||
htmlNoWhiteSpaces.toLowerCase().indexOf("