I am developing an app from ionic-1. I also implemented facebook login plugin. I've followed this steps. I have no errors, but when I click on the facebook button, it doesn't work, no errors displaying. I use alert in every error catch but no alert will be displayed.
NOTE: I am running in an real android device because they said that native plugin will not work in browser.
Please help me because Im working with my thesis. Thanks to all of you!
Here's my code:
.controller('CreateAccountCtrl', ['$scope','$http','$state','$q','UserService','$stateParams', '$ionicLoading','$timeout','$ionicPopup',function($scope, $http,$state,$q, UserService,$stateParams,$ionicLoading,$timeout,$ionicPopup){
$scope.$on('$ionicView.beforeEnter', function(e){
$ionicLoading.show({
animation: 'fade-in', showBackdrop: true
});
});
$scope.$on('$ionicView.afterEnter', function(e){
$ionicLoading.hide();
$scope.formData = {};
$scope.showAlert = function(ttl,msg){
var alertPopup = $ionicPopup.alert({
title: ttl,
template: msg
});
};
});
// facebook
// This is the success callbak from the login method
var fbLoginSuccess = function(response){
if(!response.authResponse){
fbLoginError("Cannot find the authResponse");
return;
}
var authResponse = response.authResponse;
getFacebookProfileInfo(authResponse)
.then(function(profileInfo){
// store user data on local storage
UserService.setUser({
authResponse: authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture: "http://graph.facebook.com/" + authResponse.userID + "/picture?type=large"
});
$ionicLoading.hide();
$state.go('app.home');
}, function(fail){
alert(fail);
// Fail get profile info
console.log('Profile Info Fail', fail);
});
};
// This is the fail callback from the login method
var fbLoginError = function(error){
console.log('fbLoginError', error);
alert(error);
$ionicLoading.hide();
};
// This method is to get the user profile info from the facebook api
var getFacebookProfileInfo = function(authResponse){
var info = $q.defer();
facebookConnectPlugin.api('/me?fields=email,name&access_token=' + authResponse.accessToken, null,
function(response){
alert(response);
console.log(response);
info.resolve(response);
},
function(response){
console.log(response);
alert(response);
info.reject(response);
}
);
return info.promise;
};
// This method is executed when the user press the "Login with faceboook" button
$scope.facebookSignIn = function(){
alert(1);
facebookConnectPlugin.getLoginStatus(function(success){
if(success.status === 'connected'){
// The user is logged in and has authenticated your app, and response.authResponse supplies
// the user's ID, a valid access token, a signed request, and the time the access token
// and signed request each expire
console.log('getLoginStatus', success.status);
alert(success.status);
// Check if we have our user saved
var user = UserService.getUser('facebook');
if(!user.userID){
getFacebookProfileInfo(success.authResponse)
.then(function(profileInfo){
UserService.setUser({
authResponse: success.authResponse,
userID: profileInfo.id,
name: profileInfo.name,
email: profileInfo.email,
picture : "http://graph.facebook.com/" + success.authResponse.userID + "/picture?type=large"
});
$state.go('app.home');
}, function(fail){
console.log('Profile info fail', fail);
alert(fail);
});
}else{
$state.go('app.home');
}
}else{
// If (success.status === 'not_authorized') the user is logged in to Facebook,
// but has not authenticated your app
// Else the person is not logged into Facebook,
// so we're not sure if they are logged into this app or not.
console.log('getLoginStatus', success.status);
alert(success.status);
$ionicLoading.show({
template: 'Logging in...'
});
facebookConnectPlugin.login(['email','public_profile'], fbLoginSuccess, fbLoginError);
}
});
};
}]);
And in my html
<a class="facebook-sign-in button button-block button-facebook" ng-click="facebookSignIn()">
<i class="icon ion-social-facebook"></i>
Sign in using facebook
</a>
APP_NAME="must be facebook application name that's created on facebook developer not your app name"
APP_ID=facebook app id.
Install with facebook v4
$ cordova plugin add cordova-plugin-facebook4 --save --variable APP_ID="123456789" --variable APP_NAME="myApplication"
$rootScope.loginFacebook = function() {
$cordovaFacebook.login(["public_profile", "email", "user_birthday", "user_photos"]).then(function(success){
console.info(success.status);
if (success.status === 'connected') {
var checkrequest = {
'AuthSession[device_token]': $localStorage.device_token
}
appname.check(checkrequest).then(function(response) {
console.log(response);
if (response.key == "NOAUTH") {
$state.go('main.allowPush')
}
})
} else if (success.status === 'not_authorized') {
console.info('the user is logged in to Facebook but has not
authenticated your app')
} else {
console.info('the user is nott logged in to Facebook')
}
}, function(error) {
console.info(error);
});
}
Related
I can not create a server session in the mobile requests.
I am developing a mobile application. Sign in with LinkedIn to application made only from mobile.
I wrote the rest api with nodejs. I used the passport for linkedin login.Then I tested it from browser.It worked smoothly on browser.
When i make a request to my endpoint(/auth/linkedin) it redirect to linkedin and typing my account information and allow the app .It is redirect again to callback endpoint (auth/linkedin/callback). I am returning information of the logged-in user if success login. I am making process this session information on next requests.
But when I login from mobile, user information is printed webview and I cannot create session.How can i solve this problem. What am I doing wrong?
I am junior. if you see my code wrong please specify for improve my skill.
app.js
const AuthController = require("./router/Auth");
app.use(express.json());
app.use(session({
secret:'secretkey',
saveUninitialized: false,
resave: true,
cookie: {maxAge: 365*24*60*60*1000}
}));
app.use(passport.initialize());
app.use(passport.session());
app.use('/auth',AuthController);
passport.use(new LinkedInStrategy({
clientID: config.linkedin.clientID,
clientSecret: config.linkedin.clientSecret,
callbackURL: config.baseUrl[env] + "/auth/linkedin/callback",
scope: config.linkedin.scope
},
function(accessToken, refreshToken, profile, done) {
User.findOne({'linkedin.id' : profile.id}, function(err, user) {
if (err) return done(err);
if (user) return done(null, user);
else {
// if there is no user found with that linkedin id, create them
var newUser = new User();
// set all of the linkedin information in our user model
newUser.linkedin.id = profile.id;
newUser.linkedin.token = accessToken;
newUser.name = profile.displayName;
if (typeof profile.emails != 'undefined' && profile.emails.length > 0)
newUser.email = profile.emails[0].value;
if(typeof profile.photos != 'undefined' && profile.photos.length> 0)
newUser.photo = profile.photos[0]
// save our user to the database
newUser.save()
.then(createWallet)
.then(updateWallet)
.then(user => {
return done(null,user)
})
.catch(err =>{
throw err;
});
}
});
}
));
passport.serializeUser(function(user, done){
done(null, user.id)
})
passport.deserializeUser(function(id, done) {
User.getUserById(id, function(err, user) {
done(err, user);
});
});
app.listen(PORT,()=>{
console.log("Listening...",PORT);
});
function createWallet (user){
const userId = user.id;
return new Promise((resolve,reject) => {
request(config.blockChain['url']+'/?type=register&userID='+userId,{json:true} ,(err,res,body)=>{
if(err) reject(err);
user.wallet = {
"secret":body.secret,
"publicKey":body.publicKey
}
resolve(user);
})
}
)
}
function updateWallet(user){
return user.save();
}
Auth.js
router.get('/linkedin', passport.authenticate('linkedin'));
router.get('/linkedin/callback',
passport.authenticate('linkedin',{ failureRedirect: '/'}),(req,res)=>{
const user = req.user;
response = {
status:true,
msg:"Login is successfull",
data: user
}
res.status(200).json(response);
});
I try to create Cordova mobile app based on angularjs following this tutorial: https://mobilefirstplatform.ibmcloud.com/blog/2016/08/11/best-practices-for-building-angularjs-apps-with-mobilefirst-foundation-8.0/
and LTPA Based Security Check login flow (in Mobilefirst 8.0) based on sample from: https://github.com/mfpdev/ldap-and-ltpa-sample
Mobile app is using angular. Authorisation implementation:
app.factory('Auth', function ($rootScope) {
var securityCheckName = 'LTPA',
_$scope = null,
challengeHandler = null,
URL = '',
challengeHandler = WL.Client.createSecurityCheckChallengeHandler(securityCheckName);
challengeHandler.securityCheckName = securityCheckName;
WLAuthorizationManager.login(securityCheckName, {'username': '', 'password': ''});
challengeHandler.handleChallenge = function (challenge) {
if (challenge && challenge.loginURL) {
URL = challenge.loginURL;
}
};
challengeHandler.handleSuccess = function (data) {
// code
};
challengeHandler.handleFailure = function (error) {
// code
};
return {
login: function ($scope, username, password) {
_$scope = $scope;
var request = new WLResourceRequest(URL, WLResourceRequest.POST);
request.send("j_username=" + username + "&j_password=" + password + "&action=Login").then(
function(response) {
challengeHandler.submitChallengeAnswer({});
},
function(error) {
// on error
});
}
};
});
This seems to work only on iOS. On Android handleSuccess function is not invoked.
As in the past, there was a problem with sending cookies on Android devices (with older MF versions) so I tried workaround in login function, that the hidden InAppBrowser was opened with logon form, then a user login process was made and once token was received, it was set via cordova-cookie-master-plugin and submitChallengeAnswer was invoked:
login: function ($scope, username, password) {
_$scope = $scope;
var request = new WLResourceRequest(URL, WLResourceRequest.POST);
request.send("j_username=" + username + "&j_password=" + password + "&action=Login").then(
function(response) {
if (device.platform == "iOS") {
challengeHandler.submitChallengeAnswer({});
} else {
iab = cordova.InAppBrowser.open(URL, "_blank", "hidden=yes");
iab.addEventListener('loadstop', function(event){
iab.executeScript({code:
'var field1 = document.getElementsByTagName("input")[0];' +
'var field2 = document.getElementsByTagName("input")[1];' +
'field1.setAttribute("value", "' + username + '");' +
'field2.setAttribute("value", "' + password + '");' +
'document.forms[0].submit();'
}, function(){
// on error
});
try {
cookieMaster.getCookieValue(URL, 'LtpaToken2', function(data) {
WL.Client.setCookie({
"name" : "LtpaToken2",
"value" : data.cookieValue,
"domain" : ".example.com",
"path" : "/",
"expires" : "Thu, 18 Dec 2999 12:00:00 UTC"
}).then(function() {
challengeHandler.submitChallengeAnswer({});
}).fail(function(err) {
// on error
});
}, function(error) {
// on error
});
} catch(err) {
// on error
}
});
iab.addEventListener('exit', function(){
iab.removeEventListener('loadstop', function() { /* on success */ });
});
}
},
function(error) {
// on error
});
}
This solution also not working for me. I've expect that after challengeHandler.submitChallengeAnswer() was fired, the handleSuccess will be invoked, but it is not happened. handleChallenge is invoked instead.
I am trying to log my users with Facebook, but can't figure out how to do it.
This is the code I have so far :
facebookConnectPlugin.getLoginStatus(
function(status) {
if (status.status != "connected") {
facebookConnectPlugin.login(
['public_profile', 'email'],
function(success) {
console.log("Success", success);
},
function(error) {
console.log("Error", error);
}
);
}
else {
console.log("logging status : ", status.status);
}
},
function(error) {
console.log("Getting logging status failed : ", error);
}
);
On my Android device, I do not have the Facebook app installed, and I am not logged into Facebook on any browser.
I would expect the facebookConnectPlugin.login() method to popup the login form, but instead this is what it returns :
Which basically means : "You did not enter. You are not connected to Facebook. Enter Facebook and try again".
I looked into this Meteor plugin to see how they were doing it, but they respect the exact same logic.
I am not sure what to do from here. Any suggestion is most welcome !
you can try code for get Login Status read more here
var fbLoginSuccess = function (userData) {
alert("UserInfo: " + JSON.stringify(userData));
facebookConnectPlugin.getLoginStatus(
function (status) {
alert("current status: " + JSON.stringify(status));
}
);
};
you can try code for get User Profile.
facebookConnectPlugin.login( ["public_profile","email"],
function (response) {
if(response.authResponse.userID!=''){
facebookConnectPlugin.api(response.authResponse.userID+"/?fields=id,email,first_name", ["public_profile"],
function (response) {
console.log('SUCCESS:'+response);
alert('first_name : '+response.first_name+',email:'+response.email+',id:'+response.id);
},
function (response) {
console.log('ERROR:'+response);
});
}
},
function (response) {
console.log('ERROR:'+response);
});
let me know if its not working...
i use this tutorial https://github.com/nraboy/ng-cordova-facebook-example but this example is not implemented the function of logout ,i add this code:
facebookExample.controller("LogoutController", function($scope, $http, $localStorage, $location) {
$scope.logout = function() {
$cordovaFacebook.logout();
}, function(error) {
alert("There was a problem signing in! See the console for logs");
console.log(error);
}
});
profile.html :
<ion-nav-buttons side="right">
<button class="button icon-left ion-log-out button-stable" ng-controller="LogoutController" ng-click="logout()">Logout</button>
</ion-nav-buttons>
but i found any result
Your code is invalid javascript... lots of parsing errors. also, you dont need another controller just for logout. The fact that a user is logged in is based upon an access token in localstorage, just wipe it and go to another state.. update your profile controller to this:
facebookExample.controller("ProfileController", function($scope, $http, $localStorage, $location) {
$scope.init = function() {
if($localStorage.hasOwnProperty("accessToken") === true) {
$http.get("https://graph.facebook.com/v2.2/me", { params: { access_token: $localStorage.accessToken, fields: "id,name,gender,location,website,picture,relationship_status", format: "json" }}).then(function(result) {
$scope.profileData = result.data;
}, function(error) {
alert("There was a problem getting your profile. Check the logs for details.");
console.log(error);
});
} else {
alert("Not signed in");
$location.path("/login");
}
};
$scope.logout = function(){
delete $localStorage.accessToken;
$location.path("/login");
};
});
profile.html:
<ion-nav-buttons side="right">
<button class="button icon-left ion-log-out button-stable" ng-click="logout()">Logout</button>
</ion-nav-buttons>
I have to update our app from using the v1 graph api and sdk methods to v2.X.
I have downloaded the latest facebookConnect plugin found here
I need to get the user to login to allow our app to post to the users timeline. Before i have to request publish_scope permission, but this has now changed to publish_actions.
I have tried this code, but apparently you cannot request publish_actions straight away so you have to break it up, and request public_profile first, then publish_actions. I get this message when trying to do public_profile and publish_actions at the same time
Cannot pass a publis or manage permission (publish_actions) to a
request for read authorization
So my code looks like this, but i dont think i am doing it right? Do i need the second login call? Should i be using another method? Also if the user says "Not now" to the publish_actions permission, there doesnt seem to be a way to handle it, because the success method is called?
Here is some code
$(this).find('#imgFacebook').on("tap", function (e) {
e.preventDefault();
var onError = function(msg, e) {
console.log(msg + JSON.stringify(e));
logout();
};
var requestPublishPermissions = function(f) {
console.log('requesting publish permission...');
facebookConnectPlugin.login(['publish_actions'], function(e) {
console.log('Permission granted: ' + JSON.stringify(e));
if (e.authResponse) {
// user has logged in and allowed permissions!! YAY
} else {
alert('There was an error logging you in to facebook, or you did not authorize the app to post on your wall');
}
}, function(e) {
onError('Permission denied: ', e);
});
};
var login = function() {
console.log('logging in...');
facebookConnectPlugin.login(['public_profile'], function(e) {
console.log('logged in successfully: ' + JSON.stringify(e));
requestPublishPermissions(e);
}, function(e) {
if (e.errorMessage != 'User cancelled dialog') {
alert('There was an error logging you in to facebook: ' + JSON.stringify(e));
}
onError('login error: ', e);
});
};
var logout = function(success) {
// check that knowone is logged in
facebookConnectPlugin.getLoginStatus(function(e) {
console.log('status is: ' + JSON.stringify(e));
if (e.authResponse && e.status == 'connected') {
console.log('logging out...');
facebookConnectPlugin.logout(function() {
console.log('logout successful...');
if (success) success();
}, function(e) {
console.log('error logging out: ' + JSON.stringify(e));
if (success) success();
});
} else {
// know one logged in
if (success) success();
}
}, function(e) {
if (success) success();
})
};
logout(login);
});
Because i do not want to save the users details on the application, i make sure that logout is called first, and then log the user is.
Anyone got any pointers?