firebase facebook and twitter Re-authenticating: - facebook

I have properly set firebase authentication in my app for Facebook and twitter but I have a problem.
Once an user is connected, if he decides to logout and enter with a different credentials he can't do it. Indeed if he tries to logout again with Facebook the system doesn't ask his username and password but uses credentials inserted before.
I tried with rememberMe option but it didn't solve the problem.
Can someone help me?

I strictly followed the example that can be found here: https://www.firebase.com/docs/security/simple-login-overview.html
Any way i modified it a little bit for doing some check.
Here is the code I'm using
firebaseRef = new Firebase('https://cicero.firebaseio.com');
authClient = new FirebaseAuthClient(firebaseRef, function(error, user) {
if (error) {
/*login error*/
switch(error.code) {
case 'INVALID_EMAIL':
case 'INVALID_PASSWORD':
EventDispatcher.trigger("login_error","invaild user or email");
break;
case 'INVALID_USER':
EventDispatcher.trigger("login_error","user does not exist.");
break;
case 'UNKNOWN_ERROR':
EventDispatcher.trigger("login_error","unknown error, please contact event administrator.");
}
} else if (user) {
/*user si logga*/
cicero_user = user;
var users = new Users();
users.firebase.on('value',function(){
if(cicero_user.provider == 'password'){
var user = users.findWhere({id: cicero_user.id, type:'password'});
cicero_user.displayName = user.get('name');
alert(cicero_user.displayName);
} else {
var social_user = users.findWhere({id: cicero_user.id,type: cicero_user.provider});
if(social_user == undefined){
var new_social_user = new User({id: cicero_user.id, name: cicero_user.displayName, type: cicero_user.provider});
users.add(new_social_user);
}
}
Ciceronotifier.on();
EventDispatcher.trigger("hide_spinner");
Backbone.history.navigate("map", {trigger: true});
},this);
} else {
/*user si slogga*/
cicero_user = undefined;
firebaseRef.unauth(); <-- i have added these two lines right now but the problem seems unresolved
firebaseRef = new Firebase('https://cicero.firebaseio.com');
Backbone.history.navigate("login", {trigger: true});

Related

User Password Not Resetting in ASP Core

Im attempting to create a forgot password feature in asp core with entity framework.
[UnitOfWork]
public virtual async Task PasswordReset(PasswordResetViewModel resetPasswordViewModel)
{
//var user = await GetUserByChecking(emailAddress);
var user = await _userManager.FindByEmailAsync(resetPasswordViewModel.UsernameOrEmailAddress);
if (user == null)
{
throw new UserFriendlyException("User not found!");
}
var result = await _userManager.ResetPasswordAsync(user, resetPasswordViewModel.PasswordResetToken, resetPasswordViewModel.NewPassword);
switch (result.Succeeded)
{
case true:
throw new UserFriendlyException("Password Reset");
case false:
throw new UserFriendlyException(result.Errors.ToString());
default:
break;
}
}
when the following runs
userManager.ResetPasswordAsync
i get a successful result however i am still unable to login with the new password and the old password continues to work.
I have fixed this. The issue was that I returned an exception on a successful password reset. This for some reason did not save the change . I changed it to return a JSON string and it worked

haw load user information after login SPA koa.js

I realized the authorization of the user through the passport (Koa, Mongodb, React, Redux).
router.post('/login', function(ctx, next) {
return passport.authenticate('local', async function(err, user, info) {
if (err) throw err;
if (user === false) {
ctx.status = 401;
ctx.body = { error: info };
} else {
ctx.body = {
success: true
};
await ctx.login(user);
}
})(ctx, next);
})
If the user logged in, he redirects to the profile page(main page).
router.get('/login', function(ctx, next) {
if (ctx.isAuthenticated()) {
ctx.redirect('/');
} else {
ctx.body = fs.readFileSync(path.resolve(path.join('build', 'index.html')), 'utf8')
}
});
Since I have a spa I always pass a static file (routing on the client via a react-router)
The problem is that I can not understand how I get information about the user when the profile page is loaded
If I send a ajax-request (feth) from the React-component, then the request for another session id and it is not associated with the user.
Or, I need to do this on the server, but how I might to use the store storage on the server?
How best to solve this problem?
Well, while it might not be the best way, the easiest way to do this would be to have a section in your html file like..
<script type="text/javascript">
window.currentUser = $$USER$$
</script>
And then do a replace on the body.
let content = fs.readFileSync(path.resolve(path.join('build', 'index.html')), 'utf8')
content = content.replace('$$USER$$', JSON.stringify(user))
ctx.body = content
In your React app, you can use window.currentUser.

can't get gmail user displayname via firebase3 login in Ionic platform

I am working on google auth with firebase signinwithcredential. I first used cordovaoath to get the id token and sign it in with firebase. I specifically indicated in my code that I would like to get the displayName, but it always come back null. I was wondering anyone have faced the same problem?
this.loginWithGoogle = function loginWithGoogle() {
$cordovaOauth.google("mygoogleclient id here", ["https://www.googleapis.com/auth/calendar","https://www.googleapis.com/auth/userinfo.email",
"https://www.googleapis.com/auth/userinfo.profile","https://www.googleapis.com/auth/plus.me", "https://www.googleapis.com/auth/plus.login", "https://www.googleapis.com/auth/drive"]).then(function (result) {
// "email", "profile",
console.log("first come here to oath");
console.log("Response Object -> " + JSON.stringify(result));
var unsubscribe = firebase.auth().onAuthStateChanged(function (firebaseUser) {
unsubscribe();
// Check if we are already signed-in Firebase with the correct user.
// Build Firebase credential with the Google ID token.
var credential='';
credential = firebase.auth.GoogleAuthProvider.credential(
result.id_token);
// Sign in with credential from the Google user.
firebase.auth().signInWithCredential(credential).catch(function (error) {
// Handle Errors here.
var errorCode = error.code;
var errorMessage = error.message;
// The email of the user's account used.
var email = error.email;
// The firebase.auth.AuthCredential type that was used.
var credential = error.credential;
});
});
}, function (error) {
console.log("Error -> " + error);
});
};
sreenshot of my returned result
You should request an access token, and not an ID token, if you are requesting additional scopes.
To fix your code, change this line:
var credential = firebase.auth.GoogleAuthProvider.credential(
null, result.access_token); // <- access_token

Facebook OAuthException - This authorization code has expired. [code=100]

I have setup the Facebook API SDK for ColdFusion - https://github.com/affinitiz/facebook-cf-sdk
I've setup a login process which works successfully but after 10 minutes or so when I return and refresh the page, it shows the following error:
This authorization code has expired. [code=100]
Is there something I am missing with the FB login? Am I meant to be checking against something manually in order to persist the session?
Cheers
Shaun
<cfscript>
import facebook.sdk.FacebookApp;
import facebook.sdk.FacebookGraphAPI;
// Replace this with your appId and secret
APP_ID = "";
SECRET_KEY = "";
SCOPE = "publish_stream";
if (APP_ID is "" or SECRET_KEY is "") {
// App not configured
facebookGraphAPI = new FacebookGraphAPI();
} else {
// Create facebookApp instance
facebookApp = new FacebookApp(appId=APP_ID, secretKey=SECRET_KEY);
// See if there is a user from a cookie or session
userId = facebookApp.getUserId();
if (userId) {
try {
userAccessToken = facebookApp.getUserAccessToken();
facebookGraphAPI = new FacebookGraphAPI(accessToken=userAccessToken, appId=APP_ID);
userObject = facebookGraphAPI.getObject(id=userId);
userFriends = facebookGraphAPI.getConnections(id=userId, type='friends', limit=10);
authenticated = true;
} catch (any exception) {
// Usually an invalid session (OAuthInvalidTokenException), for example if the user logged out from facebook.com
// this is where the error occurs
userId = 0;
facebookGraphAPI = new FacebookGraphAPI();
}
} else {
facebookGraphAPI = new FacebookGraphAPI();
}
// Login or logout url will be needed depending on current user state.
if (userId) {
logoutUrl = facebookApp.getLogoutUrl();
} else {
parameters = {scope=SCOPE};
loginUrl = facebookApp.getLoginUrl(parameters);
}
}
Apparently you're not exchanging the OAuth code to an Access Token. See the docs here how to do that: Manually Build a Login Flow

How can i post the feed to facebook page as admin using c# sdk?

I want to update the facebookpage using c# sdk. I have partially successful with this, the problem is whenever I post messages to the page, post is visible only for admin(i am the admin of the page)is logged In. I want the post or feed to be visible to every one who visit the page.
(even admin is logged out post's are not visible to admin also)
The following code i am trying to achieve
public ActionResult FacebookPagePost()
{
string app_id = "xxxx";
string app_secret = "xxx";
string scope = "publish_stream,manage_pages";
string page_Id = "xxX";
if (Request["code"] == null)
{
return Redirect(string.Format(
"https://graph.facebook.com/oauth/authorize?client_id={0}&redirect_uri={1}&scope={2}",
app_id, Request.Url.AbsoluteUri, scope));
}
else
{
try
{
Dictionary<string, string> tokens = new Dictionary<string, string>();
string url = string.Format("https://graph.facebook.com/oauth/access_token?client_id={0}&redirect_uri={1}&scope={2}&code={3}&client_secret={4}",
app_id, Request.Url.AbsoluteUri, scope, Request["code"].ToString(), app_secret);
HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
{
StreamReader reader = new StreamReader(response.GetResponseStream());
string vals = reader.ReadToEnd();
foreach (string token in vals.Split('&'))
{
tokens.Add(token.Substring(0, token.IndexOf("=")),
token.Substring(token.IndexOf("=") + 1, token.Length - token.IndexOf("=") - 1));
}
}
string access_token = tokens["access_token"];
var client = new FacebookClient(access_token);
dynamic fbAccounts = client.Get("/me/accounts");
dynamic messagePost = new ExpandoObject();
messagePost.picture = "http://pic.com/pic.png";
messagePost.link = "http://www.examplearticle.com";
messagePost.name = "name goes here";
messagePost.description = "description goes here";
//Loop over the accounts looking for the ID that matches your destination ID (Fan Page ID)
foreach (dynamic account in fbAccounts.data) {
if (account.id == page_Id)
{
//When you find it, grab the associated access token and put it in the Dictionary to pass in the FB Post, then break out.
messagePost.access_token = account.access_token;
break;
}
}
client.Post("/" + page_Id + "/feed", messagePost);
}
catch (FacebookOAuthException ex)
{
}
catch (Exception e)
{
}
}
}
1) Create a Facebook App at: developers.facebook.com and get yourself an APPID and APPSECRET. (there are a lot of tutorials online for doing this so I will skip repeating it)
2) Go to: http://developers.facebook.com/tools/explorer and choose your app from the dropdown and click "generate access token".
3) After that do the following steps here:
https://stackoverflow.com/questions/17197970/facebook-permanent-page-access-token to get yourself a permanent page token.
(I can not stress this enough, follow the steps carefully and thoroughly)*
*I have tool I built that does this for me, all I enter is the APPID, APPSECRET and ACCESSTOKEN which the tool then generates a permanent page token for me. Anyone is welcomed to use it and help make it better,
https://github.com/devfunkd/facebookpagetokengenerator
=========================================================================
Ok at this point you should have your APPID, APPSECRET and a PERMANENT PAGE TOKEN.
=========================================================================
In your Visual Studio solution:
4) Using Nuget:Install-Package Facebook
5) Implement the Facebook client:
public void PostMessage(string message)
{
try
{
var fb = new FacebookClient
{
AppId = ConfigurationManager.AppSettings.Get("FacebookAppID"),
AppSecret = ConfigurationManager.AppSettings.Get("FacebookAppSecret"),
AccessToken = ConfigurationManager.AppSettings.Get("FacebookAccessToken")
};
dynamic result = fb.Post("me/feed", new
{
message = message
});
}
catch (Exception exception)
{
// Handle your exception
}
}
I hope this helps anyone who is struggling to figure this out.