Facebook: FB.apiClient TypeError: $wnd.FB.Facebook is undefined" why this error occures? - gwt

We are facing one problem with facebook.
we integrated FB in our web application, when user login through fconnect in our web application then he registered with our system(1st time only) just providing his email id.For normal user few user i/p for registration in our system
Our web-application developed in java [GWT2.0].
Problem is when FACEBOOK or normaluser login through FB in our web-application.( 1 at a time)
when user refreshes page then FB pop window Occues with message
"Debug: Exception while loading FB.apiClient TypeError: $wnd.FB.Facebook is undefined"
or sometimes $wnd.FB.Facebook.apiClient is null occures
we get above error[pop-up] message 3 times.
we used following script in html page
< script type="text/javascript" language="javascript"
src="http://static.ak.connect.facebook.com/js/api_lib/v0.4/FeatureLoader.js.php">
In only 1 page of our web-application i.e UserHome page where we display users info .
on that page only above error message occurs
We used following GWT Code [from Gwittit] In controller class[Singleton class ]
/**
* Function get called when all the data on first page get loaded.
*
* */
public void notifyFinishedLoadinPage() {
FacebookConnect.waitUntilStatusReady(new
RenderAppWhenReadyCallback());
}
private MyLoginCallback
loginCallback = new MyLoginCallback();
class MyLoginCallback implements LoginCallback {
public void onLogin() {
isFacebookSign = true;
fbLoggedInUserId = ApiFactory.getInstance().getLoggedInUser();
for (FacebookObserver Observer : facebookObservers) {
Observer.notifyFacebookLogin(true);
}
}
}
public void publishStream(final FacebookObserver fbObserver) {
FacebookConnect.init(FacebookConstants.FACEBOOK_API_KEY,
"xd_receiver.htm", loginCallback);
FacebookConnect.requireSession(new
AsyncCallback() {
public void onFailure(Throwable caught) {
Window.alert("Require session failed: " + caught);
GWT.log("Require session failed: " + caught, null);
}
public void onSuccess(Boolean isLoggedIn) {
if (isLoggedIn) {
for (FacebookObserver Observer :
facebookObservers) {
Observer.notifyPublishStream();
}
}
}
});
}
public void facebookConnection() {
FacebookConnect.init(FacebookConstants.FACEBOOK_API_KEY,
"xd_receiver.htm", loginCallback);
//SERVER
FacebookConnect.requireSession(new
AsyncCallback() {
public void onFailure(Throwable caught) {
GWT.log("Require session failed: " + caught, null);
}
public void onSuccess(Boolean isLoggedIn) {
if (loginCallback != null && isLoggedIn) {
loginCallback.onLogin();
} else {
//User not logged in
}
}
});
}
/**
* Fired when we know users status
*/
private class RenderAppWhenReadyCallback implements
AsyncCallback {
public RenderAppWhenReadyCallback() {
FacebookConnect.init(FacebookConstants.FACEBOOK_API_KEY,
"xd_receiver.htm", loginCallback);
//SERVER
}
public void onFailure(Throwable caught) {
Window.alert("Unable to login through Facebook: " + caught);
}
public void onSuccess(ConnectState result) {
if (result == ConnectState.connected) {
isFacebookSign = true;
for (FacebookObserver Observer : facebookObservers) {
Observer.notifyFacebookLogin(true);
}
//History.newItem(HistoryConstants.USERHOME_PAGE_HISTORY_TOKEN);
} else {
//rightSideFlexTable.clearCell(0, 0);
//rightSideFlexTable.setWidget(0, 0,
facebookPanel);
isFacebookSign = false;
}
}
};
Now we unable to found solution to this problem.
Can any one help Us to solve this problem ASAP
Hope-for the Best Co-operation

we found solution for above Question.
Facebook (login)loading requires few time.
In Our web page we fetch fb details like fb users loggedInId ,Image,etc.
so at the time of page loading we get all values null because facebook not load properly
so we get $wnd.FB.Facebook.apiClient is null or
Debug: Exception while loading FB.apiClient TypeError: $wnd.FB.Facebook is undefined"
To solve this problem we write one method which calls when user refreshes page or after facebook loading done properly.
public void notifyFacebookLogin(boolean isLogin) {
Long fbLoggedInUserId = ApiFactory.getInstance().getLoggedInUser();
if (fbLoggedInUserId != null) {
if (globalEndUserInfo == null) {
globalEndUserInfo = new EndUserInfo();
globalEndUserInfo.setFbLoggedInUserId(fbLoggedInUserId);
}
}
// code wherever we deal with FB related object
}
Now no error message display when user refreshes page or if fb takes time to loading
In this way we solve our Problem. :)

Related

UBER with SSO using uber rides-android-sdk

I'm trying to get data from ALL_TRIPS Scope. I'm running into a few issues.
1) once I add the Scope.All_Trips to the .setScopes I get redirected verse being able to login to obtain the Token, therefore I get the necessary data from the get CurrentRide() method.
configuration = new SessionConfiguration.Builder()
.setClientId(CLIENT_ID)
.setRedirectUri(REDIRECT_URI)
.setScopes(Arrays.asList(Scope.HISTORY, Scope.PROFILE, Scope.RIDE_WIDGETS, Scope.ALL_TRIPS))
.setEnvironment(SessionConfiguration.Environment.SANDBOX)
.build();
validateConfiguration(configuration);
Error: Webpage not available The webpage at
Market://details?hl-en&id=com.ubercab&referrer=mat_cli%3
And it goes on and one.
Once i remove the All_TRIPS SCOPE I get the ability to Sign in.
Any help would be great so that I can move forward with getting the details like driver, vehicle, RideID.
private void LoadAllTrips(){
Session session = loginManager.getSession();
RidesService AllTrips = UberRidesApi.with(session).build().createService();
AllTrips.getCurrentRide().enqueue(new Callback<Ride>() {
#Override
public void onResponse(Call<Ride> call, Response<Ride> response) {
if (response.isSuccessful())
{
Toast.makeText(LoginSampleActivity.this, response.body().getRideId(), Toast.LENGTH_LONG).show();
}
else
{
ApiError error = ErrorParser.parseError(response);
Toast.makeText(LoginSampleActivity.this, error.getClientErrors().get(0).getTitle(), Toast.LENGTH_LONG).show();
}
}
#Override
public void onFailure(Call<Ride> call, Throwable t) {
}
});
}

Connect facebook login to firebase in unity

I want in my unity game with firebase facebook login when user login through facebook there user name, email & profile picture save in firebase.
I tried from firebase unity login auth docs but i cant get any thing from there.
On there docs to difficult to understand for beginners.
using UnityEngine;
using Facebook.Unity;
using UnityEngine.UI;
using Firebase.Auth;
public class FacebookManager : MonoBehaviour
{
public Text userIdText;
private FirebaseAuth mAuth;
private void Awake()
{
if (!FB.IsInitialized)
{
FB.Init();
}
else
{
FB.ActivateApp();
}
}
public void LogIn()
{
FB.LogInWithReadPermissions(callback:OnLogIn);
}
private void OnLogIn(ILoginResult result)
{
if (FB.IsLoggedIn)
{
AccessToken tocken = AccessToken.CurrentAccessToken;
userIdText.text = tocken.UserId;
Credential credential =FacebookAuthProvider.GetCredential(tocken.UserId);
}
else
{
Debug.Log("Login Failed");
}
}
public void accessToken(Credential firebaseResult)
{
FirebaseAuth auth = FirebaseAuth.DefaultInstance;
if (!FB.IsLoggedIn)
{
return;
}
auth.SignInWithCredentialAsync(firebaseResult).ContinueWith(task =>
{
if (task.IsCanceled)
{
Debug.LogError("SignInWithCredentialAsync was canceled.");
return;
}
if (task.IsFaulted)
{
Debug.LogError("SignInWithCredentialAsync encountered an error: " + task.Exception);
return;
}
FirebaseUser newUser = task.Result;
Debug.LogFormat("User signed in successfully: {0} ({1})",
newUser.DisplayName, newUser.UserId);
});
}
}
Please help me i am beginner in coding
Image
tocken.UserId This is wrong. Use tocken.TokenString . This will solve your problem. :)

Facebook Login with Unity 5 - Always return me Graph API Error: Bad request

I just start write my first game with unity.
I Created on facebook app - in games category.
I downloaded Facebook idk and added to unity.
I changed app id in Facebook settings.
Now I tried my code:
public class LoginScript : MonoBehaviour {
public string resultstr { get; set; }
public Text LableResult { get; set; }
List<string> perms = new List<string> (){"public_profile", "email", "user_friends"};
// Use this for initialization
void Start () {
LableResult = gameObject.GetComponent<Text> ();
LableResult.text = "Test";
if (!FB.IsInitialized) {
// Initialize the Facebook SDK
FB.Init (InitCallback, OnHideUnity);
} else {
// Already initialized, signal an app activation App Event
FB.ActivateApp ();
}
}
private void InitCallback ()
{
if (FB.IsInitialized) {
// Signal an app activation App Event
FB.ActivateApp ();
// Continue with Facebook SDK
// ...
} else {
Debug.Log ("Failed to Initialize the Facebook SDK");
}
}
private void OnHideUnity (bool isGameShown)
{
if (!isGameShown) {
// Pause the game - we will need to hide
Time.timeScale = 0;
} else {
// Resume the game - we're getting focus again
Time.timeScale = 1;
}
}
// Update is called once per frame
void Update () {
}
private void AuthCallback (ILoginResult result)
{
if (FB.IsLoggedIn) {
// AccessToken class will have session details
var aToken = Facebook.Unity.AccessToken.CurrentAccessToken;
// Print current access token's User ID
Debug.Log (aToken.UserId);
// Print current access token's granted permissions
foreach (string perm in aToken.Permissions) {
Debug.Log (perm);
}
} else {
Debug.Log ("User cancelled login");
}
}
// On Facebook login button
public void OnFacebook ()
{
FB.LogInWithReadPermissions (perms, AuthCallback);
}
}
But I'm ALWAYS getting in Result:
Graph Api Error: 400 Bad request
And callback_id 2 (sometimes I've seen 3)
Login I try in Mock window with token from facebook.
I tried deploy on iPhone - and game just crashed when I click on login button
Please to close this topic. I fixed it. It was my fail )) (Used app token instead user token )) (Happends)))))
The same thing happened to me!
Remember to check the user token part, which won't be set by default!

Show success message and then redirect to another page after a timeout using PageFlow

How can I show a success message and then redirect the user to another page after a timeout of e.g. 5 seconds?
I need this for the login page after a successful login. I tried the following and I can see the warning message on login failure, but not the success message on login success. It shows immediately the target page.
public String check(){
if (username.equals("test") && password.equals("test")) {
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Sample info message", "PrimeFaces rocks!"));
return "Success";
}else{
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_WARN,"Sample warn message", "Watch out for PrimeFaces!"));
return "Failure";
}
}
I'm using Seam's PageFlow for navigation.
I have a
<p:messages id="messages" showDetail="true" autoUpdate="true" closable="true" />
on the login page.
It is one of the utilities of Flash. Instead of
FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Sample info message", "PrimeFaces rocks!"));:
simply use this code
FacesContext facesContext = FacesContext.getCurrentInstance();
Flash flash = facesContext.getExternalContext().getFlash();
flash.setKeepMessages(true);
flash.setRedirect(true);
facesContext.addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO,"Sample info message", "PrimeFaces rocks!"));
First of all, with the code you posted you won't see the FacesMessage before the redirect, you'll see it after the redirect. But also, in order to make that happen you'll need to add a filter, because messages are lost when you redirect. This is the code for the filter you need (don't forget to declare it in web.xml):
public class MultiPageMessagesSupport implements PhaseListener {
private static final long serialVersionUID = 1250469273857785274L;
private static final String sessionToken = "MULTI_PAGE_MESSAGES_SUPPORT";
#Override
public PhaseId getPhaseId() {
return PhaseId.ANY_PHASE;
}
/*
* Check to see if we are "naturally" in the RENDER_RESPONSE phase. If we
* have arrived here and the response is already complete, then the page is
* not going to show up: don't display messages yet.
*/
#Override
public void beforePhase(final PhaseEvent event) {
FacesContext facesContext = event.getFacesContext();
int msg = this.saveMessages(facesContext);
if (PhaseId.RENDER_RESPONSE.equals(event.getPhaseId())) {
if (!facesContext.getResponseComplete()) {
this.restoreMessages(facesContext);
}
}
}
/*
* Save messages into the session after every phase.
*/
#Override
public void afterPhase(final PhaseEvent event) {
if (event.getPhaseId() == PhaseId.APPLY_REQUEST_VALUES ||
event.getPhaseId() == PhaseId.PROCESS_VALIDATIONS ||
event.getPhaseId() == PhaseId.INVOKE_APPLICATION) {
FacesContext facesContext = event.getFacesContext();
int msg = this.saveMessages(facesContext);
}
}
#SuppressWarnings("unchecked")
private int saveMessages(final FacesContext facesContext) {
List<FacesMessage> messages = new ArrayList<FacesMessage>();
for (Iterator<FacesMessage> iter = facesContext.getMessages(null); iter.hasNext();) {
messages.add(iter.next());
iter.remove();
}
if (messages.isEmpty()) {
return 0;
}
Map<String, Object> sessionMap = facesContext.getExternalContext().getSessionMap();
List<FacesMessage> existingMessages = (List<FacesMessage>) sessionMap.get(sessionToken);
if (existingMessages != null) {
existingMessages.addAll(messages);
} else {
sessionMap.put(sessionToken, messages);
}
return messages.size();
}
#SuppressWarnings("unchecked")
private int restoreMessages(final FacesContext facesContext) {
Map<String, Object> sessionMap = facesContext.getExternalContext().getSessionMap();
List<FacesMessage> messages = (List<FacesMessage>) sessionMap.remove(sessionToken);
if (messages == null) {
return 0;
}
int restoredCount = messages.size();
for (Object element : messages) {
facesContext.addMessage(null, (FacesMessage) element);
}
return restoredCount;
}
}
If this doesn't work for you, and you need to show the message before, then you'll have to something like the following: make the method return void, invoke it through ajax, and after adding the success message invoke some javascript method that will wait a couple of seconds and then make the redirect (maybe by programmatically clicking a hidden button that redirects to next page).
In my opinion this is not worth the trouble, you will just delay the login process. Anyway user will know tha tlogin succeeded because he will be redirect to home page (or whatever page you send him to)
EDIT:
the messages are displayed in the page when the method finishes, so waiting in the managed bean method won't work. after adding the FacesMessage, use
RequestContext.getCurrentInstance().execute("waitAndRedirect()");
And in your xhtml, you'll need to have a javascript function similar to this:
function waitAndRedirect() {
setTimeout(function() {
hiddenButtonId.click();
}, 2000);
}
where hiddenButtonId is the ID of a p:button which redirects to home page and is hidden (display:none)
But again, this a nasty approach, in my opinion there's no need to do this, you will just delay the login process.
you can not declare MultiPageMessagesSupport in the web.xml you must declare MultiPageMessagesSupport in the faces-config.xml. por example:
enter code here
<lifecycle>
<phase-listener>your.package.MultiPageMessagesSupport</phase-listener>
</lifecycle>

Waiting until application return Sucess or Failure(AsyncCallBack)

Just for example, let's check the code below
private void loadUserFromServer() {
dispatchAsync.execute(new FindLoggedUserAction(),
new AsyncCallback<FindLoggerUserResult>() {
#Override
public void onFailure(Throwable caught) {
//do something
}
#Override
public void onSuccess(BuscarUsuarioLogadoResult result) {
//dosomething with user
result.getUser();
}
operationTwo();
}
My problem is, I have to execute operationTwo(); after some result of dipatcher(Success or failure).
This is just an example, let's assume I can't put operationTwo() inside the onSucess or onFailure()
My real PROBLEM
My GateKeeper of presenters that user must be login.
private UserDTO user;
#Override
public boolean canReveal() {
if(getUser() == null){
ShowMsgEvent.fire(eventBus,"Must Login first", AlertType.ERROR);
return false;
}
return true;
}
}
public UserDTO getUser()
{
if(user == null)
{
//call server
loadUserFromServer();
}
return user;
}
private void loadUsuarioFromServer() {
dispatchAsync.execute(new BuscarUsuarioLogadoAction()
,new AsyncCallback<BuscarUsuarioLogadoResult>() {
#Override
public void onFailure(Throwable caught) {
//something
}
#Override
public void onSuccess(BuscarUsuarioLogadoResult result) {
if(!(result.getDto().equals(user)))
{
setUsuario(result.getDto(), false); //Set user UserDTO user
//event for update Presenter Login/Logout
// and Label with username
fireUserUpdateEvents();
}
else
{
setUsuario(result.getDto(), false);
}
}
});
As you can see, when a Presenter with that Gatekeeper is called and user is null,
getUser() is called, but when dispatch executes, the method doesn't wait until the return of Sucess or Failure
Result: getUser() returns null.
After the sucessful result of dispatch, getUser() returns a DTO. But, as you can see canReveal() already returned false.
Do not think that GateKeeper is a good approach to handle security in your case. You will not be able to reach stable work. Problem that you will have:
You are not handling network connection lost. If you code is already cached but you need to reload User it will be a big problem with double checking.
Sync calls are always problematic, specially with bad network connection. You will have tons of not responding messages.
To handle presenter access it will be better to use revealInParent method. Most of your presenter already overrides it and it looks like:
#Override
protected void revealInParent() {
RevealContentEvent.fire(...);
}
So you can just not fire Reveal event before you actually download user data. In your case the code will looks like:
#Override
protected void revealInParent() {
if(getUser() == null){
RevealContentEvent.fire(...);
return;
}
dispatchAsync.execute(new BuscarUsuarioLogadoAction()
,new AsyncCallback<BuscarUsuarioLogadoResult>() {
#Override
public void onFailure(Throwable caught) {
//something
}
#Override
public void onSuccess(BuscarUsuarioLogadoResult result) {
if(!(result.getDto().equals(user)))
{
setUsuario(result.getDto(), false); //Set user UserDTO user
//event for update Presenter Login/Logout
// and Label with username
fireUserUpdateEvents();
}
else
{
setUsuario(result.getDto(), false);
}
RevealContentEvent.fire(...);
}
});
We have also encountered similar problems. Its better to use Async call chaining. Since you can't do that there are two options for your problem
Setup a timer which will check from time to time whether the user is null or not and return only after when user is populated.
Use JSNI (Native code) and make the synchronous call. But beware this is bad practice
Yes, as Abhijith mentioned in previous answer there are 2 options -
1) Synchronous calls - which GWT doesn't support. So it is ruled out.
2) Setting timer - unless user logs in control will not come out of the timer loop. So failed status will never return from the timer. This approach serves only half of your requierment(serving only success state).
To solve your problem you try the following code snippet -
private UserDTO user;
private CanRevealCallBack revealCallBack;
public interface CanRevealCallBack {
returnStatus(boolean status);
}
#Override
public void canReveal(CanRevealCallBack callBack) {
revealCallBack = callBack;
if(user == null){
loadUserFromServer();
}
else{
revealCallBack.returnStatus( true );
}
}
private void loadUsuarioFromServer() {
dispatchAsync.execute(new BuscarUsuarioLogadoAction()
,new AsyncCallback<BuscarUsuarioLogadoResult>() {
#Override
public void onFailure(Throwable caught) {
//something
}
#Override
public void onSuccess(BuscarUsuarioLogadoResult result) {
if(!(result.getDto().equals(user)))
{
setUsuario(result.getDto(), false); //Set user UserDTO user
//event for update Presenter Login/Logout
// and Label with username
fireUserUpdateEvents();
}
else
{
setUsuario(result.getDto(), false);
}
if(result.getDto() == null){
revealCallBack.returnStatus( true );
}
else{
revealCallBack.returnStatus( false );
}
}
});
So, you have to pass a revealCallback to the canReveal method. CallBack gets executed and returns u the status on success of the async call. In returnStatus method of the callback you can program the logic with the correct user log-in status.