Implemented authorization for all face app users and enhanced general FaceRecognitionService and enhanced the front end UI

git-svn-id: https://svn.apache.org/repos/asf/incubator/photark/trunk@1160029 13f79535-47bb-0310-9956-ffa450edef68
diff --git a/photark-face-recognition/src/main/java/org/apache/photark/face/services/FaceRecognitionService.java b/photark-face-recognition/src/main/java/org/apache/photark/face/services/FaceRecognitionService.java
index a65b512..ad7769f 100644
--- a/photark-face-recognition/src/main/java/org/apache/photark/face/services/FaceRecognitionService.java
+++ b/photark-face-recognition/src/main/java/org/apache/photark/face/services/FaceRecognitionService.java
@@ -271,4 +271,46 @@
      */
     public void createNewDefaultFaceClient(String apiKey, String apiSecret);
 
+
+    /**
+     *   Checks whether User Name Contains In Private NameSpace
+     * @param photarkUid
+     * @param userName
+     * @return
+     */
+    public boolean isUserNameContainsInPrivateNameSpace(String photarkUid, String userName) ;
+
+
+    /**
+     *  Checks whether User Name Contains In Global NameSpace
+     * @param userName
+     * @return
+     */
+    public boolean isUserNameContainsInGlobalNameSpace(String userName) ;
+
+    /**
+     *  Stores the user specific trained index in the corresponding user profile in local jcr
+     * @param photarkUid
+     * @param userName
+     * @return
+     */
+    public boolean addFaceUserNameToUserProfile(String photarkUid, String userName);
+
+    /**
+     *  Checks whether a user name is allowed to recognize
+     * @param photarkUid
+     * @param userName
+     * @return
+     */
+    public boolean isUserAllowedToTrain(String photarkUid, String userName);
+
+    /**
+     * Use to handle authorization level of users in recognition
+     * @param photarkUid
+     * @param userName
+     * @return
+     */
+    public String checkGenericRecognitionValidity(String photarkUid, String userName);    
+
+
 }
diff --git a/photark-face-recognition/src/main/java/org/apache/photark/face/services/FaceRecognitionServiceImpl.java b/photark-face-recognition/src/main/java/org/apache/photark/face/services/FaceRecognitionServiceImpl.java
index 50d506b..6497d20 100644
--- a/photark-face-recognition/src/main/java/org/apache/photark/face/services/FaceRecognitionServiceImpl.java
+++ b/photark-face-recognition/src/main/java/org/apache/photark/face/services/FaceRecognitionServiceImpl.java
@@ -19,13 +19,19 @@
 package org.apache.photark.face.services;
 
 import java.io.File;
+import java.util.HashMap;
 import java.util.List;
+import java.util.Map;
 
 import com.github.mhendred.face4j.model.*;
 import org.apache.photark.face.services.beans.BeanGeneratorUtil;
 import org.apache.photark.face.services.beans.PhotArkFace;
 import org.apache.photark.face.services.beans.PhotarkPhoto;
+import org.apache.photark.jcr.JCRRepositoryManager;
+import org.apache.photark.jcr.util.JCREncoder;
+import org.apache.photark.security.utils.Constants;
 import org.oasisopen.sca.annotation.Init;
+import org.oasisopen.sca.annotation.Reference;
 import org.oasisopen.sca.annotation.Scope;
 import org.oasisopen.sca.annotation.Service;
 
@@ -34,22 +40,67 @@
 import com.github.mhendred.face4j.exception.FaceServerException;
 import com.github.mhendred.face4j.response.GroupResponse;
 import com.github.mhendred.face4j.response.LimitsResponse;
-import com.github.mhendred.face4j.response.TrainResponse;
 import com.github.mhendred.face4j.response.UsersResponse;
- 
+
+import javax.jcr.*;
+
 @Service(FaceRecognitionService.class)
 @Scope("COMPOSITE")
 public class FaceRecognitionServiceImpl implements FaceRecognitionService {
 
     private DefaultFaceClient defaultFaceClient;
-    private String API_KEY = "";
-    private String API_SECRET = "";
-
+    private final String API_KEY = "";
+    private final String API_SECRET = "";
+    private JCRRepositoryManager repositoryManager;
+    private Map<String, String> friendMap;
 
     @Init
     public void init() {
         System.out.println("# ... Initializing FaceRecognitionService ...");
-        defaultFaceClient = new DefaultFaceClient(API_KEY,API_SECRET);
+        defaultFaceClient = new DefaultFaceClient(API_KEY, API_SECRET);
+        friendMap = new HashMap<String, String>();
+        loadFriendMap();
+    }
+
+    private void loadFriendMap() {
+
+        Session session;
+        try {
+            session = repositoryManager.getSession();
+            Node listNodeUsers = (Node) session.getItem("/" + Constants.USER_STORE + "/" + Constants.USER_LISTS + "/" + Constants.REGISTERED_USER_LIST);
+
+            NodeIterator nit = listNodeUsers.getNodes();
+            while (nit.hasNext()) {
+                Node propertyNode;
+                Node userNode = nit.nextNode();
+                if (userNode.hasNode("face.friends.names")) {
+                    propertyNode = userNode.getNode("face.friends.names");
+                } else {
+                    propertyNode = userNode.addNode("face.friends.names");
+                }
+
+                PropertyIterator propertyIterator = propertyNode.getProperties();
+                while (propertyIterator.hasNext()) {
+                    Property property = propertyIterator.nextProperty();
+                    if ((property != null) && (property.getValue() != null)) {
+                        String userName = property.getValue().getString();
+                        friendMap.put(userName, "True");
+                    }
+                }
+
+            }
+
+        } catch (LoginException e) {
+            e.printStackTrace();
+        } catch (RepositoryException e) {
+            e.printStackTrace();
+        }
+    }
+
+
+    @Reference(name = "repositoryManager")
+    protected void setRepositoryManager(JCRRepositoryManager repositoryManager) {
+        this.repositoryManager = repositoryManager;
     }
 
     /**
@@ -62,7 +113,7 @@
     /**
      * @see {@link FaceRecognitionService#train(String)}
      */
-    public void train(String uids)  {
+    public void train(String uids) {
         try {
             defaultFaceClient.train(uids);
         } catch (FaceClientException e) {
@@ -96,9 +147,9 @@
     /**
      * @see {@link FaceRecognitionService#saveTags(String,String,String)}
      */
-    public void saveTags(String tids, String uid, String label)  {
+    public void saveTags(String tids, String uid, String label) {
         try {
-             defaultFaceClient.saveTags(tids, uid, label);
+            defaultFaceClient.saveTags(tids, uid, label);
         } catch (FaceClientException e) {
             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
         } catch (FaceServerException e) {
@@ -109,7 +160,7 @@
     /**
      * @see {@link FaceRecognitionService#recognizeFromFile(File,String)}
      */
-    public PhotarkPhoto recognizeFromFile(File imageFile, String uids)  {
+    public PhotarkPhoto recognizeFromFile(File imageFile, String uids) {
         Photo photo = null;
         try {
             photo = defaultFaceClient.recognize(imageFile, uids);
@@ -124,7 +175,7 @@
     /**
      * @see {@link FaceRecognitionService#recognizeFromUrl(String,String)}
      */
-    public PhotarkPhoto recognizeFromUrl(String url, String uid)  {
+    public PhotarkPhoto recognizeFromUrl(String url, String uid) {
         Photo p = null;
         try {
             p = defaultFaceClient.recognize(url, uid).get(0);
@@ -141,7 +192,7 @@
      * @see {@link FaceRecognitionService#detectFromFile(File)}
      */
     public PhotarkPhoto detectFromFile(File imageFile) {
-       Photo photo = null;
+        Photo photo = null;
         try {
             photo = defaultFaceClient.detect(imageFile);
         } catch (FaceClientException e) {
@@ -149,13 +200,13 @@
         } catch (FaceServerException e) {
             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
         }
-       return BeanGeneratorUtil.createPhotarkPhoto(photo);
+        return BeanGeneratorUtil.createPhotarkPhoto(photo);
     }
 
     /**
      * @see {@link FaceRecognitionService#detectFromUrl(String)}
      */
-    public PhotarkPhoto detectFromUrl(String url)  {
+    public PhotarkPhoto detectFromUrl(String url) {
         Photo photo = null;
         try {
             photo = defaultFaceClient.detect(url).get(0);
@@ -164,7 +215,7 @@
         } catch (FaceServerException e) {
             e.printStackTrace();  //To change body of catch statement use File | Settings | File Templates.
         }
-        return  BeanGeneratorUtil.createPhotarkPhoto(photo);
+        return BeanGeneratorUtil.createPhotarkPhoto(photo);
     }
 
     /**
@@ -273,4 +324,92 @@
     }
 
 
+    public boolean isUserAllowedToTrain(String photarkUid, String userName) {
+        boolean isUserAllowedToTrain = false;
+
+        if ((isUserNameContainsInPrivateNameSpace(photarkUid, userName))
+                || ((!isUserNameContainsInGlobalNameSpace(userName))) && (!isUserNameContainsInPrivateNameSpace(photarkUid, userName))) {
+            isUserAllowedToTrain = true;
+        }
+        return isUserAllowedToTrain;
+    }
+
+    public boolean isUserNameContainsInPrivateNameSpace(String photarkUid, String userName) {
+        boolean isUserNameContainsInPrivateNameSpace = false;
+        Session session;
+        try {
+            session = repositoryManager.getSession();
+            Node listNodeUsers = (Node) session.getItem("/" + Constants.USER_STORE + "/" + Constants.USER_LISTS + "/" + Constants.REGISTERED_USER_LIST);
+            Node userNode = listNodeUsers.getNode(JCREncoder.toJCRFormat(photarkUid));
+            Node propertyNode;
+            if (userNode.hasNode("face.friends.names")) {
+                propertyNode = userNode.getNode("face.friends.names");
+            } else {
+                propertyNode = userNode.addNode("face.friends.names");
+            }
+
+            if (propertyNode.hasProperty(userName)) {
+                isUserNameContainsInPrivateNameSpace = true;
+            }
+
+            session.save();
+
+        } catch (LoginException e) {
+
+            e.printStackTrace();
+        } catch (RepositoryException e) {
+
+            e.printStackTrace();
+        }
+        return isUserNameContainsInPrivateNameSpace;
+    }
+
+    public String checkGenericRecognitionValidity(String photarkUid, String userName) {
+        if (isUserNameContainsInPrivateNameSpace(photarkUid, userName)) {
+            return userName;
+        } else {
+            return "photark.not.allowed";
+        }
+    }
+
+    public boolean isUserNameContainsInGlobalNameSpace(String userName) {
+        boolean isUserNameContainsInGlobalNameSpace = false;
+        if (friendMap.containsKey(userName)) {
+            isUserNameContainsInGlobalNameSpace = true;
+        }
+        return isUserNameContainsInGlobalNameSpace;
+    }
+
+    public boolean addFaceUserNameToUserProfile(String photarkUid, String userName) {
+        boolean userNameExists = true;
+        Session session;
+        try {
+            session = repositoryManager.getSession();
+            Node listNodeUsers = (Node) session.getItem("/" + Constants.USER_STORE + "/" + Constants.USER_LISTS + "/" + Constants.REGISTERED_USER_LIST);
+            Node userNode = listNodeUsers.getNode(JCREncoder.toJCRFormat(photarkUid));
+            Node propertyNode;
+            if (userNode.hasNode("face.friends.names")) {
+                propertyNode = userNode.getNode("face.friends.names");
+            } else {
+                propertyNode = userNode.addNode("face.friends.names");
+            }
+
+            if (!propertyNode.hasProperty(userName)) {
+                propertyNode.setProperty(userName, userName);
+                userNameExists = false;
+                friendMap.put(userName, "True");
+            }
+
+            session.save();
+
+        } catch (LoginException e) {
+
+            e.printStackTrace();
+        } catch (RepositoryException e) {
+
+            e.printStackTrace();
+        }
+        return userNameExists;
+    }
+
 }
diff --git a/photark-face-recognition/src/main/java/org/apache/photark/face/services/applications/facebook/FacebookFriendFinderImpl.java b/photark-face-recognition/src/main/java/org/apache/photark/face/services/applications/facebook/FacebookFriendFinderImpl.java
index 8640a47..9ea890a 100644
--- a/photark-face-recognition/src/main/java/org/apache/photark/face/services/applications/facebook/FacebookFriendFinderImpl.java
+++ b/photark-face-recognition/src/main/java/org/apache/photark/face/services/applications/facebook/FacebookFriendFinderImpl.java
@@ -104,17 +104,17 @@
                 String confidence = "";
                 String gender = "";
                 if (face.getGuess() != null) {
-                    System.out.println("***Identified*** " + face.getGuess().toString());
                     uid = face.getGuess().getGuessID();
                     confidence = face.getGuess().getConfidence();
                     gender = face.getGender();
-
+                    System.out.println("***Identified*** " + uid);
                     faceMap.put(uid, Integer.valueOf(confidence));
                     if (faceMap.containsKey(uid) && (faceMap.get(uid) < Integer.valueOf(confidence))) {
                         faceMap.remove(uid);
                     }
-
-                    detectedFriends.add(new Entry<String, String[]>(uid, getFacebookUserDataTuple(facebookClient, uid, gender, confidence)));
+                    if ((uid != null) && (uid.endsWith("@facebook.com"))) {
+                        detectedFriends.add(new Entry<String, String[]>(uid, getFacebookUserDataTuple(facebookClient, uid, gender, confidence)));
+                    }
                 } else {
                     System.out.println("??? Unidentified ..");
                 }
diff --git a/photark-face-recognition/src/main/java/org/apache/photark/face/services/applications/generic/GenericFriendFinder.java b/photark-face-recognition/src/main/java/org/apache/photark/face/services/applications/generic/GenericFriendFinder.java
index c600813..9fbdb33 100644
--- a/photark-face-recognition/src/main/java/org/apache/photark/face/services/applications/generic/GenericFriendFinder.java
+++ b/photark-face-recognition/src/main/java/org/apache/photark/face/services/applications/generic/GenericFriendFinder.java
@@ -32,7 +32,7 @@
      * @param userName username under the private namespace i.e xxx@photark.com
      * @param label optional, a label to the tag
      */
-    public void trainUrlImage(String imagePath, String userName, String label) ;
+    public boolean trainUrlImage(String imagePath, String userName, String label, String photarkUid) ;
 
     /**
      * Train the face.com index with the given picture
@@ -40,7 +40,7 @@
      * @param userName userName username under the private namespace i.e xxx@photark.com
      * @param label optional, a label to the tag
      */
-    public void trainLocalImage(String imagePath, String userName, String label);
+    public boolean trainLocalImage(String imagePath, String userName, String label, String photarkUid);
 
     /**
      * Recognize a given one or more private namespace trained friends
diff --git a/photark-face-recognition/src/main/java/org/apache/photark/face/services/applications/generic/GenericFriendFinderImpl.java b/photark-face-recognition/src/main/java/org/apache/photark/face/services/applications/generic/GenericFriendFinderImpl.java
index 926a56f..88ccfc9 100644
--- a/photark-face-recognition/src/main/java/org/apache/photark/face/services/applications/generic/GenericFriendFinderImpl.java
+++ b/photark-face-recognition/src/main/java/org/apache/photark/face/services/applications/generic/GenericFriendFinderImpl.java
@@ -83,15 +83,14 @@
                 String confidence = "";
                 String gender = "";
                 if (face.getGuess() != null) {
-//                    System.out.println("***Identified*** " + face.getGuess().toString());
                     userName = face.getGuess().getGuessID();
                     confidence = face.getGuess().getConfidence();
                     gender = face.getGender();
-                    System.out.println("***Identified*** " + userName+" : "+" : "+gender+" : "+confidence);
-                    if(userName != null) {
-                    detectedFriends.add(new Entry<String, String[]>(userName, new String[]{userName, gender, confidence}));
+                    System.out.println("***Identified*** " + userName + " : " + " : " + gender + " : " + confidence);
+                    if ((userName != null) && (userName.endsWith("@photark.com"))) {
+                        detectedFriends.add(new Entry<String, String[]>(userName, new String[]{userName, gender, confidence}));
                     }
-                    } else {
+                } else {
                     System.out.println("??? Unidentified ..");
                 }
             }
@@ -106,47 +105,73 @@
         return detectedFriends.toArray(dataArray);
     }
 
-    public void trainLocalImage(String imagePath, String userName, String label) {
-        try {
-            PhotarkPhoto photo = faceRecognitionService.detectFromFile(new File(imagePath));
-            for (PhotArkFace face : photo.getPhotArkFaces()) {
-                if (face.getGuess() != null) {
-                    userName = face.getGuess().getGuessID();
+    public boolean trainLocalImage(String imagePath, String userName, String label, String photarkUid) {
+        boolean isTrained = false;
+        if (faceRecognitionService.isUserAllowedToTrain(photarkUid, userName)) {
+            try {
+                PhotarkPhoto photo = faceRecognitionService.detectFromFile(new File(imagePath));
 
-                    faceRecognitionService.saveTags(face.getTid(), userName, label);
+                if (photo.getPhotArkFaces().size() == 1) {
+                    faceRecognitionService.saveTags(photo.getPhotArkFace().getTid(), userName, label);
+                    faceRecognitionService.train(userName);
+                    faceRecognitionService.addFaceUserNameToUserProfile(photarkUid, userName);
                 } else {
-                    faceRecognitionService.saveTags(face.getTid(), userName, label);
+                    for (PhotArkFace face : photo.getPhotArkFaces()) {
+                        if (face.getGuess() != null) {
+                            if (face.getGuess().getGuessID() != null) {
+                                userName = face.getGuess().getGuessID();
+                            }
+                            faceRecognitionService.saveTags(face.getTid(), userName, label);
+                        } else {
+                            faceRecognitionService.saveTags(face.getTid(), userName, label);
+                        }
+
+                        faceRecognitionService.train(userName);
+                        faceRecognitionService.addFaceUserNameToUserProfile(photarkUid, userName);
+                    }
                 }
-
-                faceRecognitionService.train(userName);
+                isTrained = true;
+            } catch (FaceClientException e) {
+                e.printStackTrace();
+            } catch (FaceServerException e) {
+                e.printStackTrace();
             }
-        } catch (FaceClientException e) {
-            e.printStackTrace();
-        } catch (FaceServerException e) {
-            e.printStackTrace();
         }
-
+        return isTrained;
     }
 
-    public void trainUrlImage(String imagePath, String userName, String label) {
-        try {
-            PhotarkPhoto photo = faceRecognitionService.detectFromUrl(imagePath);
-            for (PhotArkFace face : photo.getPhotArkFaces()) {
-                if (face.getGuess() != null) {
-                    userName = face.getGuess().getGuessID();
-
-                    faceRecognitionService.saveTags(face.getTid(), userName, label);
+    public boolean trainUrlImage(String imagePath, String userName, String label, String photarkUid) {
+        boolean isTrained = false;
+        if (faceRecognitionService.isUserAllowedToTrain(photarkUid, userName)) {
+            try {
+                PhotarkPhoto photo = faceRecognitionService.detectFromUrl(imagePath);
+                if (photo.getPhotArkFaces().size() == 1) {
+                    faceRecognitionService.saveTags(photo.getPhotArkFace().getTid(), userName, label);
+                    faceRecognitionService.train(userName);
+                    faceRecognitionService.addFaceUserNameToUserProfile(photarkUid, userName);
                 } else {
-                    faceRecognitionService.saveTags(face.getTid(), userName, label);
+                    for (PhotArkFace face : photo.getPhotArkFaces()) {
+                        if (face.getGuess() != null) {
+                            if (face.getGuess().getGuessID() != null) {
+                                userName = face.getGuess().getGuessID();
+                            }
+                            faceRecognitionService.saveTags(face.getTid(), userName, label);
+                        } else {
+                            faceRecognitionService.saveTags(face.getTid(), userName, label);
+                        }
+                        faceRecognitionService.train(userName);
+                        faceRecognitionService.addFaceUserNameToUserProfile(photarkUid, userName);
+                    }
                 }
-
-                faceRecognitionService.train(userName);
+                isTrained = true;
+            } catch (FaceClientException e) {
+                e.printStackTrace();
+            } catch (FaceServerException e) {
+                e.printStackTrace();
             }
-        } catch (FaceClientException e) {
-            e.printStackTrace();
-        } catch (FaceServerException e) {
-            e.printStackTrace();
         }
 
+        return isTrained;
     }
+
 }
diff --git a/photark-jcr/src/main/java/org/apache/photark/jcr/services/JCRGalleryImpl.java b/photark-jcr/src/main/java/org/apache/photark/jcr/services/JCRGalleryImpl.java
index 5aa2284..a3c2e53 100644
--- a/photark-jcr/src/main/java/org/apache/photark/jcr/services/JCRGalleryImpl.java
+++ b/photark-jcr/src/main/java/org/apache/photark/jcr/services/JCRGalleryImpl.java
@@ -75,7 +75,7 @@
                Session session = repositoryManager.getSession();
                Node baseRoot = session.getRootNode();
                Node rootNode;
-
+                                         
                if (!baseRoot.hasNode("albums")) {
                    rootNode = baseRoot.addNode("albums");
                } else {
diff --git a/photark-ui-admin/src/main/webapp/admin/face.html b/photark-ui-admin/src/main/webapp/admin/face.html
index c63f067..f22f800 100644
--- a/photark-ui-admin/src/main/webapp/admin/face.html
+++ b/photark-ui-admin/src/main/webapp/admin/face.html
@@ -39,7 +39,6 @@
     <div id="adminDiv">
         <div style="float:right;width:50%;font-size:0.8em;text-align:right;padding-top:5px;padding-right:10px;">
             <div><span id="loginName"></span>&nbsp;&nbsp;<span><a href="../" style="color:black;">Gallery</a></span>&nbsp;&nbsp;<span><a
-                    href="../upload.html" style="color:black;">Face Recognition</a></span>&nbsp;&nbsp;<span><a
                     href="../logout/" style="color:black;">Logout</a></span></div>
         </div>
         <div id="newAlbum">
diff --git a/photark-ui-admin/src/main/webapp/admin/js/face.js b/photark-ui-admin/src/main/webapp/admin/js/face.js
index d9d5943..47487bd 100644
--- a/photark-ui-admin/src/main/webapp/admin/js/face.js
+++ b/photark-ui-admin/src/main/webapp/admin/js/face.js
@@ -97,8 +97,28 @@
     window.location = url;
 }
 
-function trainUser() {
-     var userName = dojo.byId("train_uname_input").value;
+function trainUser(){
+        dojo.xhrPost({
+        url:"../security", //photark.constants.SecurityEndpoint,
+        content:{request:"getUser"},
+        handleAs: "json",
+        load: function(response, ioArgs) {
+         if(response.user.userId != "Guest") {
+          _trainUsers(response.user.userId);
+         } else {
+             alert("Please logged in before using Photark FaceApps..!!!");
+         }
+        },
+        error: function(response, ioArgs) {
+
+        }
+    });
+
+}
+
+function _trainUsers(photark_uid) {
+    var photarkUid = photark_uid;
+    var userName = dojo.byId("train_uname_input").value;
 
     if (selectFaceApp.value == "General-Face-Recognition") {
         var filePath = dojo.byId("imageFilePathInput").value;
@@ -110,10 +130,10 @@
         }
 
         if ((filePath == "" ) && (fileUrl != "")) {
-            genericFaceService.trainUrlImage(fileUrl, userName, label).addCallback(facebook_gff_void_callback);
+            genericFaceService.trainUrlImage(fileUrl, userName, label, photarkUid).addCallback(facebook_gff_void_callback);
         } else if ((fileUrl == "" ) && (filePath != "")) {
 
-            genericFaceService.trainLocalImage(filePath, userName, label).addCallback(facebook_gff_void_callback);
+            genericFaceService.trainLocalImage(filePath, userName, label, photarkUid).addCallback(facebook_gff_void_callback);
         } else {
            alert("..You should fill either image file path or url ...!!! ");
         }
@@ -139,19 +159,31 @@
     });
 }
 
+function facebook_ff_callback(items, exception) {
+    if (exception) {
+        alert("Error while Training the user..Please try again...");
+    } else {
+        alert("Successfully Trained in Facebook...!!");
+    }
+}
+
 function facebook_ff_void_callback(items, exception) {
     if (exception) {
         alert("Error while Training the user..Please try again...");
     } else {
-        alert("Successfully Trained...!!");
+        alert("Successfully Authenticated in Facebook...!!");
     }
 }
 
-function facebook_gff_void_callback(items, exception) {
+function facebook_gff_void_callback(trained, exception) {
     if (exception) {
         alert("Error while Training the user..Please try again...");
     } else {
-          alert("Successfully Trained...!!");
+        if(trained) {
+            alert("Successfully Trained...!!");
+        } else {
+           alert("UserName already exists..Please choose another UserName..!!!");
+        }
     }
 }
 
diff --git a/photark-ui/src/main/webapp/js/gallery.js b/photark-ui/src/main/webapp/js/gallery.js
index 4440a28..58e8dc7 100644
--- a/photark-ui/src/main/webapp/js/gallery.js
+++ b/photark-ui/src/main/webapp/js/gallery.js
@@ -297,6 +297,25 @@
 }
 
 function showFriends() {
+     dojo.xhrPost({
+        url:"security", //photark.constants.SecurityEndpoint,
+        content:{request:"getUser"},
+        handleAs: "json",
+        load: function(response, ioArgs) {
+            if(response.user.userId != "Guest") {
+              _showFriends();
+            } else {
+                alert("Please login before using Photark Face Apps....!!!");
+            }
+
+        },
+        error: function(response, ioArgs) {
+
+        }
+    });
+}
+
+function _showFriends() {
     clearFaceTable();
 
     var facetype = dojo.byId("faceAppType").value;
@@ -305,12 +324,28 @@
     if (facetype == "facebook") {
         showFacebookFriends();
     } else if (facetype == "private") {
-       showGenericFriends(textField.value);
+        checkGenericRecognition(textField.value);
+//       showGenericFriends(textField.value);
     }
 
 
 }
 
+function checkGenericRecognition(userName){
+       dojo.xhrPost({
+        url:"security", //photark.constants.SecurityEndpoint,
+        content:{request:"getUser"},
+        handleAs: "json",
+        load: function(response, ioArgs) {
+            faceService.checkGenericRecognitionValidity(response.user.userId,userName).addCallback(face_callback);
+        },
+        error: function(response, ioArgs) {
+
+        }
+    });
+}
+
+
 function showPreLoader(){
     var img = dojo.byId("loadingImg");
                     dojo.attr(img, {
@@ -325,6 +360,7 @@
                     });
 }
 
+
 function showGenericFriends(userName) {
 //  var file_path =  document.getElementById("albumImage").src;
     var file_path = "https://lh4.googleusercontent.com/-rb_m-GQcL00/Ti8sqThvrDI/AAAAAAAAAMY/kUBurbFKJ0A/s640/friends_2.jpg";
@@ -363,12 +399,18 @@
 
 }
 
-function face_callback(items, exception) {
+function face_callback(userName, exception) {
     if (exception) {
         alert("FB AUTH Error");
 
+    } else {
+        if(userName != "photark.not.allowed") {
+            showGenericFriends(userName);
+        } else {
+            alert("You are only allowed to Recognize friends from your own domain...!!!");
+        }
+
     }
-    //alert("FB AUTH OK");
 
 }
 
diff --git a/photark-webapp/src/main/webapp/WEB-INF/web.composite b/photark-webapp/src/main/webapp/WEB-INF/web.composite
index 6583ec8..c21b3b4 100644
--- a/photark-webapp/src/main/webapp/WEB-INF/web.composite
+++ b/photark-webapp/src/main/webapp/WEB-INF/web.composite
@@ -176,6 +176,7 @@
    			<binding.sca name="local"/>
    			<tuscany:binding.jsonrpc uri="/FaceRecognitionService"/>
    		</service>
+        <reference name="repositoryManager" target="RepositoryManager"/>
 	</component>
 
      <component name="FacebookFriendFinder">