Adding google plus login to ionic app - angularjs

I am trying to add google plus login to my ionic app.
Following this link gives me an error.
https://ionicthemes.com/tutorials/about/google-plus-login-with-ionic-framework
Error is : cannot read property googleplus of undefined.
Here is my app.js:
.run(function($ionicPlatform) {
$ionicPlatform.ready(function() {
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})

Steps to Configure authentication in Device(android)
ionic start newApp
ionic platform add android
cordova plugin add cordova-plugin-inappbrowser
bower install ngCordova
bower install ng-cordova-oauth -S
include both script into index.html above cordova.js
<script src="lib/ngCordova/dist/ng-cordova.min.js"></script>
<script src="lib/ng-cordova-oauth/dist/ng-cordova-oauth.js"></script>
<script src="cordova.js"></script>
Dependency injection
include below code
$scope.googleLogin = function() {
console.log('In My Method');
$cordovaOauth.google("Client ID", ["https://www.googleapis.com/auth/urlshortener", "https://www.googleapis.com/auth/userinfo.email"]).then(function(result) {
console.log(JSON.stringify(result));
// results
}, function(error) {
// error
console.log('In Error');
console.log(error);
});
}
add button to view file and call the function

1 first add inappbrower in your app
2 create app id for google console
https://console.developers.google.com
a: create new project
b: click on Credentials
c: choose web application
d: set redirect path
if u have if not than set http://localhost/callback
e: click on create button
than a pop up appear save those id
after that add following code
NOTE:Please change your app id and secret id in code
$scope.loginGoogle = function() {
var requestToken = '';
var accessToken = '';
var clientId = '1018908884240-futc1bfc681kl2jegi3a7nn1m28aem1o.apps.googleusercontent.com';
var clientSecret = 'KRQGDwu_llvagUucKM9oLZ7I';
var deferred = $q.defer();
$cordovaOauth.google(clientId, ['email']).then(function(result) {
$localStorage.accessToken = result.access_token;
deferred.resolve(result.access_token);
$http.get('https://www.googleapis.com/oauth2/v1/userinfo?alt=json&access_token=' + $localStorage.accessToken, {
params: {
format: 'json'
}
}).then(function(result) {
console.log(JSON.stringify(result));
var id =result.data.id;
deferred.resolve(result.data);
}, function(error) {
deferred.reject({
message: 'here was a problem getting your profile',
response: error
});
});
}, function(error) {
deferred.reject({
message: 'There was a problem signing in',
response: error
});
});
}

Try to add <script src="cordova.js"></script> to your index.html file.
And Cordova plugins only runs on emulators or real devices. try Ripple Emulator if you want to test it in a browser.
Credit to Cordova plugins not working with ionic

Related

Can't get Dan Wilson's Google Analytics plugin to work

What i am doing wrong? What else is required? I have added the Android platform to my app which I am importing in Android Studio and launching the app. But I cannot see any change in the Analytics dashboard.
plugin :- cordova plugin add cordova-plugin-google-analytics [having cordova 5.0+]
app.js
$ionicPlatform.ready(function() {
document.addEventListener("deviceready", onDeviceReady, false);
function onDeviceReady() {
window.plugins.sim.getSimInfo(successCallback, errorCallback);
}
function successCallback(result) {
console.log(result);
}
function errorCallback(error) {
console.log(error);
}
// Android only: check permission
function hasReadPermission() {
window.plugins.sim.hasReadPermission(successCallback, errorCallback);
}
// Android only: request permission
function requestReadPermission() {
window.plugins.sim.requestReadPermission(successCallback, errorCallback);
}
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if(ionic.Platform.isWebView()){
var device_name = device.name,
device_version = device.version,
device_platform = device.platform;
if (typeof analytics !== "undefined") {
analytics.startTrackerWithId('UA-XXXXX-X'); // security purpose cannot give tracker_ID.
analytics.trackView('home');// tracking home page
analytics.trackView('partsearch'); //tracking part search page
analytics.trackView('aggregates');// tracking aggregate page
analytics.trackEvent("Affiliate", "Search");// check end of the code
console.log("Starting Analytics");
} else {
console.log("Google Analytics plugin could not be loaded.")
}
}
}
home.html
<div on-touch = "onTouchSearch()" style="text-align:center;height:105px;padding:5px;vertical-align:middle;" class="waves-effect waves-light no-margin" on-click="_gaq.push(['_trackEvent','Affiliate','Search']);">
//when search button is clicked on my app i want to see it in my google analytics dashboard

cordova-plugin-geolocation not working on Android device

I've implemented the cordova-plugin-geolocation plugin in my ionic/cordova app. It works perfectly when I run the app in my browser as well as on an iOS device. However when I try and run it on an Android device the map doesn't get displayed and it doesn't get your current GPS co-ordinates. After it times out it throws the following error:
[object PositionError]
First I added the plugin (as well as the cordova-plugin-whitelist plugin by running this is the cli:
cordova plugin add cordova-plugin-geolocation
cordova plugin add cordova-plugin-whitelist
I then added the following to my index.html:
<script src="//maps.googleapis.com/maps/api/js"></script>
<script src="lib/angular-google-maps/dist/angular-google-maps.min.js"></script>
I then modified my app.js to include 'uiGmapgoogle-maps':
var app = angular.module('myApp', ['ionic', 'ngCordova', 'uiGmapgoogle-maps']);
My HTML for the map:
<!-- Google map -->
<ui-gmap-google-map center='map.center' zoom='map.zoom'>
<ui-gmap-marker coords="marker.coords" options="marker.options" events="marker.events" idkey="marker.id" closeClick="hideMarkerPopup()" onClicked="showMarkerPopup()"></ui-gmap-marker>
</ui-gmap-google-map>
And finally the logic in my controller:
ionic.Platform.ready(function() {
var posOptions = {
enableHighAccuracy: true,
timeout: 20000,
maximumAge: 0
};
// Display 'loading' dialog
$ionicLoading.show({
template: 'Loading...'
});
$cordovaGeolocation.getCurrentPosition(posOptions).then(function(position) {
// Apply new values to map
$scope.location = {};
$scope.location.lat = position.coords.latitude;
$scope.location.long = position.coords.longitude;
$scope.map = {
center: {
latitude: $scope.location.lat,
longitude: $scope.location.long
},
zoom: 16,
pan: 1
};
$scope.marker = {
id: 0,
coords: {
latitude: $scope.location.lat,
longitude: $scope.location.long
}
};
$scope.marker.options = {
draggable: false
};
// Dismiss 'loading' dialog
$ionicLoading.hide();
}, function(err) {
// Dismiss 'please wait' dialog
$ionicLoading.hide();
var alertPopup = $ionicPopup.alert({
title: 'GPS Error',
template: err
});
});
}); // ionic.Platform.ready END
But, as I said. It works in the browser and iOS devices but not on Android devices.. Any help?
I could not let working geoLocation 100% good in all cases, so i use this external service, in case cordovaGeoLocation gives me an error:
/** i declare de external service */
$scope.getLocation = function (){
return $http.get("http://ip-api.com/json/" ,{
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json',
}
}).catch(function(error) {
console.log(error);
});
}
/** and then i use this */
$scope.getLocation().then(function (res){
var coords = {
Coordinates : {
latitude: res.data.lat
,longitude: res.data.lon
}
};
$scope.coords = coords.Coordinates;
}).catch(function (err){
console.log(err);
});
I encountered the exact same error and the solution is to add the following to the AndroidManifest.xml (Located inside Platforms -> Android)
<uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_FINE_LOCATION" />
<uses-permission android:name="android.permission.ACCESS_LOCATION_EXTRA_COMMANDS" />
Apparently, the plugin did not add permissions into the manifest.
I'm answering my own question because I see that this is an issue that lots of people run into and there's not that much info out there on how to fix it. I followed this tutorial: http://www.gajotres.net/using-cordova-geoloacation-api-with-google-maps-in-ionic-framework/ I think it came down to not only installing the whitelist plugin, but using the correct meta tag in your index.html (you can find the meta tag in the tutorial). Working perfectly not on Android devices.

'AWS is not defined' when using aws-sdk-js in angular

Following this tutorial, implementing the AWS sdk with angular, I'm getting AWS is not defined from jshint (using grunt to serve the app).
I've installed the sdk with bower install aws-sdk-js --save, and it correctly appears in my index.html file.
This is my controller:
angular.module('myApp')
.controller('S3uploadCtrl', function ($scope) {
console.log(AWS);
$scope.creds = {
bucket: 'myBucket',
accessKey: 'accKey',
secretKey: 'secKey'
};
$scope.upload = function() {
// Configure The S3 Object
AWS.config.update({ accessKeyId: $scope.creds.accessKey, secretAccessKey: $scope.creds.secretKey });
AWS.config.region = 'us-west-2';
var bucket = new AWS.S3({ params: { Bucket: $scope.creds.bucket } });
if($scope.file) {
var params = { Key: $scope.file.name, ContentType: $scope.file.type, Body: $scope.file, ServerSideEncryption: 'AES256' };
bucket.putObject(params, function(err, data) {
if(err) {
// There Was An Error With Your S3 Config
alert(err.message);
return false;
}
else {
// Success!
alert('Upload Done');
}
})
.on('httpUploadProgress',function(progress) {
// Log Progress Information
console.log(Math.round(progress.loaded / progress.total * 100) + '% done');
});
}
else {
// No File Selected
alert('No File Selected');
}
};
function alert(msg) {
console.alert(msg);
}
});
There isn't much about this on google. I found one other SO question which I've tried to follow to no avail. (changed the order of my <script> tags etc.)
It's a JSHint error. JSHint makes sure you're accessing defined variables, and has no idea that an AWS global variable exists et runtime. So you need to tell JSHint that this globa variable exists and that you allow your code to access this global variable (although you probably should hide it behind an angular service, to make your code testable).
Edit your .jshintrc file (it might have another name: check your build configuration), and add (or modify) the following rule:
"globals": { "AWS" : false }
If you are just getting a JSHint error, it might be because AWS is not recognised as a variable. Create a .jshintrc file in the root of your project, and put this config in it:
"globals": {
"AWS": false
}
'AWS is not defined' this error occurs when you forgot to define js ,
After "bower install aws-sdk-js"
you need to define "aws-sdk.min.js" and "aws-sdk.js" to your index.html in script tag like
<script src="bower_components/aws-sdk/dist/aws-sdk.min.js"></script>
<script src="bower_components/aws-sdk/dist/aws-sdk.js"></script>

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.

Facebook login on mobile via Cordova/Angular/Ionic

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.

Resources