Authenticating the Ionic app with a backend server - angularjs

I try to create with angularjs based Ionic app an authentication mechanism. The system looks like this:
mobile users are created by administrators on the backend server. The created mobile user can login into the app.
I get an Example and implemented it for my app.
constants.js
angular.module('starter')
.constant('AUTH_EVENTS', {
notAuthenticated: 'auth-not-authenticated',
notAuthorized: 'auth-not-authorized'
})
.constant('USER_ROLES', {
admin: 'admin_role',
public: 'public_role'
});
dashController.js
myApp.controller('DashCtrl', function ($scope, $state, $http, $ionicPopup, AuthService, $location, $window) {
$scope.logout = function () {
AuthService.logout();
$window.location.href = '/index.html';
};
$scope.performValidRequest = function () {
$http.get('http://localhost:8100/valid').then(
function (result) {
$scope.response = result;
});
};
$scope.performUnauthorizedRequest = function () {
$http.get('http://localhost:8100/notauthorized').then(
function (result) {
// No result here..
}, function (err) {
$scope.response = err;
});
};
$scope.performInvalidRequest = function () {
$http.get('http://localhost:8100/notauthenticated').then(
function (result) {
// No result here..
}, function (err) {
$scope.response = err;
});
};
});
loginAppController.js
myApp.controller('LoginAppCtrl', function ($scope, $state, $ionicPopup, AuthService, AUTH_EVENTS, $location, $window) {
$scope.username = AuthService.username();
$scope.$on(AUTH_EVENTS.notAuthorized, function (event) {
var alertPopup = $ionicPopup.alert({
title: 'Unauthorized!',
template: 'You are not allowed to access this resource.'
});
});
$scope.$on(AUTH_EVENTS.notAuthenticated, function (event) {
AuthService.logout();
$window.location.href = '/loginPage.html';
var alertPopup = $ionicPopup.alert({
title: 'Session Lost!',
template: 'Sorry, You have to login again.'
});
});
$scope.setCurrentUsername = function (name) {
$scope.username = name;
};
})
loginController.js
myApp.controller('LoginCtrl', function ($scope, $state, $ionicPopup, AuthService, $location, $window) {
$scope.data = {};
$scope.login = function (data) {
AuthService.login(data.username, data.password).then(function (authenticated) {
$window.location.href = '/index.html';
$scope.setCurrentUsername(data.username);
}, function (err) {
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
};
})
loginService.js
angular.module('starter')
myApp.service('AuthService', function ($q, $http, USER_ROLES) {
var LOCAL_TOKEN_KEY = 'yourTokenKey';
var username = '';
var isAuthenticated = false;
var role = '';
var authToken;
function loadUserCredentials() {
var token = window.localStorage.getItem(LOCAL_TOKEN_KEY);
if (token) {
useCredentials(token);
}
}
function storeUserCredentials(token) {
window.localStorage.setItem(LOCAL_TOKEN_KEY, token);
useCredentials(token);
}
function useCredentials(token) {
username = token.split('.')[0];
isAuthenticated = true;
authToken = token;
if (username == 'admin') {
role = USER_ROLES.admin
}
if (username == 'user') {
role = USER_ROLES.public
}
// Set the token as header for your requests!
$http.defaults.headers.common['X-Auth-Token'] = token;
}
function destroyUserCredentials() {
authToken = undefined;
username = '';
isAuthenticated = false;
$http.defaults.headers.common['X-Auth-Token'] = undefined;
window.localStorage.removeItem(LOCAL_TOKEN_KEY);
}
var login = function (name, pw) {
return $q(function (resolve, reject) {
if ((name == 'admin' && pw == '1') || (name == 'user' && pw == '1')) {
// Make a request and receive your auth token from your server
storeUserCredentials(name + '.yourServerToken');
resolve('Login success.');
} else {
reject('Login Failed.');
}
});
};
var logout = function () {
destroyUserCredentials();
};
var isAuthorized = function (authorizedRoles) {
if (!angular.isArray(authorizedRoles)) {
authorizedRoles = [authorizedRoles];
}
return (isAuthenticated && authorizedRoles.indexOf(role) !== -1);
};
loadUserCredentials();
return {
login: login,
logout: logout,
isAuthorized: isAuthorized,
isAuthenticated: function () {
return isAuthenticated;
},
username: function () {
return username;
},
role: function () {
return role;
}
};
})
app.js
var myApp = angular.module('starter', ['ionic', 'ngMockE2E'])
.run(function($ionicPlatform, $ionicPopup) {
$ionicPlatform.ready(function() {
// Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
// for form inputs)
if (window.cordova && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
}
if (window.StatusBar) {
StatusBar.styleDefault();
}
});
})
.run(function($httpBackend) {
$httpBackend.whenGET('http://localhost:8100/valid')
.respond({message: 'This is my valid response!'});
$httpBackend.whenGET('http://localhost:8100/notauthenticated')
.respond(401, {message: "Not Authenticated"});
$httpBackend.whenGET('http://localhost:8100/notauthorized')
.respond(403, {message: "Not Authorized"});
$httpBackend.whenGET(/.*/).passThrough();
})
.run(function ($rootScope, $state, AuthService, AUTH_EVENTS, $location, $window) {
$rootScope.$on('$stateChangeStart', function (event,next, nextParams, fromState) {
if ('data' in next && 'authorizedRoles' in next.data) {
var authorizedRoles = next.data.authorizedRoles;
if (!AuthService.isAuthorized(authorizedRoles)) {
event.preventDefault();
$state.go($state.current, {}, {reload: true});
$rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
}
}
if (!AuthService.isAuthenticated()) {
if (next.name !== 'login') {
event.preventDefault();
$window.location.href = '/loginPage.html';
}
}
});
})
HTML:
<ion-content style="text-align: left" ng-controller="LoginCtrl">
<span class="item item-input item-stacked-label"
style="font-weight: bold">Name and password:</span>
<label class="item item-input">
<span class="input-label">Name:</span>
<input name="name" placeholder="Name!" autofocus="true" required="true"
type="text"
ng-model="data.username"/>
</label>
<label class="item item-input">
<span class="input-label">Password:</span>
<input name="password" placeholder="Password!" required="true" type="password"
ng-model="data.password"/>
</label>
<button id="button-1" class="button button-block button-positive" ng-click="login(data)">Login</button>
</ion-content>
In a related article I get these steps as an answer:
1) Send username password to server using $http.post();
2) Server authenticates the credentials. and returns a token in return
is credentials are correct.
3) App stores this token locally and passes it to server for later
request as a mean of identification of logged in user.
Ideally you should implement SOAP or REST based services on your
server and consume those services in your app.
The example works localy. But where should change, so that I can authenticate with a user and password which stored on the backen server?

Related

how do you do a remember me or a stay signed in function with AngualarFire?

or using normal email and password method so that everytime i open the app i dont have to sign in. just go through..
.controller('signupCtrl', function(taskref, $scope, $firebaseArray, $state, $firebaseAuth) {
var fbref = $firebaseAuth(taskref);
$scope.createUser = function() {
taskref.$createUser({
email: $scope.email,
password: $scope.password
})
.then(function(authData) {
$state.go('settings');
};
})
with this sign in function with either googleAuth or email&password methods
.controller('googleSignUpCtrl', function(taskref, $scope, $firebaseObject, $firebaseAuth, $state) {
$scope.googleSignIn = function() {
var authData = taskref.getAuth();
taskref.authWithOAuthPopup("google", function(error, authData) {
if (error) {
console.log("Login Failed!", error);
} else {
taskref.child("users").child(authData.uid).once("value", function(snapshot) {
var ifExists = snapshot.exists();
if (ifExists) {
$state.go('tabsController.pendingTasks');
console.log("user already exists");
} else {
$state.go('settings');
$scope.authData = authData;
}
});
}
}, {
remember: "sessionOnly",
scope: "email"
});
}
})

authentication mechanism in angularjs

i am newbie in AngularJS, i have read a tutorial about login and authentication with angular js but i still confused in many points of my code, for now i have arrived to login and to store a token in browser's session, but i can't redirect to home page after loggin in,
here is myservice :
function authenticationSvc ($http, $q, $window, auth_uri) {
var userInfo;
function login(username, password) {
var deferred = $q.defer();
$http.post(auth_uri, {
username: username,
password: password
}).then(function(result) {
userInfo = {
accessToken: result.data.token
};
$window.sessionStorage["pallas_token"] = result.data.token;
deferred.resolve(userInfo);
},
function(error) {
deferred.reject(error);
});
return deferred.promise;
}
function getUserInfo() {
return userInfo;
}
return {
login: login,
getUserInfo: getUserInfo
};
};
and this is my state config
.state('dashboard', {
url:'/dashboard',
controller: 'HomeController',
templateUrl: 'partials/dashboard/main.html',
resolve:{
auth: function($q, authenticationSvc) {
var userInfo = authenticationSvc.getUserInfo();
if (userInfo) {
return $q.when(userInfo);
} else {
return $q.reject({ authenticated: false });
}
}
}
}
finally this my .run block:
angular
.module ( 'mainApp' )
.run ( function ( $rootScope, $state, $location) {
$rootScope.$on('$stateChangeSuccess', function( userInfo) {
console.log( userInfo );
});
$rootScope.$on('$stateChangeError', function(evt, toState, toParams, fromState, fromParams, error) {
if (error.authenticated == false) {
$state.transitionTo("login");
}
});
});
please help me to resolve this issue, i need help my friends :(
i am sorry for missing to post my login controller, there is:
function LoginController($scope, $state, authenticationSvc){
$scope.submit = function(credentials){
authenticationSvc.login(credentials.username, credentials.password);
};
};
Your login method return a success promise when the user pass the authentication. So.. you can edit your controller in this way:
function LoginController($scope, $state, authenticationSvc){
$scope.submit = function(credentials){
authenticationSvc.login(credentials.username, credentials.password).then(function(){
$state.go('dashboard');
console.log('User logged in!');
}).catch(function(){
console.log('User NOT logged in!');
});
};
};
UPDATE
To maintain the state after a page refresh you need to restore the userInfo object from sessionStorage. I also added the logout logic! Take a look:
function authenticationSvc ($http, $q, $window, auth_uri) {
var userInfo;
function login(username, password) {
...
}
function logout() {
$window.sessionStorage.removeItem("pallas_token");
userInfo = null;
}
function getUserInfo() {
return userInfo;
}
function init(){
if ($window.sessionStorage["pallas_token"]){
userInfo = {
accessToken: $window.sessionStorage["pallas_token"]
};
}
}
init();
return {
login: login,
logout: logout,
getUserInfo: getUserInfo
};
};
Logout:
function LoginController($scope, $state, authenticationSvc){
$scope.submit = function(credentials){
...
};
$scope.logout = function(){
authenticationSvc.logout();
$state.go('login');
console.log('User logged out!');
};
};
Enjoy!

How to use $q service in angular js for login?

I am new in angular js. i have making ionic app useing angular js and ionic framework,
This is my service.js file.
In this i have create LoginService for Login control. but its not working.
angular.module('starter.services', ['ngCookies'])
.service('LoginService', function ($q, $http, $cookies, $rootScope) {
return {
loginUser: function (name, pw) {
var deferred = $q.defer();
var promise = deferred.promise;
var user_data = $http.get("http://vanhalterenwatersport.nl/van/webservice/appc/login.php");
user_data.then(function (result) {
var user = result.data;
log(user);
console.log($rootScope.session);
})
function log(user) {
var i;
var isloggedin = false;
for (i = 0; i < user.length; i++) {
if (name == user[i].user_email && pw == user[i].password) {
isloggedin = true;
id = user[i].iduser;
$rootScope.session = id;
break;
}
}
if (isloggedin) {
deferred.resolve('Welcome ' + name + '!');
} else {
deferred.reject('Wrong credentials.');
}
}
promise.success = function (fn) {
promise.then(fn);
return promise;
}
promise.error = function (fn) {
promise.then(null, fn);
return promise;
}
return promise;
}
}
})
This is my controllers.js file
angular.module('starter.controllers', ['ngRoute','ngCookies'])
.controller('AppCtrl', function($scope, $ionicModal, $timeout) {
// With the new view caching in Ionic, Controllers are only called
// when they are recreated or on app start, instead of every page change.
// To listen for when this page is active (for example, to refresh data),
// listen for the $ionicView.enter event:
//$scope.$on('$ionicView.enter', function(e) {
//});
})
.controller('LoginCtrl', function($scope, LoginService, $ionicPopup, $state, $cookies, $rootScope) {
$scope.data = {};
$scope.create = function () {
$state.go('signup');
}
$scope.forgot = function () {
$state.go('forgotpassword');
}
$scope.login = function () {
console.log($scope.data.user_email);
LoginService.loginUser($scope.data.user_email, $scope.data.password).success(function (data) {
var wat = $rootScope.session;
console.log(wat);
$state.go('app.dashboard');
}).error(function (data) {
var alertPopup = $ionicPopup.alert({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
})
This is my login.html
<ion-view view-title="Login" hide-nav-bar="true" name="login-view">
<ion-content ng-controller="LoginCtrl">
<div class="bar-header padding">
<h1 class="title vanimage"><img src='img/logo.png'></h1>
</div>
<div class="list">
<label class="item item-input">
<span class="input-label">Username</span>
<input type="text" name="username" ng-model="data.user_email">
</label>
<label class="item item-input">
<span class="input-label">Password</span>
<input type="password" name="password" ng-model="data.password">
</label>
<label class="item">
<button class="button button-block button-positive" ng-click="login()">Log in</button>
</label>
</div>
<div class="padding">
<button class="button button-block button-positive" ng-click="create()">Registeer hier</button>
<button class="button button-block button-positive" ng-click="forgot()">Password Vergeten?</button>
</div>
</ion-content>
</ion-view>
You should put the auth logic in the backend, more secure and efficent.
This is the code I use for login in a service of a Ionic app:
login: function( loginEmail, loginPassword ) {
var deferred = $q.defer();
$http({
method: 'POST',
url: backend_url + '/auth',
// --- change content-type if needed (default = application/json)
// headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
data: { email: loginEmail, password: loginPassword }
}).then( function( result ) {
if( typeof result.data.token !== 'undefined' ) deferred.resolve( { token: result.data.token } );
else deferred.reject( { error: 'invalid_response' } );
}, function( result ) {
if( typeof result.data.error !== 'undefined' ) deferred.reject( { error: result.data.error, status: result.status } );
else deferred.reject( { error: 'invalid_login' } );
});
return deferred.promise;
},
$http always return a promice, so if you want to do it correctly in your service, using $q try smth like this:
var fn = function (method, url) {
var deferred = $q.defer();
$http(method, url)
.success(function (data) {
deferred.resolve(data);
}
.error(function (data, status) {
deferred.reject({
data: data,
status: status
});
});
return deferred.promise;
}
And if you want to call this function you should do
fn(method, url)
.then(
function(result){
... do if ok (resolve)
},
function( error) {
... do if error (reject)
}
)
You forgot to return the deferred object in your service..
This probably results in the following error:
Cannot read property then of undefined
I've made a basic example to demonstrate the $q service:
Controller - Login function
$scope.login = function login() {
LoginService.loginuser($scope.data.user_email, $scope.data.password)
.then(function onLoginSuccess(response) {
// response should contain 'success' data
$state.go('app.dashboard');
}, function onLoginFailed(error) {
var alertPopup = $ionicPopup.aler({
title: 'Login failed!',
template: 'Please check your credentials!'
});
});
}
Service
var API = {};
function loginUser(email, password) {
var deferred = $q.defer();
$http.get("http://vanhalterenwatersport.nl/van/webservice/appc/login.php")
.then(function onUserLoggedIn(response) {
deferred.resolve(response);
}, function onLoginFailed(error) {
deffered.reject(error);
});
// Make sure to return your promise!
return deferred.promise;
}
API.loginUser = loginUser;
Sidenote: You're also using GET in your login function. For this type of operations, you would typically POST a data-object to your back-end which on his turn will return you a result.

Unable to minify JS

Before implementing Firebase authentication this JS file successfully minifyed without any problems.
The file works without any problems when using the none-midifyed version, I'm unable to test the minifyed version as Atom will not allow me to minify and save due to the following error (See attached)!
I'm using and following Scotch.io's advice: https://scotch.io/tutorials/declaring-angularjs-modules-for-minification
Any pointers/advice would be great!
Error
Controller JS
var fbcontrollers = angular.module('fbcontrollers', []);
fbcontrollers.controller('authCtrl', ['$scope', 'Auth', '$location', function($scope, Auth, $location) {
$scope.auth = Auth;
$scope.user = $scope.auth.$getAuth();
// Store User Data
function userData() {
var isNewUser = true;
var fire = new Firebase('https://courtyard-bridal.firebaseio.com/');
fire.onAuth(function(authData) {
if (authData && isNewUser) {
fire.child("users").child(authData.uid).set({
name: getName(authData),
email: getEmail(authData),
provider: authData.provider
});
}
function getName(authData) {
switch (authData.provider) {
case 'password':
return authData.password.email.replace(/#.*/, '');
case 'facebook':
return authData.facebook.displayName;
}
}
function getEmail(authData) {
switch (authData.provider) {
case 'password':
return authData.password.email;
case 'facebook':
return authData.facebook.email;
}
}
});
}
// Facebook Login
$scope.fblogin = function() {
var scope = {
scope: 'email'
};
$scope.auth.$authWithOAuthPopup('facebook', scope).then(function(auth) {
// Store Data
userData();
// Redirtect on Success
$location.path('/dash');
}).catch(function(error) {
console.log('error');
});
};
// Default Form Data
$scope.form = ({
'email': '',
'password': ''
});
// Login Form
$scope.login = function() {
var email = $scope.form.email;
var password = $scope.form.password;
$scope.authData = null;
$scope.auth.$authWithPassword({
email: email,
password: password
}).then(function(Auth) {
$scope.authData = Auth;
$location.path('/dash');
}).catch(function(error) {
console.log(error);
});
};
// Register (Create User) Form
$scope.register = function() {
var email = $scope.form.email;
var password = $scope.form.password;
// Create User
$scope.auth.$createUser({
email: email,
password: password
}).then(function(Auth) {
// Store Data
userData();
// Login Created User
$scope.authData = null;
$scope.auth.$authWithPassword({
email: email,
password: password
}).then(function(Auth) {
$scope.authData = Auth;
$location.path('/dash');
}).catch(function(error) {
console.log('error');
});
}).catch(function(error) {
console.log(error);
});
};
}]);
fbcontrollers.controller('dashCtrl', ['$scope', 'Auth', '$location', function($scope, Auth, $location) {
$scope.auth = Auth;
$scope.user = $scope.auth.$getAuth();
if($scope.user.provider === 'facebook') {
$scope.id = $scope.user.uid;
$scope.name = $scope.user.facebook.displayName;
$scope.email = $scope.user.facebook.email;
$scope.profile = $scope.user.facebook.profileImageURL;
} else if ($scope.user.provider === 'password') {
$scope.id = $scope.user.uid;
$scope.name = $scope.user.password.email.replace(/#.*/, '');
$scope.email = $scope.user.password.email;
$scope.profile = $scope.user.password.profileImageURL;
}
console.log($scope.user);
// Logout
$scope.logout = function() {
$scope.auth.$unauth();
$location.path('/auth');
};
}]);
I am pretty sure the problem is connected with the use of catch. Note that catch is a keyword in javascript, used in exception (error) handling. Promises use catch as a method name and that's a bit of a collision. In general it's safer to use it indirectly:
}).then(function(...) {
...
})['catch'](function(error) {
...
});
The same applies to the finally keyword.

Making promises in modules

I try to make facebook registration module in my app. Facebook API is faster than my Angular controller, so promise should be used here. The problem is that $q seems to be an empty object and defer function is undefined.
module:
var module = angular.module('app.facebook', []);
module.constant("fbAppId", 'herecomesmycode');
module.factory('facebook', FacebookAPI);
FacebookAPI.$inject = ['$ionicLoading', '$q', '$ionicPlatform', '$state', 'authService', 'datacontext', '$location'];
function FacebookAPI(UserService, $q, $ionicLoading, fbAppId, $state, authService, datacontext, $location) {
return {
fbLoginSuccess: fbLoginSuccess,
fbLoginError: fbLoginError,
getFacebookProfileInfo: getFacebookProfileInfo,
fbLogin: fbLogin,
fbRegister: fbRegister
};
and here $q.defer is undefined:
function fbRegister() {
console.log($q.defer);
if (!cordova) {
facebookConnectPlugin.browserInit(fbAppId);
}
var data;
facebookConnectPlugin.getLoginStatus(function (response) {
if (response.status !== 'connected') {
facebookConnectPlugin.login(["email"],
function(response) {
data = getApiData();
},
function(response) {
});
} else {
data = getApiData();
}
});
}
Without using promise, it gets fast from API but all variables I want to fill with values from API, are initiated before API finishes and are undefined.
The whole module:
(function() {
'use strict';
var module = angular.module('app.facebook', []);
module.constant("fbAppId", 'myappkey');
module.factory('facebook', FacebookAPI);
FacebookAPI.$inject = ['$ionicLoading', '$ionicPlatform', '$state', 'authService', '$q'];
function FacebookAPI(UserService, $ionicLoading, fbAppId, $state, authService, $q) {
return {
fbLoginSuccess: fbLoginSuccess,
fbLoginError: fbLoginError,
getFacebookProfileInfo: getFacebookProfileInfo,
fbLogin: fbLogin,
fbRegister: fbRegister
}
function fbRegister() {
console.log($q);
if (!cordova) {
facebookConnectPlugin.browserInit(fbAppId);
}
var data;
facebookConnectPlugin.getLoginStatus(function (response) {
if (response.status !== 'connected') {
facebookConnectPlugin.login(["email"],
function(response) {
data = getApiData();
},
function(response) {
});
} else {
data = getApiData();
}
});
}
function getApiData() {
var formData = {};
facebookConnectPlugin.api("me/?fields=id,first_name,last_name,link,gender,email,birthday", ["public_profile", "email", "user_birthday"],
function (result) {
if (result.gender == "male") {
result.gender = '1';
} else {
result.gender = '2';
}
formData = {
name: result.first_name + " " + result.last_name,
email: result.email,
birthday: new Date(result.birthday),
gender: result.gender
}
console.log("moduĊ‚" + formData);//here we have nice and neat data
return formData;
}, function(res) {
});
}
};
//This is the success callback from the login method
function fbLoginSuccess(response) {
var fbLogged = $q.defer();
if (!response.authResponse) {
fbLoginError("Cannot find the authResponse");
return;
}
var expDate = new Date(
new Date().getTime() + response.authResponse.expiresIn * 1000
).toISOString();
var authData = {
id: String(response.authResponse.userID),
access_token: response.authResponse.accessToken,
expiration_date: expDate
}
authService.facebookLogin(response.authResponse.accessToken).then(function() {
fbLogged.resolve(authData);
});
};
//This is the fail callback from the login method
function fbLoginError(error) {
var fbLogged = $q.defer();
fbLogged.reject(error);
alert(error);
$ionicLoading.hide();
};
//this method is to get the user profile info from the facebook api
function getFacebookProfileInfo() {
var info = $q.defer();
facebookConnectPlugin.api('/me', "",
function(response) {
info.resolve(response);
},
function(response) {
info.reject(response);
}
);
return info.promise;
}
//This method is executed when the user press the "Login with facebook" button
function fbLogin() {
if (!cordova) {
//this is for browser only
facebookConnectPlugin.browserInit(fbAppId);
}
//check if we have user's data stored
var user = UserService.getUser();
facebookConnectPlugin.getLoginStatus(function(success) {
//alert(JSON.stringify(success, null, 3));
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
facebookConnectPlugin.api("me/?fields=id,first_name,last_name,link,gender,email", ["public_profile", "email"],
function(result) {
//alert("Result: " + JSON.stringify(result));
//alert(result.first_name);
})
var accessToken = success.authResponse.accessToken;
authService.facebookLogin(accessToken).then(function() {
$state.go('app.map');
}, function(err) { alert('auth failed: ' + JSON.stringify(err, null, 2)); });
} 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.
$ionicLoading.show({
template: 'Loging in...'
});
// permissions from facebook
facebookConnectPlugin.login([
'email',
'public_profile',
'user_about_me',
'user_likes',
'user_location',
'read_stream',
'user_photos'
], fbLoginSuccess, fbLoginError);
fbLogged.promise.then(function(authData) {
var fb_uid = authData.id,
fb_access_token = authData.access_token;
//get user info from FB
getFacebookProfileInfo().then(function(data) {
var user = data;
user.picture = "http://graph.facebook.com/" + fb_uid + "/picture?type=large";
user.access_token = fb_access_token;
//save the user data
//store it on local storage but it should be save it on a database
UserService.setUser(user);
$ionicLoading.hide();
$state.go('app.map');
});
});
}
});
}
})();

Resources