getAuth() returns null - firebase-authentication

I need to use the user authentication for facebook,twitter and google. I initially created a firebase account and used this following code.
var ref = new Firebase("https://keks.firebaseio.com");
ref.getAuth();
console.log(ref.getAuth());
This always returns null in my console. Why this happens? Can someone help me?

Calling getAuth() doesn't authenticate the user, it only returns the current authentication state. The API documentation says:
Returns the current authentication state of the Firebase client. If the client is unauthenticated, this method will return null.
Since you are getting null, it means your user hasn't been authenticated yet. You can authenticate the user, by calling authWithOAuthPopup():
function authHandler(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
console.log("Authenticated successfully with payload:", authData);
}
}
ref.authWithOAuthPopup("<provider>", authHandler);
This last snippet comes from the Firebase documentation on authentication.
Since both parts of my answer come from the Firebase documentation, I highly recommend that you spend some time there.

Related

React-redux and React Native error handling for expired JWT

I have a system where the authentication is based around JWT. I have a JWT auth token, and a refresh token on the client. The refresh token is stored in the database on the server, and is used to refresh the JWT once the JWT expires every 12 hours - pretty standard setup I believe.
My issue is incorporating it in to my React Native project and handling token expiration. The user will likely be performing many API calls to their "protected" areas which require the JWT, but once the JWT expires it will send back a "UnauthorizedError" like so:
router.use('/protected', ejwt({secret: config.secret}));
//catch any errors if the JWT is not valid
router.use((err, req, res, next) => {
if (err.name === 'UnauthorizedError') {
res.status(401).send({
success: false,
error: "UnauthorizedError"
});
}
});
This will send back to the RN app that the JWT has expired, but at this point I would like the app to send another request back to the server generate a new JWT, but I'm not sure of a way to do this most efficiently for every API call initiated from my app. Each API call could call a function to check the server if the returned value is "UnauthorizedError", but I know this isn't the best way:
return AuthApi.someApiCall(token).then(response => {
if(response.success){
//do some success stuff
}else{
//this seems bad to be repeated for every API call
checkToken(response).then(() => {
dispatch(updateAuthToken());
});
}
})
I've been looking around and Redux middleware looks promising, but I don't know if there's a more established way perhaps, or anyone has any other thoughts?
Thanks!

Why is my implementation of SSO using Ember-Simple-Auth with Auth0 getting stuck in a redirect loop?

I have an ember application that uses the Auth0 Ember Simple Auth addon to use the Ember-Simple-Auth functionality with Auth0's Lock.js. Recently I have been trying to implement single-sign-onfunctionality, such that if a user logs into a login portal application, their session will be preserved for other applications on the same domain, and they will not need to log in repeatedly. However my implementation of SSO is resulting in an infinite redirect loop between my login logic and Auth0's endpoint.
I have enabled SSO in the Auth0 application settings. My login is implemented in a few blocks.
My route.js contains a beforeModel() method which contains:
if (!get(session, 'isAuthenticated')){
// Forward to the login action
}
My login action:
login() {
var session = get(this, 'session');
session.authenticate('authenticator:myauthenticator', { authParams: { scope: 'openid' } });
}
This grabs the session object, and calls my custom authenticator. So far, this is basically just ember-simple-auth boilerplate, and complies with the examples supplied in the Auth0 Ember-Simple-Auth documentation.
Where I run into trouble is my custom authenticator. The base authenticator is here. You can see that it handles basic login logic easily, including showing the Auth0 lock when a user isn't authenticated. However it has no logic for handling the kind of SSO-session checking that I want to implement. So I implemented a custom authenticator as below, using examples provided by Auth0 for (basically) this exact scenario (you can see their examples [here], I'm using a slightly altered version)3:
authenticate(options) {
return new Ember.RSVP.Promise((res) => {
// the callback that will be executed upon authentication
var authCb = (err, profile, jwt, accessToken, state, refreshToken) => {
if (err) {
this.onAuthError(err);
} else {
var sessionData = { profile, jwt, accessToken, refreshToken };
this.afterAuth(sessionData).then(response => res(this._setupFutureEvents(response)));
}
};
var lock = this.get('lock');
// see if there's a SSO session available
lock.$auth0.getSSOData(function(err, data) {
if (!err && data.sso) {
// there is! redirect to Auth0 for SSO
options.authParams.callbackOnLocationHash = true;
lock.$auth0.signin(options.authParams, authCb);
} else {
// regular login
lock.show(options, authCb);
}
});
});
}
This behaves mostly as I would expect it to. When I log in with an existing session from another SSO-enabled app on the same domain, if (!err && data.sso) resolves to true, and lock.$auth0.signin(options.authParams, authCb) is called. However, this signin logic is not working as intended. Auth0.signin calls the Auth0.authorize method, which generates a target URL that looks something like:
https://mydomain.auth0.com/authorize?scope=openid&response_type=token&callbackOnLocationHash=true&sso=true&client_id=(MyClientIdHash)&redirect_uri=localhost%23access_token%3(MyAccessToken)%26id_token%3(MyIdToken1).(MyIdToken2).(MyIdToken3)token_type%3DBearer&auth0Client=(MyAuth0Client)
My application is then redirected to this URL for authorization. I get a 302 and am redirected back to the callback URL (my root page). Because there is a new page transition, if (!get(session, 'isAuthenticated')) is hit again. It returns false, and so the same logic repeats itself, looping indefinitely.
Does anyone have any insight on what I might be doing incorrectly here? The authorize endpoint seems to behave as if I were being authenticated, but then the authentication is never actually triggered. I've debugged through this code fairly extensively but seen no obvious red flags, and I've followed provided examples closely enough that I'm not sure what I would change. I'm not entirely sure where the failure to authenticate is happening such that get(session, 'isAuthenticated') is false.

What is a good way to implement a custom authentication in Firebase?

I've done some things using firebase (so cool).
I'm doing the custom login, I've generated a AUTH_TOKEN (using nodejs).
My question is if I need to pass in all my page that I wanna to protect the code below?
Peace,
Tulio Cruz
var dataRef = new Firebase("https://example.firebaseio.com");
// Log me in.
dataRef.auth(AUTH_TOKEN, function(error, result) {
if(error) {
console.log("Login Failed!", error);
} else {
console.log('Authenticated successfully with payload:', result.auth);
console.log('Auth expires at:', new Date(result.expires * 1000));
}
});
I'm not sure I fully understand your question. If you want to know if you need to call auth every time a page is loaded -- yes you do. When using custom login with the low-level auth() api call, we don't do any session management for you.
You only need to call auth() once per page load though -- not once for each Firebase reference.

Firebase password resets

I'm trying to create a password reset mechanism and am stuck. Any suggestions how to do this with Firebase basic email/password authentication
[Engineer at Firebase - Update 2014-01-27]
Firebase Simple Login now supports password resets for email / password authentication.
Each of the Simple Login client libraries has been given a new method for generating password reset emails for the specified email address - sendPasswordResetEmail() on the Web and Android, and sendPasswordResetForEmail() on iOS.
This e-mail will contain a temporary token that the user may use to log into their account and update their credentials. This token will expire after 24 hours or when the user changes their password, whichever occurs first.
Also note that Firebase Simple Login enables full configuration of the email template as well as the sending address (including whitelabel email from your domain for paid accounts).
To get access to this feature, you'll need to update your client library to a version of v1.2.0 or greater. To grab the latest version, check out https://firebase.google.com/docs/.
Also, check out https://firebase.google.com/docs/auth/web/password-auth for the latest Firebase Simple Login - Web Client docs.
This is something that Firebase doesn't do very well. As you'll notice it requires the user to remember their old password. Usually if you want to reset a password it's because you've forgotten it. Hopefully the improve the methods they provide for account management.
https://www.firebase.com/docs/security/simple-login-email-password.html
authClient.changePassword(email, oldPassword, newPassword, function(error, success) {
if (!error) {
console.log('Password change successfully');
}
});
This was the first google result that came up when trying to figure out my issue.. for anyone who uses yeoman angularfire generator but would like to add the send email feature, this should work.
add the following to the simple login factory in simpleLogin.js:
resetPassword: function(emailIn){
return auth.$resetPassword({
email: emailIn
}, function(error) {
if (error) {
switch (error.code) {
case "INVALID_USER":
console.log("The specified user account does not exist.");
break;
default:
console.log("Error resetting password:", error);
}
} else {
console.log("Password reset email sent successfully!");
}
});
},
and call it from your login.js file
$scope.resetPassword = function(email){
simpleLogin.resetPassword(email)
};

how to retrieve login status while using offline_access

I'm facing a little problem because of the offline_access permission I'm requesting for my website.
I'm using the code that is given in the documentation in order to define if someone is logged or not :
if ($user) {
try {
// Proceed knowing you have a logged in user who's authenticated.
$user_profile = $facebook->api('/me');
} catch (FacebookApiException $e) {
$user = null;
}
}
But as I have an offline access, it seems that I'm always having a value for $user. So how can i log out someone from my website ?
Is there any way to retrieve a status via the php SDK ?
Thanks for the help,
Stéphane
In PHP try using GetLogoutUrl and sending the user there. You can also call the JS FB.logout() call from client-side. If you want to remove the app from the user, call HTTP delete to me/permissions.