Monday, January 19, 2015

Java code for Login with Facebook


package net.mydomain.myapp.controller;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLEncoder;
import java.util.Date;
import java.util.Map;

import javax.net.ssl.HttpsURLConnection;

import net.mydomain.myapp.controller.helper.FacebookDaoImpl;
import net.mydomain.myapp.domain.Account;
import net.mydomain.myapp.domain.AccountPending;
import net.mydomain.myapp.domain.Gender;
import net.mydomain.myapp.domain.Status;
import net.mydomain.myapp.domain.dao.AccountDaoImpl;
import net.mydomain.myapp.misc.myappProperties;
import net.mydomain.myapp.util.HibernateUtil;

import org.apache.commons.lang.StringUtils;
import org.hibernate.Session;
import org.hibernate.Transaction;

import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionContext;

public class FacebookController extends MyappActionSupport {
 private static final long serialVersionUID = 1L;
 private String code;
 private String state;
 private String location;
 private String FACEBOOK = "facebook"; // Facebook login
 private String HOME = "home";    //user clicked on cancel...show home page
 private String SIGNUP = "signup";  //show registration

 public String getCode() {
  return code;
 }

 public void setCode(String code) {
  this.code = code;
 }

 public String getState() {
  return state;
 }

 public void setState(String state) {
  this.state = state;
 }

 public String getLocation() {
  return location;
 }

 public void setLocation(String location) {
  this.location = location;
 }

 public String fbCallBack() {
  logger.info("code=" + code + " state=" + state);

  // Is this from facebook?
  clearHttpSession();
  
  // Validation
  if (StringUtils.isEmpty(state)) {
   logger.info("Facebook controller: Facebook callback: no state");
   addActionError("Failed facebook login");
   return HOME;
  }
  if (StringUtils.isEmpty(code)) {
   logger.info("Facebook controller: Facebook callback: no code");
   addActionError("Failed facebook login");
   return HOME;
  }
  
  code = URLEncoder.encode(code);
  String fbClientId;
  String fbClientPassword;
  String fbRedirectUrl;
  Session session = null;
  Transaction tran = null;
  try {
   fbClientId = myappProperties.faceBookClientId();
   fbClientPassword = myappProperties.faceBookClientPassword();
   fbRedirectUrl = myappProperties.baseUrl() + "fbCallBack";

   // obtain the access token
   URL url = new URL(
     "https://graph.facebook.com/oauth/access_token?client_id="
       + fbClientId + "&code=" + code + "&type=web_server"
       + "&client_secret=" + fbClientPassword  
       + "&redirect_uri=" + fbRedirectUrl);
   HttpsURLConnection con = (HttpsURLConnection) url.openConnection();
   String resp = getUrlContent(con);
   logger.info("response=" + resp);
   if (StringUtils.isEmpty(resp)) {
    addActionError("Failed facebook login");
    return HOME;
   }
   String[] resp_arr = resp.split("=");
   String accessToken = resp_arr[1];

   // obtain user profile....email, username, etc.
   url = new URL("https://graph.facebook.com/me?access_token="
     + accessToken);
   con = (HttpsURLConnection) url.openConnection();
   resp = getUrlContent(con);
   logger.info("response=" + resp);
   Gson gson = new Gson();
   FacebookDaoImpl fb = gson.fromJson(resp, FacebookDaoImpl.class);

   // check if  account exists for this user
   session = HibernateUtil.getCurremydomainession();
   tran = session.beginTransaction();
   if (fb.getEmail() == null) {
    logger.info("Permission to access email on Facebook is disabled");
    addActionError("You have not enabled permission to access email on Facebook");
    return ERROR;
   }
   Account anAccount = new AccountDaoImpl().getByEmail(fb.getEmail());
   
   if (anAccount == null) {
    // send them to registration
    AccountPending ap = new AccountPending();
    ap.setFirstName(fb.getFirstName());
    ap.setLastName(fb.getLastName());
    ap.setEmail(fb.getEmail().toLowerCase());
    ap.setPassword(null);
    ap.setCreateUsername(HibernateUtil.webUpdateUserName);
    ap.setTnCodeVerified(false);
    ap.setGender(fb.getGender() == null ? Gender.M : (fb.getGender().toUpperCase().startsWith("M") ? Gender.M : Gender.F));
    session.save(ap); 
    tran.commit();
    setSessionIdAccountPending(ap.getIdAccountPending());
    return SIGNUP;
   }
   if (anAccount.getStatusId() == Status.DEACTIVATED) {
    logger.info("account deactivated");
    addActionError("Your account has been deactivated.");
    return ERROR;
   }
   anAccount.setFbAccessToken(accessToken.substring(0,
     accessToken.indexOf("&expires")));
   anAccount.setLastLoginTimestamp(new Date());
   session.update(anAccount);
   tran.commit();
   populateHttpSession(anAccount);
  } catch (Exception e) {
   if (tran != null) 
    tran.rollback();
   logger.error("Exception ", e);
  } finally {
   if (session != null)
    session.close();
  }
  return HOME;
 }

 private String getUrlContent(HttpsURLConnection con) {
  String output = "";
  if (con != null) {
   try {
    BufferedReader br = new BufferedReader(new InputStreamReader(
      con.getInputStream()));
    String input;
    while ((input = br.readLine()) != null) {
     output += input;
     ;
    }
    br.close();
   } catch (IOException e) {
    logger.warn("Failed to get url content", e);
   } catch (Exception e) {
    logger.error("Error getting url content", e);
   }
  }
  return output;
 }
 private void setSessionIdAccountPending(Long idAccountPending) {
  Map httpSession = ActionContext.getContext().getSession();
  httpSession.put("idAccountPending", idAccountPending);
 }
 public String fbCall()
 { 
  String fbRedirectUrl = "";
  String fbClientId = "";
  if (StringUtils.isEmpty(state))
   state="test";
  logger.info("state=" + state);
  try{
   fbRedirectUrl = myappProperties.baseUrl() + "fbCallBack";
   fbClientId = myappProperties.faceBookClientId();
   
   location = "https://graph.facebook.com/oauth/authorize?client_id=" + fbClientId +
                                                        "&type=web_server" +
                                                        "&display=popup" +
                                                        "&redirect_uri=" + fbRedirectUrl +
                                                        "&response_type=token" +
                                                        "&state=" + state +
                                                        "&scope=email";
  } catch (Exception e) {
   logger.error("Exception in fbCall ", e);
  }
  return FACEBOOK;
 }
 private void clearHttpSession() {
  Map httpSession = ActionContext.getContext().getSession();
  httpSession.clear();
 }
}
FacebookDaoImpl.java
package net.mydomain.myapp.controller.helper;


public class FacebookDaoImpl  {

 private String id;
 private String name;
 private String first_name;
 private String last_name;
 private String link;
 private String username;
 private String gender;
 private String locale;
 private String type;
 private String picture;
 private String email;

 public String getId() {
  return id;
 }

 public String getName() {
  return name;
 }

 public String getFirstName() {
  return first_name;
 }

 public String getLastName() {
  return last_name;
 }

 public String getLink() {
  return link;
 }

 public String getUsername() {
  return username;
 }

 public String getGender() {
  return gender;
 }

 public String getLocale() {
  return locale;
 }

 public String getType() {
  return type;
 }

 public String getPicture() {
  return picture;
 }

 public String getEmail() {
  return email;
 }

}
Struts.xml
<action name="fbCall" class="net.mydomain.myapp.controller.FacebookController" method="fbCall">
   <result name="facebook" type="redirect">
    <param name="location">${location}</param>
   </result>
   <result name="facebook_mobile" type="redirect">
    <param name="location">${location}</param>
   </result>
  </action>
  <action name="fbCallBack" class="net.mydomain.myapp.controller.FacebookController" method="fbCallBack">
   <result name="home" type="redirectAction">
    <param name="actionName">home</param>
   </result>
   <result name="home_mobile" type="redirectAction">
    <param name="actionName">home</param>
   </result>
   <result name="signup">terminatingNumber.jsp</result>
   <result name="signup_mobile">mobile/tnEnteredM.jsp</result>
   <result name="error">error.jsp</result>
   <result name="error_mobile">mobile/error.jsp</result>
  </action>

No comments:

Post a Comment