Facebook login on mobile via Cordova/Angular/Ionic - angularjs

I'm working in a hybrid app to report potholes in our city.
The user can register to the app in a classic way (fill forms) or via one of the social networks (facebook, gmail, twitter).
The system works through a server on rails and a mobile app as a client(ionic/angular)
On the server side we have solved this, the user can make sign up / sign in to the page in the way that they want.
But with have several problems with the app, the app does nothing when you make click to the button of "sign in via facebook"
this is the style it is organized.
app/
plugins/
InAppBrowser
www/
css/
js/
controllers/
splash.js
map.js
tabs.js
services/
users.js
notifications.js
app.js
utils.js
lib/
angular/
ng-cordova-oauth/
ngCordova/
ionic/
templates/
map.html
splash.html
tabs.html
index.html
The splash.js controller is in charge of making the login function.
angular.module('app')
.controller('SplashCtrl', function($scope, User, $state, $ionicPopup, $auth, $cordovaOauth) {
$scope.session_id = User.session_id;
$scope.facebookLogin = function() {
alert("flag1");
User.fbSignIn().then(function() {
alert("flag2");
User.fbGetData().then(function() {
alert("flag3");
User.fbAuth().then(function() {
alert("flag4");
// Detect if it is a sign in or sign up
if (User.username) {
console.log('Controller reports successfull social login.');
$state.go('tab.map');
} else {
// Open finish signup modal
console.log('Contorller reports this is a new user');
$state.go('finish_signup');
}
}, function() {
alert("flag5");
$ionicPopup.alert({
title: '<b>App</b>',
template: 'Credenciales no vĂ¡lidas, vuelve a intentar.',
okText: 'Aceptar',
okType: 'button-energized'
})
});
}, function() {
alert("flag6");
// alert('Could not get your Facebook data...');
});
}, function() {
alert("flag7");
// alert('Could not sign you into Facebook...');
});
}
})
I put some alert flags through the functions to see where the app get stuck.
I can only see the 'flag1' alert on the phone.Then nothing happens
the controller communicates with the service users.js
I put the code on pastebin because it's too long
users.js service
The client must request an access token to the server and then compare in SplashCtrl if they got the token access the app redirects the user to tabs.html template that would be the main page.
The console server shows nothing. So the request application never communicates to the server. Eventhough the 'CLIENTS' and 'SERVER' variables are already declared in app.js
.constant('SERVER', {
url: 'https://rails-tutorial-denialtorres.c9.io'
})
.constant('CLIENTS', {
facebook: 'fb Api'
});
I can only logging of the server if I put a username and password in a traditional way
preview
I hope you can help me with this guys
regards and thanks!!

you try this ?
http://ngcordova.com/docs/plugins/oauth/
I tested and work very well, easy to implement, and also you can parse the json with token (and use server side if you need)
Remember this work ONLY with real device, not with Ionic Serve.
In case you looking for custom facebook login (javascript), try this code :
facebookStatus = function() {
var dfd = new jQuery.Deferred();
FB.getLoginStatus(function(response) {
if (response.status === 'connected') {
dfd.resolve({status: response.status, token: response.authResponse.accessToken});
} else if (response.status === 'not_authorized') {
// the user is logged in to Facebook, //but not connected to the app
dfd.resolve({status: response.status, token: false});
} else {
// the user isn't even logged in to Facebook.
FB.login(function(response) {
if (response.status=="connected"){
var token = response.authResponse.accessToken;
dfd.resolve({status: response.status, token: response.authResponse.accessToken});
}
}, {scope:'YOUR SCOPE HERE'});
}
});
return dfd.promise();
};
*Remember if you use this code, to add on index page the standard Facebook App details (something like)
<div id="fb-root"></div>
<script>
window.fbAsyncInit = function() {
FB.init({
appId : 'YOUR APP ID',
status : true, // check login status
cookie : false, // enable cookies to allow the server to access the session
xfbml : true // parse XFBML
});
};
// Load the SDK asynchronously
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
</script>

When I install the cordova plugin with add org.apache.cordova.inappbrowser
The id for the plugin is cordova-plugin-inappbrowser and the ngcordova.js library is looking for org.apache.cordova.inappbrowser
Changing those lines on ngcordova.js solves the issue.

Related

AngularJS - IdentityServer4.Quickstart.UI - 'AuthenticationProperties' is an ambiguous reference

I'm implementing an AngularJS app that will use IdentityServer4 for Authorization.
I have a stand alone Angular app within a .Net Core 2.0 app that calls the api controller in the .net core app. if I browse to http://localhost:5050/.well-known/openid-configuration I am getting the json returned.
I have used this example as a basis for my auth service:
function authService() {
var config = {
authority: "http://localhost:5050",
client_id: "js",
redirect_uri: "http://localhost:5050/LocalizationAdmin/callback.html",
response_type: "id_token token",
scope: "openid profile api1",
post_logout_redirect_uri: "http://localhost:5050/LocalizationAdmin/index.html"
};
var mgr = new Oidc.UserManager(config);
mgr.getUser().then(function (user) {
if (user) {
log("User logged in", user.profile);
} else {
log("User not logged in");
}
});
var service = {
login: login,
logout: logout,
};
return service;
function login() {
mgr.signinRedirect();
}
In callback.html I have added:
<body>
<script src="scripts/oidc-client.js"></script>
<script>
new Oidc.UserManager().signinRedirectCallback().then(function () {
window.location = "index.html";
}).catch(function (e) {
console.error(e);
});
</script>
</body>
It is trying to redirect to:
http://localhost:5050/account/login?returnUrl=%2Fconnect%2Fauthorize%2Fcallback%3Fclient_id%3Djs%26redirect_uri%3Dhttp%253A%252F%252Flocalhost%253A5050%252FLocalizationAdmin%252Fcallback.html%26response_type%3Did_token%2520token%26scope%3Dopenid%2520profile%2520api1%26state%3Dd526351a26f74202badb7685022a6549%26nonce%3D6c858921378645ca8fcad973eb26cc72
However I just want it to redirect to the IdentityServer4 login screen. How can I achieve this? Any help appreciated.
Edit:
I have added the UI templates from here:
https://github.com/IdentityServer/IdentityServer4.Quickstart.UI
But I am getting a number of errors, could this be because I am using .Net Core 2.0 version: assemblyref://IdentityServer4 (2.0.0-rc1-update1)
Error CS0104 'AuthenticationProperties' is an ambiguous reference between 'Microsoft.AspNetCore.Authentication.AuthenticationProperties' and 'Microsoft.AspNetCore.Http.Authentication.AuthenticationProperties'
Demo Project showing issue added to github here.
I have no idea how stable this is but I just used the powershell command pointing to the dev branch and it seems to be working.
iex ((New-Object System.Net.WebClient).DownloadString('https://raw.githubusercontent.com/IdentityServer/IdentityServer4.Quickstart.UI/dev/get.ps1'))
you might want to look instead at the quickstarts relating to 2.0.0-rc1-update1 which can be found here on the dev branch:
https://github.com/IdentityServer/IdentityServer4/tree/dev/docs/quickstarts
as they have been also updated.

Handling secure login page in protractor

My team is working to use AngularJs and Polymer components for a new web app. I am looking into how to create a UI automation suite for this. After lots of research looks like Protractor may help me out here with some tweaks to handle Polymer. But, the current challenge is as follows -
I navigate to the app
As part of our company policy, the every web visit is validated (unless within same session). Here is how the validation works -
A login page (non-Anugular) page appears after one types the required url. Sign in with the credentials
Another intermediate page appears where it asks to wait for page to load or click a link to go to next page. Click the link
Url changes back to the original used in #1
Note: These validation pages take hell lot of time to load (changes to different internal urls). Also, the validation is skipped sometimes (within same session or through some other logic)
I have been struggling to design a prototype to handle all these. I am also trying to use Page Object while designing the prototype. Here is what I have so far.
login.js
________________________________________________________
var currentUrl;
var lastChangedUrl;
var secureUrl = 'corplogin.ssogen2.corporate.company.com';
var getwayUrl = 'gateway.zscalertwo.net';
var loginSuite = function(driver) {
var defer = protractor.promise.defer();
describe('Handle login', function() {
/*afterEach(function() {
//driver.manage().deleteAllCookies();
})*/
//it('Login to security test', function(){
//********** Wait for page to load/URL to change to secure login page ************
driver.getCurrentUrl().then(function(url) {
currentUrl = url;
}).then(function() {
driver.wait(function() {
return driver.getCurrentUrl().then(function (url) {
lastChangedUrl = url;
return url !== currentUrl;
});
});
}).then(function() {
//********** login to secure page ************
if (lastChangedUrl.indexOf(secureUrl) > -1 || lastChangedUrl.indexOf(getwayUrl) > -1) {
var element = driver.findElement(By.name("username"));
element.sendKeys("Username");
element = driver.findElement(By.name("password"));
element.sendKeys("password"); //Give password
element = driver.findElement(By.name("submitFrm"));
element.click();
}
}).then (function() {
//********** page is slow. wait for page to load/URL to change ************
driver.getCurrentUrl().then(function(url) {
currentUrl = url;
}).then(function() {
driver.wait(function() {
return driver.getCurrentUrl().then(function (url) {
lastChangedUrl = url;
return url !== currentUrl;
});
});
}).then (function() {
//********** Click on the link to to go to test page ***********
if (lastChangedUrl.indexOf(getwayUrl) > -1) {
var element = driver.findElement(By.tagName("a"));
console.log("before click............");
element.click();
}
//********** page is slow. wait for page to load/URL to change ************
driver.getCurrentUrl().then(function(url) {
currentUrl = url;
}).then(function() {
driver.wait(function() {
return driver.getCurrentUrl().then(function (url) {
lastChangedUrl = url;
return url !== currentUrl;
});
});
})
.then (function() {
//return defer.promise;
//browser.pause();
});
}, 60000);
});
//});
}, 60000);
return defer.promise;
};
module.exports = loginSuite;
spec.js
___________________________________________________________________________
describe('Protractor Demo App', function() {
var myUrl = 'http://<my test app url>/';
var driver = browser.driver;
beforeEach(function() {
driver.get(myUrl);
});
it('should login', function() {
loginSuite(driver)
.then(
function(){
console.log("End of tests:");
expect(driver.getCurrentUrl()).toBe(myUrl);
});
});
The issue here -
My expectation here is to have the promise returns to spec.js after the secure login page is handled so that I can continue with other testing using the driver object. For the sake testing I am logging 'End of tests' message and doing a dummy validation. But, looks like those two lines don't get executed.
Login to the secure site works and I see page changes to original test page. I tested that with Browser.pause(). But, the logging 'End of test' never happens, nor the validation.
I need to handle the scenario where the secure login page doesn't appear. Not sure what adjustment I need to do in login.js page
Is my approach for page object and handling the promises wrong here? I am able to go to one step further on the test app page when all the code are placed under one js file instead of splitting them for page object. Please help here.
I wanted to share with you the "polymer way" of solving your problem.
The code below use two elements to monitor the URL, the auth flow, the previous page visited and log the user in/out of the app
The first will bind to the origin route, so you can send the user back there
<app-route
route="{{route}}"
pattern="/origin/:page"
data="{{data}}"
tail="{{subroute}}">
</app-route>
The second will bind to the authPage, allowing you to show/hide the auth page.
<app-route
route="{{subroute}}"
pattern=":authPage"
data="{{data}}
active="{{authPageActive}}">
</app-route>
User auth, monitoring and page redirecting
Use the element: <firebase-auth>
Is the user singned in?: signedIn="{{isSignedIn}}"
<firebase-auth id="auth" user="{{user}}" provider="google" on-
error="handleError" signedIn="{{isSignedIn}}"></firebase-auth>
Add an observer
observers: [
'_userSignedInStatus(isSignedIn)' // observe the user in/out
],
Add a Function
_userSignedInStatus: function (isSignedIn) {
if (isSignedIn === false) {
this.page = 'view404'; // redirect the user to another page
// import an element that cover the view
} else {
//send a log message to your database
}
}

Cordova InAppBrowser show location bar Cordova AngularJS Oauth

Hi I'm using the Cordova InAppBrowser and AngularJS Oauth plugins.
When I press a normal link button like this:
<a class="external" ng-href="https://www.website.com/" targe="_blank" >open link</a>
In combination with this:
<script>
$( document ).ready(function() {
// open links in native browser (phonegap);
$(document).on('click', '.external', function (event) {
event.preventDefault();
window.open($(this).attr('href'), '_blank');
return false;
});
});
</script>
It opens the link in the in app browser. In the InAppBrowser when loading the url it is showing the url location at the bottom. So this is working OK.
When the AngularJS Oauth plugin opens the InAppBrowser and starts to load the login page of Facebook for example it doesn't show the loading url location at the bottom.
I tried to add "location=yes" in the Oauth plugin like this, but it is still not showing the url loading bar at the bottom:
window.open('https://www.website.com/oauth/authorize?client_id=' + clientId + '&redirect_uri=http://localhost/callback&scope=' + appScope.join(",") + '&response_type=code&approval_prompt=force', '_blank', 'location=yes,clearsessioncache=yes,clearcache=yes');
How can I force to show the loading bar with Oauth in the InAppBrowser ?
The reason I want this is when a login page needs some time to load there is no loading indication and you mind think there is nothing happening.
This is how the Oauth function looks like with location=yes:
strava: function(clientId, clientSecret, appScope) {
var deferred = $q.defer();
if(window.cordova) {
var cordovaMetadata = cordova.require("cordova/plugin_list").metadata;
if(cordovaMetadata.hasOwnProperty("cordova-plugin-inappbrowser") === true || cordovaMetadata.hasOwnProperty("org.apache.cordova.inappbrowser") === true) {
var browserRef = window.open('https://www.strava.com/oauth/authorize?client_id=' + clientId + '&redirect_uri=http://localhost/callback&scope=' + appScope.join(",") + '&response_type=code&approval_prompt=force', '_blank', 'location=yes,clearsessioncache=yes,clearcache=yes');
browserRef.addEventListener('loadstart', function(event) {
if((event.url).indexOf("http://localhost") === 0) {
requestToken = (event.url).split("code=")[1];
$http.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
$http({method: "post", url: "https://www.strava.com/oauth/token", data: "client_id=" + clientId + "&client_secret=" + clientSecret + "&code=" + requestToken })
.success(function(data) {
deferred.resolve(data);
})
.error(function(data, status) {
deferred.reject("Problem authenticating");
})
.finally(function() {
setTimeout(function() {
browserRef.close();
}, 10);
});
}
});
browserRef.addEventListener('exit', function(event) {
deferred.reject("The sign in flow was canceled");
});
} else {
deferred.reject("Could not find InAppBrowser plugin");
}
} else {
deferred.reject("Cannot authenticate via a web browser");
}
return deferred.promise;
},
I found the solution.
My app was loading the oauth plugin twice, once via a separate oauth script I added to my project and once via the ngCordova library. The ngCordova script was overruling the oauth script I added so that's why the location=yes was not working.
I removed the separate oauth script and changed location=no to yes in the ngCordova oauth script.

How to save the google login as an app user?

So I have some code that authenticates the user to my app using google which works out fine. What I want to do is then save that user info to the firebase and then have that user be able add data specifically under their account that will then reload the next time they log in. What's the best way to do that? I'm getting very lost.
(function() {
'use strict';
angular.module('life-of-a-story')
.controller('UserController', function($scope, $firebaseAuth) {
var ref = new Firebase('https://life-of-a-story.firebaseio.com/');
// create an instance of the authentication service
var auth = $firebaseAuth(ref);
// login with Google
this.login = function() {
auth.$authWithOAuthPopup("google").then(function(authData) {
console.log(authData);
console.log("Logged in as:", authData.uid);
var user = {
'name': authData.google.displayName,
'image': authData.google.profileImageURL,
'uid': authData.uid
}
console.log(user);
}).catch(function(error) {
console.log("Authentication failed:", error);
});
};
});
})();
AngularFire is a (relatively) thin UI binding library on top of Firebase's regular JavaScript SDK. So when something is not explicitly documented in the AngularFire documentation, you can sometimes find the answer in the documentation for the regular Firebase JavaScript SDK.
Most Firebase Authentication developers store each user's data under a /users node. If that is what you're trying to do, you can read how to accomplish it in the section called Storing user data in the Firebase documentation for JavaScript.
The relevant code from there:
// we would probably save a profile when we register new users on our site
// we could also read the profile to see if it's null
// here we will just simulate this with an isNewUser boolean
var isNewUser = true;
var ref = new Firebase("https://<YOUR-FIREBASE-APP>.firebaseio.com");
ref.onAuth(function(authData) {
if (authData && isNewUser) {
// save the user's profile into the database so we can list users,
// use them in Security and Firebase Rules, and show profiles
ref.child("users").child(authData.uid).set({
provider: authData.provider,
name: getName(authData)
});
}
});
// find a suitable name based on the meta info given by each provider
function getName(authData) {
switch(authData.provider) {
case 'password':
return authData.password.email.replace(/#.*/, '');
case 'twitter':
return authData.twitter.displayName;
case 'facebook':
return authData.facebook.displayName;
}
}

"Sign-in with facebook" code in Sencha ! to integrate in apps

I am creating an app using Sencha and I need to integrate the facebook login in it . When i click on the "login in with facebook " button , if the user is not logged in facebook ,it should show a pop-up to enter facebook email-id and password, else if the user has already logged in it should just sign-in with facebook authentication. How do I implement this using sencha touch . Please help . It would be helpful if the code for this functionality is provided.Thanks
First of all, you have to create JavaScript SDK app with facebook (please follow this link). After the app is created you will have APP ID. Then add the following code to app.js
Ext.application({
name: 'FBLogin',
launch: function() {
Ext.create('Ext.container.Viewport', {
items:[
{
xtype: 'panel',
html: '<center><div id="fblogin" class="fb-login-button">Login with Facebook</div></center>'
}
],
listeners:{
render: function(obj, eOpts){
window.fbAsyncInit = Ext.bind(this.onFacebookInit, this);
(function(d){
var js, id = 'facebook-jssdk', ref = d.getElementsByTagName('script')[0];
if (d.getElementById(id)) {return;}
js = d.createElement('script'); js.id = id; js.async = true;
js.src = "//connect.facebook.net/en_US/all.js";
ref.parentNode.insertBefore(js, ref);
}(document));
}
},
onFacebookInit: function(){
console.log('onFacebookInit');
var me = this;
FB.init({
appId : 'YOUR_APP_ID',
status : true,
xfbml : true
});
FB.Event.subscribe('auth.authResponseChange', Ext.bind(me.onFacebookAuthResponseChange, me));
},
onFacebookAuthResponseChange: function(response){
this.down('panel').setVisible(false);
alert("Success fully Logged in");
}
});
}
});
There will be a field called 'SiteURL:' under Website with facebook Login when you create Facebook APP. That should be pointed to your web app URL. (ex: http://example.com)
You could try using Phonegap Facebook Connect Plugin 0.4.0 (stable version)
and Use Phonegap Plugin Build to build package for Android,Iphone ,windows phone,blackbery,etc.
//on Device Ready
FB.init({ appId: "appid", nativeInterface: CDV.FB, useCachedDialogs: false });
// call for native app if there else give a popup for login
FB.login(
function(response) {
if (response.session) {
alert('logged in');
} else {
alert('not logged in');
}
},
{ scope: "email" }
);
Inorder to integrate with sencha which needs to add three script files cdv-plugin-fb-connect.js, phonegap.js and facebook-js-sdk.js in index.html file and add config.xml file to project build for phone gap build for building native app(without using the sencha native packaging).For config.xml file configuration please see this config Help
If any doubt please see github example here
Hope it works

Resources