Facebook login redirect issue - javascript

I have a site with a working Facebook login.
The problem is happens when the user comes to the site for the first time (or after clearing cookies).
The user flow is the following:
User clicks "Sign Up with Facebook"
User is redirected to Facebook authentication
If User accepts, he/she is redirected to the 'Sign Up' page.
The problem is that if the person is doing this for the first time, they are always redirected back to the home page.
There are only 2 possible views that can be given for this url
The Sign Up page, with only some form data sent as parameters
An alert box upon successful DB persistence
Thus, I have ruled out PHP as a possible cause of the redirect.
I have included the JavaScript managing the Facebook interaction.
All other relevant code can be found in the HTML of the page.
The Page can be found at http://trioisrael.com
function fb_login(){
FB.login(function(response) {
if (response.authResponse) {
window.location = "http://trioisrael.com/signup"
//console.log(response); // dump complete info
access_token = response.authResponse.accessToken; //get access token
user_id = response.authResponse.userID; //get FB UID
FB.api('/me', function(response) {
user_email = response.email; //get user email
// you can store this data into your database
});
} else {
//user hit cancel button
alert('We use facebook to make sure that everyone is really who they say they are');
}
}, {
scope: 'user_photos,user_birthday'
});
}

Trying to do additional stuff after assigning a new value to window.location (which should be window.location.href, of course) does not make sense.
If you want to do additional stuff after login, do it before redirecting the user somewhere else.

Related

How to find original email redirect link from landing page for firebase email link sign in option

In firebase, in order to authenticate a use after they click an email link, firebase needs the original clicked email link.
Example
This link redirects you a few times, and brings you to the page needed (currently set to localhost for dev purposes)
Firebase will only accept the email link, and only for one test per email which makes it difficult to diagnose this.
I need a way to fetch the first link clicked (the email link) from the landing page.
I apolagise if this has been answered anywhere else but I tried several combinations of keywords that did not work
export default function Home() {
return (
<>
boilerplate
<button onClick={bigFunction}>Press me to check if the browser has the email saved</button>
</>
)
}
let signinwithemaillink = "https://ticketme.page.link/qbvQ"
function bigFunction()
{
console.log(window.location.href)
if (isSignInWithEmailLink(auth, signinwithemaillink)) {
// Additional state parameters can also be passed via URL.
// This can be used to continue the user's intended action before triggering
// the sign-in operation.
// Get the email if available. This should be available if the user completes
// the flow on the same device where they started it.
let email = window.localStorage.getItem('emailForSignIn');
if (!email) {
// User opened the link on a different device. To prevent session fixation
// attacks, ask the user to provide the associated email again. For example:
email = 'example#gmail.com';
}
// The client SDK will parse the code from the link for you.
signInWithEmailLink(auth, email, signinwithemaillink)
.then((result) => {
alert("all good")
console.log(result.user)
// Clear email from storage.
window.localStorage.removeItem('emailForSignIn');
// You can access the new user via result.user
// Additional user info profile not available via:
// result.additionalUserInfo.profile == null
// You can check if the user is new or existing:
// result.additionalUserInfo.isNewUser
})
.catch((error) => {
console.log(error.code)
// Some error occurred, you can inspect the code: error.code
// Common errors could be invalid email and invalid or expired OTPs.
});
}
}
As you can tell there is still an incredible amount of comments from the firebase docs, Im just trying to get this to work.
*Amended - I cut out the dynamic link, so the current redirect cycle is as follows:
Email -> Firebase Redirect Link -> Desired Page

How to get User Details after Google Authentication in web app using firebase?

I have a web-app that allows users to sign in using their gmail account.Once the user is signed in, I am able to see it's details using result.user object like this-
function signInWithGoogle(){
var provider=new firebase.auth.GoogleAuthProvider();
firebase.auth().signInWithPopup(provider).then(function(result){
var user=result.user;
console.log("user_provider="+user.displayName+" user_email="+user.email+" user_dp="+user.photoURL+" user_verification="+user.emailVerified+" uid="+user.uid);
}).catch(function(error){
console.log("error="+error);
});
}
After signing in, I want to keep user details in page even after reloading and refreshing for that I used User object of auth() like this-
$(document).ready(function(){
var user=firebase.auth().currentUser;
console.log(user);
});
But it's showing user as null although I can see user email address in authentication console in firebase.
P.S. I have also used onAuthStateChanged instead of currentUser , but still it's not working.
onAuthStateChanged should work. You have to listen to it correctly.
firebase.auth().onAuthStateChanged(function(user) {
if (user) {
// currentUser should be available now.
} else {
// No user logged in.
}
});
Keep in mind that the state is stored in single host origin web storage. So if you navigate to a page with a different domain, the state will not propagate.

Show welcome message for successful login (after redirect)?

I have a modal login page which users can log in with ajax (created with vue Js) :
return login_modal.$http.post('/login', data).then(
function (response) {
if (response.data.auth) {
window.location = response.data.intended_url
} else {
login_modal.incorrect_credential = true;
}
}
)
When user login successfully, the page is redirected to the firstly requested page OR home page. All things works great
Now I want to show an alert or a toastr message to user after he/she is redirected, but I don't know if he/she is just logged in or logged in before! The welcome message should be show only if user is just logged in! one time only.
I know how to use cookies or sessions in php or js, but I don't know how to accomplish this! for example saving a short living cookie (5 seconds!!). Is this the right way?

angularjs redirection after login

may I know how to redirect user to where they originally at after login ? say i have a post wwww.example.com/post/435 and it required user to log in in order to "like/comment" the post, so after the user login how can i redirect user back to the post ? i have tried this
$http.post('/sessionHandler/login',$scope.form).
success(function(data){
history.back(); // bring user back to previous path
}).error(function(err){
$scope.errorMessage = err;
});
however this is not really effective, if a user previous path is other site or a browser new tab it will redirect the user back to where they are.
i also found some example by using $locationChangeStart but i'm having some difficulties to understand how it works this is what i have so far for $locationChangeStart
$http.post('/sessionHandler/login',$scope.form).
success(function(data){
$rootScope.$on("$locationChangeStart", function (event, next, current) {
$location.path();// how to access to previous url where the user from ?
// how to use event, next and current to get the user last
// path on my site, and how to determine the last site is
// on my site but not other website ?
});
})
your help is appreciated !!
May not be the best answer, but I use a cookie for this - so whenever I'm redirecting to a new location, I'll use $cookies.loginDestination = $location.path(), then whenever a user logs in, I use something like:
var loginDestination = $cookies.loginDestination || '/';
$cookies.loginDestination = null;
$location.path(loginDestination);

Facebook client side authorization flow and get access_token for all scenarios like when scope for an app changes, etc

I am trying to do 3 simple things using JS thru a client side authorization flow :
Check if the user is logged in. If not, display the login dialog with proper scope.
If user is already logged into Facebook on the browser, then ensure the app has been authorized (if not, display the Authorize dialog).
If user has already authorized the app then ensure that the access_token on the authResponse has the right scope (permissions) required by the app. (if not, redisplay the authorize dialog for the new permissions).
I am trying to leverage js sdk for this, without wanting to write any hand-coded dialog's etc, since the sdk handles the browsers/devices nuances automagically.
I could not find this properly described anywhere either on FB documentation or otherwise. (no documentation around the fact that the permissions/scope for the app can change post authorization).
Thanks you in advance.
After an arduous attempt I have this working and here are the steps to do this with the minimum amount of code.
*The Approach *
Use fb-login-button to facilitate login. Login Button is the only thing that is displayed when the user first arrives on the page. All other forms are 'hidden', forcing the user to click on this button before being able to go forward.
setup onlogin="function();" on the fb-login-button - so that you can hide the login-button and display the rest of the forms/etc for the user to proceed on your app. Please note that onlogin is called only once (either when the user logs in or authorizes the app with the new scope) - so it is safe to always hide the login-button and display the remaining of the page/form for the user to proceed.
The most important step : use the same fb-login-button to also do the authorization with the right scope : so even if the user is logged in - force the user to click the login-button. fb-login-button in this case, will check if the scope of existing access_token (for already logged in fb user), is a subset of that requested on the fb-login-button attribute. fb-login-button will display the authorize dialog for you automatically in this case. In any case the onLogin callback is triggered (when the login-button should be hidden() and the remaining page/forms be shown()).
Subscribe to the FB.events to get the authResponses and the corresponding access_token every time it is set, which happens 2 times :
a. When the fetch is first displayed for already logged in user
b. After the user authorizes the app first time or second time with the new scope.
This allows you to keep the authResponse and access_token fresh to be used for all subsequent graph calls/etc..
*Implementation Steps *
fb-login-button must be created with onlogin callback :
<div class="fb-login-button" onLogin="onLogin();" scope="publish_actions"
data-size="large">Use This App</div>
Please note that the text does not say Login, but 'Use this App', since the button is displayed for authorization in addition to just logging in.
Subscribe to the Events.
// authRepsonse Change is needed when the user hits the UseApp button
// and permissions are re-fetched - then a new token needs to be refreshed
FB.Event.subscribe('auth.authResponseChange', handleResponseChange);
// when the user logins and all permissions are all set, clicking on the
// use-app will not do anything and authResponse will always be null.
// so this subscription is necessary
FB.Event.subscribe('auth.statusChange', handleResponseChange);
Login Function to hide Login button and display form.
function onLogin () {
hideLogin();
showMain();
}
Handle Status Changes to save Token.
// global variable that contains the access_token
// for use in graph calls/etc.
var authResponse = null;
function handleResponseChange(response) {
if (response && response.authResponse) {
authResponse = response.authResponse
if (response.status == 'connected') {
updateUserInfo(response);
return;
}
}
else {
authResponse = null;
}
hideMain();
showLogin();
}
Hope this helps and I believe that this is probably the most optimal way of handling client side authentication flow without doing any extra authorization/login dialog and let FB sdk do the trick.

Categories

Resources