Removed facebook support because of old api

This commit is contained in:
Ziver Koc 2016-11-23 00:50:01 +01:00
parent e79cea52ce
commit 7b7ba10b5d
5 changed files with 1 additions and 407 deletions

View file

@ -29,14 +29,6 @@
<param-name>DATA_PATH</param-name> <param-name>DATA_PATH</param-name>
<param-value>C:\\data</param-value> <param-value>C:\\data</param-value>
</init-param> </init-param>
<init-param>
<param-name>FB_APPID</param-name>
<param-value>123456789</param-value>
</init-param>
<init-param>
<param-name>FB_APPSEC</param-name>
<param-value>123456789abcdefklmnopqrst</param-value>
</init-param>
<load-on-startup>1</load-on-startup> <load-on-startup>1</load-on-startup>
</servlet> </servlet>
<servlet-mapping> <servlet-mapping>

View file

@ -2,7 +2,6 @@ package zall;
import java.io.File; import java.io.File;
import java.io.IOException; import java.io.IOException;
import java.io.PrintWriter;
import java.util.List; import java.util.List;
import java.util.logging.Level; import java.util.logging.Level;
import java.util.logging.Logger; import java.util.logging.Logger;
@ -21,13 +20,9 @@ import zall.bean.Image;
import zall.bean.Media; import zall.bean.Media;
import zall.bean.User; import zall.bean.User;
import zall.util.Email; import zall.util.Email;
import zall.util.facebook.FBUser;
import zall.util.facebook.FacebookConnect;
import zall.util.msg.UserMessage; import zall.util.msg.UserMessage;
import zall.util.msg.UserMessage.MessageType; import zall.util.msg.UserMessage.MessageType;
import zutil.db.DBConnection; import zutil.db.DBConnection;
import zutil.db.bean.DBBean;
import zutil.db.bean.DBBeanSQLResultHandler;
import zutil.log.LogUtil; import zutil.log.LogUtil;
public class Zallery extends HttpServlet{ public class Zallery extends HttpServlet{
@ -68,12 +63,6 @@ public class Zallery extends HttpServlet{
throw new ServletException("Missing DATA_PATH parameter!"); throw new ServletException("Missing DATA_PATH parameter!");
if( config.getInitParameter("THEME") != null ) if( config.getInitParameter("THEME") != null )
THEME = config.getInitParameter("THEME"); THEME = config.getInitParameter("THEME");
if( config.getInitParameter("FB_APPID") != null &&
config.getInitParameter("FB_APPID") != null)
FacebookConnect.setApplicationID(
config.getInitParameter("FB_APPID"),
config.getInitParameter("FB_APPSEC"));
LogUtil.setLevel("zall", Level.FINEST); LogUtil.setLevel("zall", Level.FINEST);
//LogUtil.setLevel("zutil", Level.FINEST); //LogUtil.setLevel("zutil", Level.FINEST);
} }
@ -98,27 +87,10 @@ public class Zallery extends HttpServlet{
String page = new File(request.getRequestURI()).getName(); String page = new File(request.getRequestURI()).getName();
request.setAttribute("page", page); request.setAttribute("page", page);
User user = (User) session.getAttribute("user"); User user = (User) session.getAttribute("user");
FacebookConnect fbc = (FacebookConnect) session.getAttribute("facebook");
if( fbc == null )
fbc = FacebookConnect.getConnection( request.getCookies() );
String action = request.getParameter("action"); String action = request.getParameter("action");
if( action == null ) action = ""; if( action == null ) action = "";
UserMessage msgs = UserMessage.getUserMessage(session); UserMessage msgs = UserMessage.getUserMessage(session);
// Take care of facebook open graph
if( request.getHeader("User-Agent").startsWith("facebookexternalhit/1.1") && page.startsWith("media") ){
PrintWriter out = response.getWriter();
out.print("<HTML><HEAD>"+
"<!-- Facebook OpenGraph -->"+
"<meta property='og:title' content='"+WEBSITE_NAME+"'/>"+
"<meta property='og:type' content='album'/>"+
"<meta property='fb:app_id' content='"+FacebookConnect.getAplicationId()+"'/>"+
"<meta property='og:url' content='"+WEBSITE_URL+"media?type="+request.getParameter("type")+"&id="+request.getParameter("id")+"'/>"+
"<meta property='og:image' content='"+WEBSITE_URL+"content?type="+request.getParameter("type")+"&id="+request.getParameter("id")+"&size=small'/>"+
"<meta property='og:site_name' content='"+WEBSITE_NAME+"'/>"+
"</HEAD></HTML>");
return;
}
// Verify email address // Verify email address
if( action.equalsIgnoreCase("verfemail") ){ if( action.equalsIgnoreCase("verfemail") ){
@ -132,35 +104,6 @@ public class Zallery extends HttpServlet{
else else
msgs.add(MessageType.ERROR, "Email verification failed!"); msgs.add(MessageType.ERROR, "Email verification failed!");
} }
// auth with facebook
if( user == null ){
if( fbc != null ){
FBUser fb_user = fbc.getUser();
user = User.loadByFacebook(request, response, db, fb_user.getUID() );
// New user?
if( user == null ){
logger.info("Creating new user from Facebook login.");
user = new User();
user.setFacebookUid( fb_user.getUID() );
user.setName( fb_user.getName() );
user.setEmail( "" );
user.registerOnHost(request, response, db, false );
ZalleryAjax.sendEmailNewUserToAdmin(user, db);
msgs.add(MessageType.INFO, "Your account has successfully been created. The account is waiting account activation by an admin.");
}
logger.info("Used Facebook to auth User: \""+user.getName()+"\".");
user.registerOnHost(request, response, db, false );
session.setAttribute("user", user);
session.setAttribute("facebook", fbc);
user.save(db);
//if( page.startsWith("login") )
response.sendRedirect( "gallery" );
//else
// response.sendRedirect( page );
return;
}
}
// auth with cookie // auth with cookie
if( user == null ){ if( user == null ){
user = User.loadByCookie(request, db, getCookieValue(request.getCookies(), "sessionHash") ); user = User.loadByCookie(request, db, getCookieValue(request.getCookies(), "sessionHash") );
@ -181,7 +124,6 @@ public class Zallery extends HttpServlet{
session.invalidate(); session.invalidate();
session = request.getSession( true ); session = request.getSession( true );
msgs.setSession( session ); msgs.setSession( session );
if( fbc != null ) fbc.logout( response );
user.logout( response ); user.logout( response );
if( !user.isEmailVerified() ) if( !user.isEmailVerified() )
@ -199,12 +141,6 @@ public class Zallery extends HttpServlet{
String include_jsp = null; String include_jsp = null;
if( user != null ){ if( user != null ){
logger.finest("Valid user: \""+user.getName()+"\""); logger.finest("Valid user: \""+user.getName()+"\"");
// Register facebook on user
if( user.getFacebookUid() == null && fbc != null){
FBUser fb_user = fbc.getUser();
user.setFacebookUid( fb_user.getUID() );
msgs.add(MessageType.INFO, "Facebook connected to your account.");
}
// Import JSP pages // Import JSP pages
if(page.startsWith("media")){ if(page.startsWith("media")){
try{ try{

View file

@ -1,120 +0,0 @@
package zall.util.facebook;
import java.io.IOException;
import java.io.InputStream;
import java.util.logging.Logger;
import zutil.io.IOUtil;
import zutil.log.LogUtil;
import zutil.parser.DataNode;
import zutil.parser.json.JSONParser;
/**
* This class represent a Facebook user
*
* @author Ziver
*/
public class FBUser {
private static Logger logger = LogUtil.getLogger();
/** This is the connection to Facebook **/
private FacebookConnect fbc;
/** the user id of this user */
private String uid;
/* User data */
private String name;
private String email;
private String birthday;
private String gender;
private String relationship_status;
private String website;
private int timezone;
private String locale;
public FBUser( FacebookConnect fbc, String uid ){
this.fbc = fbc;
this.uid = uid;
load();
}
/**
* Updates the data of the user in this object
*/
public void load(){
try {
InputStream stream = fbc.getServiceURL( uid ).openStream();
String data = IOUtil.readContentAsString( stream );
DataNode node = JSONParser.read( data );
logger.finer("User("+uid+") data from Facebook: "+data);
if( node.get("name") != null )
name = node.get("name").getString();
if( node.get("email") != null )
email = node.get("email").getString();
if( node.get("birthday") != null )
birthday = node.get("birthday").getString();
if( node.get("gender") != null )
gender = node.get("gender").getString();
if( node.get("relationship_status") != null )
relationship_status = node.get("relationship_status").getString();
if( node.get("website") != null )
website = node.get("website").getString();
if( node.get("timezone") != null )
timezone = node.get("timezone").getInt();
if( node.get("locale") != null )
locale = node.get("locale").getString();
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* @return The unique user id on Facebook
*/
public String getUID(){
return uid;
}
public String getName(){
return name;
}
public String getEmail(){
return email;
}
public String getBirthday(){
return birthday;
}
public String getGender(){
return gender;
}
public String getRelationshipStatus(){
return relationship_status;
}
public String getWebsite(){
return website;
}
public int getTimezone(){
return timezone;
}
public String getLocale(){
return locale;
}
/**
* Returns an instance of the given UID user class
*
* @param uid is the id of the user
* @return a cached FBUser object or a new one if its not cached
*/
public static FBUser get( FacebookConnect fbc, String uid ){
if( uid == null )
return null;
return new FBUser( fbc, uid );
}
}

View file

@ -1,204 +0,0 @@
package zall.util.facebook;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.logging.Logger;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import zutil.Hasher;
import zutil.log.LogUtil;
import zutil.parser.Base64Decoder;
import zutil.parser.DataNode;
import zutil.parser.json.JSONParser;
/**
* This class connects to Facebook and
* retrieves information about the user
*
* @author Ziver
*/
public class FacebookConnect {
private static Logger logger = LogUtil.getLogger();
/** The URL to the Facebook OpenGraph service. (must end with a '/') **/
public static final String SERVICE_URL = "https://graph.facebook.com/";
/** The application id for this application generated by Facebook **/
protected static String application_id = null;
/** The application secret for this application generated by Facebook **/
protected static String application_secret = null;
protected String access_token;
protected FBUser user;
private FacebookConnect( String access_token, String uid ){
this.access_token = access_token;
user = FBUser.get( this, uid );
}
/**
* @return the main user
*/
public FBUser getUser(){
return user;
}
/**
* Returns the given user by UID
*
* @param uid is the user id of the user
* @return a FBUser object or null if there is no such user
*/
public FBUser getUser(String uid){
return FBUser.get( this, uid );
}
/**
* @return The access token for this session
*/
protected String getAccessToken(){
return access_token;
}
/**
* Generates a url for calling the Facebook OpenGraph API
*
* @param page is the page ex. a UID
* @return A URL to the service
* @throws MalformedURLException
*/
protected URL getServiceURL(String page) throws MalformedURLException{
return getServiceURL(page, null);
}
/**
* Generates a url for calling the Facebook OpenGraph API
*
* @param page is the page ex. a UID
* @param params is URL parameters ex. "?name=lol" or "&name=lol&lol=name" or "name=lol" etc...
* @return A URL to the service
* @throws MalformedURLException
*/
protected URL getServiceURL(String page, String params) throws MalformedURLException{
StringBuilder url = new StringBuilder( SERVICE_URL );
url.append( page );
url.append( '?' );
url.append( "access_token=" );
url.append( access_token );
if( params != null && !params.isEmpty() ){
if( params.charAt(0) == '?' )
params = params.substring( 1 );
if( params.charAt(0) != '&' )
url.append( '&' );
url.append( params );
}
return new URL( url.toString() );
}
/**
* Sets the static values for this application
* @param id is the application id for this application generated by Facebook
* @param secret is the application secret for this application generated by Facebook
*/
public static void setApplicationID(String id, String secret){
application_id = id;
application_secret = secret;
}
public static String getAplicationId() {
return application_id;
}
/**
* Creates a new instance of the FacebookConnect for the logged in user
* or null if the creation was unsuccessful.
*
* @param cookies is the cookies from the client
* @return A new FacebookConnect object or null if the creation was unsuccessful
*/
public static FacebookConnect getConnection( Cookie[] cookies ){
if( cookies == null ){
logger.severe("Cookie is not set!");
return null;
}
String cookie_name = "fbsr_" + application_id;
// Find the cookie
for(Cookie cookie : cookies) {
if ( cookie_name.equals(cookie.getName()) ){
// remove the trailing "
String value = cookie.getValue();
return getConnection( value );
}
}
return null;
}
/**
* Creates a new instance of the FacebookConnect for the logged in user
* or null if the creation was unsuccessful.
*
* @param value is the string value from facebook
* @return A new FacebookConnect object or null if the creation was unsuccessful
*/
public static FacebookConnect getConnection( String value ){
if( application_id == null ){
logger.severe("Application_id is not set!");
return null;
}
if( application_secret == null ){
logger.severe("Application_secret is not set!");
return null;
}
value = value.trim();
if( value.isEmpty() )
return null;
value = value.replaceAll("-", "+");
value = value.replaceAll("_", "/");
// Parse the attributes
String[] attrib = value.split("\\.", 2);
String signature = Base64Decoder.decodeToHex( attrib[0] );
System.out.println( signature );
//attrib[1] = Base64Decoder.addPadding( attrib[1] );
String data = Base64Decoder.decode( attrib[1] );
DataNode map = JSONParser.read( data );
System.out.println(map);
if ( !map.getString("algorithm").equalsIgnoreCase("HMAC-SHA256") ) {
logger.severe("Unknown algorithm: '"+map.getString("algorithm")+"' Expected 'HMAC-SHA256'");
return null;
}
// Check hash signature
String local_sig = Hasher.HMAC_SHA256( attrib[1], application_secret );
System.out.println(local_sig);
if ( !signature.equals( local_sig )) {
logger.severe("Bad Signed JSON signature: '"+signature+"' Expected '"+local_sig+"'");
return null;
}
//if( map.containsKey( "access_token" ) )
// return new FacebookConnect( map.get( "access_token" ), map.get( "uid" ) );
//return null;
return null;
}
/**
* This method remove the cookie from the user by setting the MaxAge to -1
*
* @param response is the response that the cookie will be added to
*/
public void logout(HttpServletResponse response) {
Cookie cookie = new Cookie( "fbsr_" + application_id, null);
cookie.setMaxAge( 0 );
cookie.setPath("/");
response.addCookie( cookie );
}
}

View file

@ -1,10 +0,0 @@
package zall.util.test;
import zall.util.facebook.FacebookConnect;
public class FacebookTester {
public static void main(String[] args){
FacebookConnect.setApplicationID("110543555676926", "5b2dd75314a2fd58b080b06a19b55713");
FacebookConnect.getConnection("rZtSPvnBVqNi8hnjJuIffghIvQdq56yaLh1FiP-KybQ.eyJhbGdvcml0aG0iOiJITUFDLVNIQTI1NiIsImNvZGUiOiJBUUJnR3ZtNzVfLXIyVU9iSU4wdnJ4N2pMYVRicVpLdVprdE1xQXVWMHBxUjZMcGkzTDJXVEtYV3BxQmJ5MjByX1pnSFo1dDJLX3lGTENFRTJ3Sko1ek8tbHU2Z3Eyb2xfaDB4WGNneW9OTHNRODBsR2tpMG1hVFdSV083a2VfOUlPb0puYkVqajVSdnhyYW03UW9DOHRkRUEtS2NRZE1DUmptd1kzeHNSNFVsUDBuOE9fblFLa1RUbldYNjY0XzR5UEUiLCJpc3N1ZWRfYXQiOjEzMzU3OTQ4MDcsInVzZXJfaWQiOiIxMTg3MDk1NTIyIn0");
}
}