My ionic 1 project currently has firebase authentication which lets the user log in with an email and password and redirects the user to view that can only be accessed when the user is logged in.
I want to load google maps on the logged in view. I have successfully been able to load google maps on another view that does not firebase authentication in its controller but the minute I put the same code in the controller of the logged in view and setup the div with on the logged in view then it does not load up. There have been no errors in console so im not quite sure what is going on.
So code is as followed:
AuthService calls the firebase service
MuserController (Controller of logged in view):
.controller('MuserCtrl', function($scope, $timeout, $stateParams, ionicMaterialInk, ionicMaterialMotion, $state, AuthService, $cordovaGeolocation) {
$scope.$parent.clearFabs();
$timeout(function() {
$scope.$parent.hideHeader();
}, 0);
ionicMaterialInk.displayEffect();
$scope.current_user = {};
var current_user = AuthService.getUser();
//if user is already logged in
if(current_user) {
//If facebook login
if (current_user && current_user.provider == "facebook") {
$scope.current_user.email = current_user.facebook.displayName;
$scope.current_user.image = current_user.facebook.profileImageURL;
}
//If email login
else {
/*Google Map setting*/
var options = {timeout: 10000, enableHighAccuracy: true};
$cordovaGeolocation.getCurrentPosition(options).then(function(position){
var latLng = new google.maps.LatLng(position.coords.latitude, position.coords.longitude);
var mapOptions = {
center: latLng,
zoom: 15,
mapTypeId: google.maps.MapTypeId.ROADMAP
};
$scope.map = new google.maps.Map(document.getElementById("map"), mapOptions);
}, function(error){
console.log("Could not get location");
});
$scope.current_user.email = current_user.password.email;
$scope.current_user.image = current_user.password.profileImageURL;
}
//No user is currently logged in
} else {
$state.go('app.start');
}
//Logout Function
$scope.logout = function(){
AuthService.doLogout();
$state.go('app.start');
};
})
Services.js (Firebase Authentication Service):
angular.module('socialAuth',[])
.service('AuthService', function($q){
var _firebase = new Firebase("https://logfirebase.firebaseio.com/");
// var _firebase = new Firebase("https://geomuse-169214.firebaseio.com");
// var config = {
// apiKey: "AIzaSyBwdvuilAWOU9DttaGPabpKsHIDHJOuF1Q",
// authDomain: "geomuse-169214.firebaseapp.com",
// databaseURL: "https://geomuse-169214.firebaseio.com",
// projectId: "geomuse-169214",
// storageBucket: "geomuse-169214.appspot.com",
// messagingSenderId: "103764525324"
// };
// firebase.initializeApp(config);
// var rootRef = firebase.database().ref();
this.userIsLoggedIn = function(){
var deferred = $q.defer(),
authService = this,
isLoggedIn = (authService.getUser() !== null);
deferred.resolve(isLoggedIn);
return deferred.promise;
};
this.getUser = function(){
return _firebase.getAuth();
};
this.doLogin = function(user){
var deferred = $q.defer();
_firebase.authWithPassword({
email : user.email,
password : user.password
}, function(errors, data) {
if (errors) {
var errors_list = [],
error = {
code: errors.code,
msg: errors.message
};
errors_list.push(error);
deferred.reject(errors_list);
} else {
deferred.resolve(data);
}
});
return deferred.promise;
};
this.doFacebookLogin = function(){
var deferred = $q.defer();
_firebase.authWithOAuthPopup("facebook", function(errors, data) {
if (errors) {
var errors_list = [],
error = {
code: errors.code,
msg: errors.message
};
errors_list.push(error);
deferred.reject(errors_list);
} else {
deferred.resolve(data);
}
});
return deferred.promise;
};
this.doSignup = function(user){
var deferred = $q.defer(),
authService = this;
_firebase.createUser({
firstname : user.firstname,
lastname : user.lastname,
email : user.email,
password : user.password,
gender : user.gender
}, function(errors, data) {
if (errors) {
var errors_list = [],
error = {
code: errors.code,
msg: errors.message
};
errors_list.push(error);
deferred.reject(errors_list);
} else {
// After signup we should automatically login the user
authService.doLogin(user)
.then(function(data){
// success
deferred.resolve(data);
},function(err){
// error
deferred.reject(err);
});
}
});
return deferred.promise;
};
this.doLogout = function(){
_firebase.unauth();
};
})
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.css" rel="stylesheet">
<link href="lib/ion-md-input/css/ion-md-input.min.css" rel="stylesheet">
<link href="lib/ionic-material/dist/ionic.material.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="css/geomuse.css" rel="stylesheet">
<link href="http://code.ionicframework.com/ionicons/1.5.2/css/ionicons.min.css" rel="stylesheet">
<script src="lib/ionic/js/ionic.bundle.js"></script>
<script src="lib/ionic-material/dist/ionic.material.min.js"></script>
<script src="lib/ion-md-input/js/ion-md-input.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="lib/ngCordova/dist/ng-cordova.js"></script>
<script src="cordova.js"></script>
<!--Googple maps plugin-->
<script src="http://maps.google.com/maps/api/js?key=AIzaSyAq9weEMgdVahLcdbvokguOZDuZ3PVVyig&sensor=true"></script>
<!--Firebase-->
<script src="lib/firebase/firebase.js"></script>
<script src="lib/angularfire/dist/angularfire.min.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
</head>
<body ng-app="starter">
<ion-nav-view></ion-nav-view>
</body>
</html>
muser.html (Logged in view):
<ion-view view-title="Login" align-title="left">
<ion-content>
<div id="map"></div>
</ion-content>
</ion-view>
app.js
angular.module('starter', ['ionic', 'starter.controllers', 'ionic-material', 'ionMdInput', 'ngCordova', 'firebase', 'socialAuth'])
.run(function($ionicPlatform, $state, AuthService, $rootScope) {
$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) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
AuthService.userIsLoggedIn().then(function(response)
{
if(response === true)
{
$state.go('app.muser');
}
else
{
$state.go('auth.connect');
}
});
// 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);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
// UI Router Authentication Check
$rootScope.$on("$stateChangeStart", function(event, toState, toParams, fromState, fromParams){
if (toState.data.authenticate)
{
AuthService.userIsLoggedIn().then(function(response)
{
if(response === false)
{
event.preventDefault();
$state.go('auth.connect');
}
});
}
});
})
.config(function($stateProvider, $urlRouterProvider, $ionicConfigProvider) {
// Turn off caching for demo simplicity's sake
$ionicConfigProvider.views.maxCache(0);
/*
// Turn off back button text
$ionicConfigProvider.backButton.previousTitleText(false);
*/
$stateProvider.state('app', {
url: '/app',
abstract: true,
templateUrl: 'templates/menu.html',
controller: 'AppCtrl'
})
.state('app.activity', {
url: '/activity',
views: {
'menuContent': {
templateUrl: 'templates/activity.html',
controller: 'ActivityCtrl'
},
'fabContent': {
template: '<button id="fab-activity" class="button button-fab button-fab-top-right expanded button-energized-900 flap"><i class="icon ion-paper-airplane"></i></button>',
controller: function ($timeout) {
$timeout(function () {
document.getElementById('fab-activity').classList.toggle('on');
}, 200);
}
}
}
})
.state('app.register', {
url: '/register',
views: {
'menuContent': {
templateUrl: 'templates/register.html',
controller: 'ConnectCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.register-email', {
url: '/register-email',
views: {
'menuContent': {
templateUrl: 'templates/register-email.html',
controller: 'SignUpCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.login', {
url: '/login',
views: {
'menuContent': {
templateUrl: 'templates/login.html',
controller: 'ConnectCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.forget-password', {
url: '/forget-password',
views: {
'menuContent': {
templateUrl: 'templates/forget-password.html',
controller: 'ForgetPasswordCtrl'
},
'fabContent': {
template: ''
}
}
})
.state('app.signup', {
url: '/signup',
views: {
'menuContent': {
templateUrl: 'templates/auth/sign-up.html',
controller: 'SignUpCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.connect', {
url: '/connect',
views: {
'menuContent': {
templateUrl: 'templates/auth/connect.html',
controller: 'ConnectCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
.state('app.muser', {
url: '/muser',
views: {
'menuContent': {
templateUrl: 'templates/app/muser.html',
controller: 'MuserCtrl'
},
'fabContent': {
template: ''
}
},
data: {
authenticate: false
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/start');
});
Help would be greatly appreciated
Related
I am creating webpage with webpack and Ive got strange error.
Data must be a valid JSON object. Received: ".... Undefined
index: id
So, I checked my objects which i sending. Then, when my service to get ID returns something like this in console log:
ƒ (){
return id;
}
So, I know that I've to run function first, then html template. Where I can get the error if we are talking about webpack?
It's my app.js, where I configure service and templates with controllers:
const css = require('./src/style/app.scss');
var angular = require('angular');
var ngRoute = require('angular-route');
var ngModule = angular.module('app', ['ngRoute']);
require('./src/js/contact')(ngModule);
require('./src/js/adminNetworks')(ngModule);
require('./src/js/automatic')(ngModule);
require('./src/js/login')(ngModule);
require('./src/js/program')(ngModule);
require('./src/js/register')(ngModule);
require('./src/js/main')(ngModule);
ngModule.service('user', function(){
var username;
var loggedin = false;
var id;
this.getName = function(){
return username;
};
this.setID = function(userID){
id = userID;
};
this.getID = function(){
return id;
};
this.isUserLoggedIn = function(){
if(!!localStorage.getItem('login')){
loggedin = true;
var data = JSON.parse(localStorage.getItem('login'));
username = data.username;
id = data.id;
}
return loggedin;
};
this.saveData = function(data){
username = data.user;
id = data.id;
loggedin = true;
localStorage.setItem('login', JSON.stringify({
username: username,
id: id
}));
};
this.clearData = function(){
localStorage.removeItem('login');
username="";
id="";
loggedin = false;
}
})
ngModule.controller('IndexController', ['$scope', 'user', function ($scope, user) {
$scope.aa = function(){
console.log(user.get);
}
}])
ngModule.config(function($routeProvider, $locationProvider){
$locationProvider.hashPrefix('');
$routeProvider
.when('/', {
templateUrl: 'main.html',
controller: 'MainCtrl'
})
.when('/program', {
templateUrl: 'program.html',
controller: 'ProgramCtrl',
resolve: {
check: function($location, user){
if(!user.isUserLoggedIn()){
$location.path('/');
alert('Musisz być zalogowany')
}
}
}
})
.when('/administration', {
templateUrl: 'adminNetworks.html',
controller: 'NetworkCtrl'
})
.when('/automatic', {
templateUrl: 'automatic.html',
controller: 'AutomaticCtrl'
})
.when('/contact', {
templateUrl: 'contact.html',
controller: 'ContactCtrl'
})
.when('/registry', {
templateUrl: 'register.html',
controller: 'RegisterCtrl'
})
.when('/login', {
templateUrl: 'login.html',
controller: 'LoginCtrl'
})
.when('/logout', {
resolve: {
deadResolve: function($location, user){
user.clearData();
$location.path('/');
}
}
})
.otherwise({
redirectTo: "/"
});
});
Firstly, I thought, that it's because of load chunks like this:
plugins: [
new HtmlWebpackPlugin({
title: 'Główna',
hash: true,
allChunks: true,
template: './src/html/index.html'
}),
new HtmlWebpackPlugin({
title: 'Main',
hash: true,
chunks: ['main'],
filename: 'main.html',
template: './src/html/main.html'
}),
but when I removed chunks section, it's still the same.
Please at least for any ideas.
#Edit - my new pass sender:
module.exports = function(ngModule) {
ngModule.controller('MainCtrl', ['$scope', '$http','user', function ($scope, $http, user) {
$scope.user = user.getName();
console.log("LOCAL STORAGE");
console.log(localStorage);
$scope.newPass = function(){
debugger;
var password = $scope.newpassword;
$http({
url: 'http://localhost/webpack/updatePass.php',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded'
},
data: 'newPass='+password+'&id='+user.getID()
}).then(function(response){
if(response.data.status =='done') {
alert('Changed');
}else {
alert('error');
}
})
}
}])
}
Currently our website in angularjs is not updated by latest javascript version without doing hard refresh is browser. In order to update it on real time basis, we have started sending a custom header (APP-VERSION) in our rest API based on which we can reload the page which results in updating the website by latest javascript version.
This version comparision code is written in javascript is the HTTP interceptor which is not updated on client side.
In order to update index.html, we have tried various scenario which are as follows:-
1.We have changed the name of index.html to default.html but still it is not updated on client side.
2.We have changed the path (/test/index.html) of index.html, still its not working.
3.We have used on-page script on every page, we got a warning "Trying to load angularjs twice".
4.We have added the custom header (add_header Cache-Control no-cache;) in the config file on nginx which is also not working/
Please help us how to forcefully update the index.html on client side.
Please find the code index.html, HTTPInterceptor, and route.js
index.html:-
<!DOCTYPE html>
<html>
<link href="images/favicon.ico" rel="shortcut icon" type="image/x-icon">
<link href="https://fonts.googleapis.com/icon?family=Material+Icons"
rel="stylesheet">
<link rel="stylesheet"
href="https://cdnjs.cloudflare.com/ajax/libs/WebRupee/2.0/font.min.css" />
<link href="https://fonts.googleapis.com/css?family=Noto+Sans" rel="stylesheet">
<!--<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.504/styles/kendo.common.min.css"/>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.504/styles/kendo.rtl.min.css"/>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.504/styles/kendo.silver.min.css"/>
<link rel="stylesheet" href="http://kendo.cdn.telerik.com/2016.2.504/styles/kendo.mobile.all.min.css"/>
-->
<link rel="stylesheet" href="/css/mrConsultant.min.css?ver=##cssVer">
<!-- <link rel="stylesheet" href="css/preLoginPartner.css"> -->
<meta name="viewport" content="width=device-width, initial-scale=1">
<base href="/">
<!-- Google Tag Manager -->
<script>
##gtmScript
</script>
<!-- End Google Tag Manager -->
</head>
<body ng-app="myApp" ng-cloak layout="column">
<div flex layout="column">
<div ng-view flex layout="column"></div>
</div>
<!-- Google Tag Manager (noscript) -->
<noscript>
##gtmNoScript
</noscript>
<!-- End Google Tag Manager (noscript) -->
</body>
<script type="text/javascript" src="js/mrConsultant.min.js?ver=##jsVer"></script>
<!--<script src="http://kendo.cdn.telerik.com/2016.2.504/js/kendo.all.min.js" ></script>
<script src="http://kendo.cdn.telerik.com/2016.2.607/js/kendo.timezones.min.js" ></script>-->
<!--<script src="https://cdnjs.cloudflare.com/ajax/libs/ngStorage/0.3.6/ngStorage.min.js" async></script>-->
<script src="http://ngmaterial.assets.s3.amazonaws.com/svg-assets-cache.js"></script>
<!--<script src="//ajax.googleapis.com/ajax/libs/angularjs/1.5.0-beta.2/angular-sanitize.js"></script>-->
<script src="https://cdnjs.cloudflare.com/ajax/libs/angular-sanitize/1.6.1/angular-sanitize.min.js"></script>
<noscript>test scritp</noscript>
</html>
HTTPInterceptor:-
myApp.factory('HTTPInterceptor', ['$location','$q','API_URL','version','CookieService','$templateCache','$window',function ($location,$q,API_URL,version,CookieService,$templateCache,$window) {
return {
'request': function (config) {
if ((config.url.indexOf('.html') ==-1) && (config.url.indexOf('.svg')==-1)) {
config.url = API_URL + config.url;
if ((config.url.indexOf('/forgot-password-consultant')==-1) && (config.url.indexOf('/reset-password-consultant')==-1)) {
config.headers['Authorization'] = CookieService.getCookie('AUTH_TOKEN');
}
config.headers['Accept'] = "application/vnd.refer.v1+json";
}
return config;
},
'response': function (resp) {
function createCustomAlert() {
d = document;
if(d.getElementById("website-update")) return;
mObj = d.getElementsByTagName("body")[0].appendChild(d.createElement("div"));
mObj.id = "website-update";
style = mObj.appendChild(d.createElement("style"));
style.innerHTML = "#import url('https://fonts.googleapis.com/css?family=Roboto')";
alertObj = mObj.appendChild(d.createElement("div"));
alertObj.id = "website-update-card";
h1 = alertObj.appendChild(d.createElement("h1"));
h1.appendChild(d.createTextNode("UPDATE ALERT"));
msg = alertObj.appendChild(d.createElement("p"));
msg.innerHTML = "A new version of Refer is available now. Update now for better performance.";
msg1 = alertObj.appendChild(d.createElement("p"));
msg1.innerHTML = "If you are on an important task, continue your work and you can update on next page.";
updateBtn = alertObj.appendChild(d.createElement("button"))
updateBtn.id = "website-update-btn";
updateBtn.innerHTML = "Update Now";
updateBtn.onclick = function() { clearTemplateCache();return true; }
notUpdateBtn = alertObj.appendChild(d.createElement("button"))
notUpdateBtn.id = "website-update-notnow";
notUpdateBtn.innerHTML = "Not now";
notUpdateBtn.onclick = function() { removeCustomAlert();return false; }
}
function removeCustomAlert() {
document.getElementsByTagName("body")[0].removeChild(document.getElementById("website-update"));
}
function clearTemplateCache() {
document.getElementsByTagName("body")[0].removeChild(document.getElementById("website-update"));
$templateCache.removeAll();
$window.location.reload();
}
if (resp.status === 401) {
$templateCache.removeAll();
$window.location.reload();
$location.path('/logout');
}/*else if(resp.status === 200 && resp.headers('app-version') != null && resp.headers('app1-version') != version){
createCustomAlert();
}*/
return resp;
},
'responseError': function (rejection) {
if(rejection.status === 401) {
$templateCache.removeAll();
$location.path('/logout');
}
return $q.reject(rejection);
}
};
}]);
myApp.config(['$httpProvider', function ($httpProvider) {
$httpProvider.interceptors.push('HTTPInterceptor');
}]);
route.js:-
myApp.config(['$routeProvider', '$locationProvider', function ($routeProvider, $locationProvider) {
if(window.history && window.history.pushState){
$locationProvider.html5Mode({
enabled: true,
requireBase: true,
rewriteLinks: true
});
}
$routeProvider.when('/unicorn-:startups-:consultant-:register', {
templateUrl: 'views/registerCampaign.html',
controller: 'RegisterController',
controllerAs: 'registerCtrl'
}).when('/register', {
templateUrl: 'views/register.html',
controller: 'RegisterController',
controllerAs: 'registerCtrl'
}).when('/login', {
templateUrl: 'views/login3.html',
controller: 'LoginController',
controllerAs: 'loginCtrl',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/jobs')
} else {
$location.path('/login');
}
}]
}
}).when('/forgot-password', {
templateUrl: 'views/forgotPassword.html',
controller: '' +
'forgotPasswordController'
}).when('/reset-password/:token/:sm', {
templateUrl: 'views/resetPassword.html',
controller: 'resetPasswordController'
}).when('/logout', {
resolve: {
auth: ['$location', 'UserService', function ($location, UserService) {
UserService.logout();
$location.path('/login');
$location.replace();
}]
}
}).when('/', {
templateUrl: 'views/dashboard.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/dashboard')
} else {
$location.path('/login');
}
}]
}
}).when('/dashboard', {
templateUrl: 'views/dashboard1.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/dashboard')
} else {
$location.path('/login');
}
}]
}
}).when('/jobs/:jobType', {
templateUrl: 'views/jobs.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/jobs.html'
} else {
$location.path('/login');
}
}]
}
}).when('/job-detail/:jobId', {
templateUrl: 'views/job-detail.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/job-detail.html'
} else {
$location.path('/login');
}
}]
}
}).when('/direct-apply/:jobId', {
templateUrl: 'views/apply-new.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/apply-new.html'
} else {
$location.path('/login');
}
}]
}
}).when('/performance', {
templateUrl: 'views/performance.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/performance')
} else {
$location.path('/login');
}
}]
}
}).when('/calendar', {
templateUrl: 'views/calender.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/calendar')
} else {
$location.path('/login');
}
}]
}
}).when('/tracker', {
templateUrl: 'views/tracker.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/tracker')
} else {
$location.path('/login');
}
}]
}
}).when('/internal-jobs', {
templateUrl: 'views/internal-jobs.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/internal-jobs')
} else {
$location.path('/login');
}
}]
}
}).when('/assigned-jobs', {
templateUrl: 'views/assigned-jobs.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
$location.path('/assigned-jobs')
} else {
$location.path('/login');
}
}]
}
}).when('/suggested-candidates/:jobId', {
templateUrl: 'views/suggested-candidates.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/suggested-candidates.html'
} else {
$location.path('/login');
}
}]
}
}).when('/suggested-apply/:jobId', {
templateUrl: 'views/apply-suggested.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/apply-suggested.html'
} else {
$location.path('/login');
}
}]
}
}).when('/edit-candidate/:jobId', {
templateUrl: 'views/edit-candidate.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/edit-candidate.html'
} else {
$location.path('/login');
}
}]
}
}).when('/database', {
templateUrl: 'views/database.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/database.html'
} else {
$location.path('/login');
}
}]
}
}).when('/database-search', {
templateUrl: 'views/database-search.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/database-search.html'
} else {
$location.path('/login');
}
}]
}
}).when('/database-search-result', {
templateUrl: 'views/database-search-result.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/database-search-result.html'
} else {
$location.path('/login');
}
}]
}
}).when('/review-compare', {
templateUrl: 'views/review-compare.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/review-compare.html'
} else {
$location.path('/login');
}
}]
}
}).when('/add-new', {
templateUrl: 'views/add-contact.html',
resolve: {
userInfo: ['$location', 'UserService', function ($location, UserService) {
if (UserService.session()) {
templateUrl: 'views/add-contact.html'
} else {
$location.path('/login');
}
}]
}
})
.otherwise({
redirectTo: '/'
});
}]);
myApp.run(['$rootScope', '$templateCache', function ($rootScope, $templateCache) {
$rootScope.$on('$viewContentLoaded', function () {
$templateCache.removeAll();
});
}]);
nginx settings:-
location / {
add_header Cache-Control no-cache;
root D:\refer-workspace\consultant_web;
try_files $uri $uri/ /index.html/ =404;
expires -1;
}
Thanks in advance.
I am a newbee in angular and I would like to know how to make a AuthenticationService where I would check if user is authenticated or not. I have routes for which I want a user to be authenticated in order to be able to see them, and if they are not authenticated that they are redirected to login page. I am using satellizer for token based authentication.
This is my app.js
angular.module('coop', ['ionic', 'coop.controllers', 'coop.services', 'satellizer'])
.constant('ApiEndpoint', {
url: 'http://coop.app/api'
})
.run(function($ionicPlatform, $rootScope, $auth, $state, $location) {
// Check for login status when changing page URL
$rootScope.$on('$routeChangeStart', function (event, next) {
var currentRoute = next.$$route;
if (!currentRoute || currentRoute.requiresAuth && !AuthenticationService.authenticated) {
$location.path('/auth');
}
else if (!currentRoute || !currentRoute.requiresAuth && AuthenticationService.authenticated) {
$location.path('/front');
}
});
$rootScope.logout = function() {
$auth.logout().then(function() {
// Remove the authenticated user from local storage
localStorage.removeItem('user');
// Remove the current user info from rootscope
$rootScope.currentUser = null;
$state.go('main.auth');
});
}
$rootScope.token = localStorage.getItem('token');
$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 && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
// StatusBar.styleDefault();
StatusBar.show();
StatusBar.overlaysWebView(false);
StatusBar.styleLightContent();
StatusBar.backgroundColorByHexString("#2a2e34");
}
});
})
.config(function($stateProvider, $urlRouterProvider, $authProvider, ApiEndpoint) {
$authProvider.loginUrl = ApiEndpoint.url + '/authenticate';
$stateProvider
.state('main', {
url: '/main',
abstract: true,
templateUrl: 'templates/main.html',
requiresAuth: true
})
.state('main.auth', {
url: '/auth',
views: {
'content': {
templateUrl: 'templates/login.html',
controller: 'AuthController',
requiresAuth: false
}
}
})
.state('main.front', {
url: '/front',
views: {
'content': {
templateUrl: 'templates/main-front.html',
controller: 'FrontPageController',
requiresAuth: true
}
}
})
.state('main.article', {
url: '/article/{id}',
views: {
'content': {
templateUrl: 'templates/main-article.html',
controller: 'ArticleController',
requiresAuth: true
}
}
});
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/main/front');
});
And my controllers:
angular.module('coop.controllers', [])
.controller('FrontPageController', function($scope, ArticleService, $state) {
ArticleService.all().then(function(data){
$scope.articles = data;
$scope.like = function(article){
article.like = article.like == 0 ? 1 : 0;
ArticleService.like(article.id, article.like)
};
})
})
.controller('ArticleController', function($scope, ArticleService, $stateParams, $ionicSlideBoxDelegate, $auth) {
ArticleService.get($stateParams.id).then(function(response) {
$scope.article = response;
$scope.commentsCount = response.comments.length;
$scope.articleText = response.text;
$scope.like = function(){
$scope.article.like = $scope.article.like == 0 ? 1 : 0;
ArticleService.like($scope.article.id, $scope.article.like)
};
$ionicSlideBoxDelegate.update();
})
})
.controller('AuthController', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) {
$scope.loginData = {}
$scope.loginError = false;
$scope.loginErrorText;
$scope.login = function() {
var credentials = {
email: $scope.loginData.email,
password: $scope.loginData.password
}
$auth.login(credentials).then(function(response) {
var token = JSON.stringify();
localStorage.setItem('token', response.data.token);
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('main.front');
}, function(){
$scope.loginError = true;
$scope.loginErrorText = error.data.error;
});
}
});
Updated code
I have changed the app.js as suggested:
// Check for login status when changing page URL
$rootScope.$on('$routeChangeStart', function (event, next) {
var currentRoute = next.$$route;
if (!currentRoute || currentRoute.requiresAuth && !$auth.isAuthenticated()) {
$location.path('/main/login');
}
else if (!currentRoute || !currentRoute.requiresAuth && $auth.isAuthenticated()) {
$location.path('/main/front');
}
});
And have added logout controller to delete user and token from localstorage, but I am still not being redirected to login page:
My controller:
.controller('AuthController', function($scope, $location, $stateParams, $ionicHistory, $http, $state, $auth, $rootScope) {
$scope.loginData = {}
$scope.loginError = false;
$scope.loginErrorText;
$scope.login = function() {
var credentials = {
email: $scope.loginData.email,
password: $scope.loginData.password
}
$auth.login(credentials).then(function(response) {
var token = JSON.stringify();
localStorage.setItem('token', response.data.token);
$ionicHistory.nextViewOptions({
disableBack: true
});
$state.go('main.front');
}, function(){
$scope.loginError = true;
$scope.loginErrorText = error.data.error;
});
}
$scope.logout = function() {
$auth.logout().then(function() {
// Remove the authenticated user from local storage
localStorage.removeItem('user');
localStorage.removeItem('token');
// Remove the current user info from rootscope
$rootScope.currentUser = null;
$state.go('main.login');
});
}
});
If you are using satellizer, it already takes care of this for you.
Use the isAuthenticated() method of satelizer's $auth service instead of defining your own
$rootScope.$on('$routeChangeStart', function (event, next) {
var currentRoute = next.$$route;
if (!currentRoute || currentRoute.requiresAuth && !$auth.isAuthenticated()) {
$location.path('/auth');
}
else if (!currentRoute || !currentRoute.requiresAuth && $auth.isAuthenticated()) {
$location.path('/front');
}
});
Basically what $auth.isAuthenticated() does is checking if the user has a vaild jwt saved, and returns true or false.
The $routeChangeStart handler kicks in in every route change, checks if the route has requiresAuth set and if isAuthenticated returns true or false and acts accordingly.
If you want to do it on your own, here is a good tutorial on how to decode the token and check if it's valid:
https://thinkster.io/angularjs-jwt-auth
I am currently trying to integrate angular bootstrap calendar https://github.com/mattlewis92/angular-bootstrap-calendar into my ionic app. However, I keep running into this error and it is not rendering
Uncaught Error: [$injector:modulerr]
http://errors.angularjs.org/1.4.3/$injector/modulerr?p0=SimpleRESTIonic&p1=
%2F%2Flocalhost%3A8100%2Flib%2Fionic%2Fjs%2Fionic.bundle.min.js%3A50%3A339)
I've tried following the steps mentioned by installing via bower but I am not sure where bower_components is. Thus, I shifted them to the www/lib directory so that they can be accessed. I included the script tags in my index.html.
<link href="lib/angular-bootstrap-calendar/dist/css/angular
bootstrap-calendar.min.css" rel="stylesheet">
<script src="lib/angular-bootstrap-calendar/dist/js/angular
bootstrap-calendar-tpls.min.js"></script>
I went on to install via npm as well because the error was still there.
The following are the code from my respective files:
app.js
angular.module('SimpleRESTIonic', ['ionic', 'backand','SimpleRESTIonic.controllers', 'SimpleRESTIonic.services','mwl.calendar','ui.bootstrap'])
.config(function (BackandProvider, $stateProvider, $urlRouterProvider, $httpProvider) {
// change here to your appName
BackandProvider.setAppName('ionicstarter');
BackandProvider.setSignUpToken('4ce88904-75c5-412c-8365-df97d9e18a8f');
// token is for anonymous login. see http://docs.backand.com/en/latest/apidocs/security/index.html#anonymous-access
BackandProvider.setAnonymousToken('87c37623-a2d2-42af-93df-addc65c6e9ad');
$stateProvider
// setup an abstract state for the tabs directive
.state('tab', {
url: '/tabs',
abstract: true,
templateUrl: 'templates/tabs.html'
})
.state('tab.dashboard', {
url: '/dashboard',
views: {
'tab-dashboard': {
templateUrl: 'templates/tab-dashboard.html',
controller: 'DashboardCtrl as vm'
}
}
})
.state('tab.login', {
url: '/login',
views: {
'tab-login': {
templateUrl: 'templates/tab-login.html',
controller: 'LoginCtrl as login'
}
}
})
.state('tab.signup', {
url: '/signup',
views: {
'tab-signup': {
templateUrl: 'templates/tab-signup.html',
controller: 'SignUpCtrl as vm'
}
}
}
);
$urlRouterProvider.otherwise('/tabs/dashboard');
$httpProvider.interceptors.push('APIInterceptor');
})
.run(function ($ionicPlatform, $rootScope, $state, LoginService, Backand) {
$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 && window.cordova.plugins.Keyboard) {
cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
cordova.plugins.Keyboard.disableScroll(true);
}
if (window.StatusBar) {
// org.apache.cordova.statusbar required
StatusBar.styleLightContent();
}
var isMobile = !(ionic.Platform.platforms[0] == "browser");
Backand.setIsMobile(isMobile);
Backand.setRunSignupAfterErrorInSigninSocial(true);
});
function unauthorized() {
console.log("user is unauthorized, sending to login");
$state.go('tab.login');
}
function signout() {
LoginService.signout();
}
$rootScope.$on('unauthorized', function () {
unauthorized();
});
$rootScope.$on('$stateChangeSuccess', function (event, toState) {
if (toState.name == 'tab.login') {
signout();
}
else if (toState.name != 'tab.login' && Backand.getToken() === undefined) {
unauthorized();
}
});
})
controller.js
angular.module('SimpleRESTIonic.controllers', ['angular-bootstrap-calendar',
'angular-ui-bootstrap'])
.controller('calenderController', function($scope, $rootScope){
$scope.calendarView = 'week';
$scope.calendarDay = new Date();
$scope.tester = 'Is the Controller connecting';
$scope.events = [
{
title: 'My event title', // The title of the event
type: 'info',
startsAt: new Date(2013,5,1,1),
endsAt: new Date(2014,8,26,15),
editable: false,
deletable: false,
incrementsBadgeTotal: true
}
];
})
.controller('LoginCtrl', function (Backand, $state, $rootScope, LoginService) {
var login = this;
function signin() {
LoginService.signin(login.email, login.password)
.then(function () {
onLogin();
}, function (error) {
console.log(error)
})
}
function anonymousLogin() {
LoginService.anonymousLogin();
onLogin();
}
function onLogin() {
$rootScope.$broadcast('authorized');
$state.go('tab.dashboard');
login.username = Backand.getUsername();
}
function signout() {
LoginService.signout()
.then(function () {
//$state.go('tab.login');
$rootScope.$broadcast('logout');
$state.go($state.current, {}, {reload: true});
})
}
function socialSignIn(provider) {
LoginService.socialSignIn(provider)
.then(onValidLogin, onErrorInLogin);
}
function socialSignUp(provider) {
LoginService.socialSignUp(provider)
.then(onValidLogin, onErrorInLogin);
}
onValidLogin = function(response){
onLogin();
login.username = response.data;
}
onErrorInLogin = function(rejection){
login.error = rejection.data;
$rootScope.$broadcast('logout');
}
login.username = '';
login.error = '';
login.signin = signin;
login.signout = signout;
login.anonymousLogin = anonymousLogin;
login.socialSignup = socialSignUp;
login.socialSignin = socialSignIn;
})
.controller('SignUpCtrl', function (Backand, $state, $rootScope, LoginService) {
var vm = this;
vm.signup = signUp;
function signUp(){
vm.errorMessage = '';
LoginService.signup(vm.firstName, vm.lastName, vm.email, vm.password, vm.again)
.then(function (response) {
// success
onLogin();
}, function (reason) {
if(reason.data.error_description !== undefined){
vm.errorMessage = reason.data.error_description;
}
else{
vm.errorMessage = reason.data;
}
});
}
function onLogin() {
$rootScope.$broadcast('authorized');
$state.go('tab.dashboard');
}
vm.email = '';
vm.password ='';
vm.again = '';
vm.firstName = '';
vm.lastName = '';
vm.errorMessage = '';
})
.controller('DashboardCtrl', function (ItemsModel, $rootScope) {
var vm = this;
function goToBackand() {
window.location = 'http://docs.backand.com';
}
function getAll() {
ItemsModel.all()
.then(function (result) {
vm.data = result.data.data;
});
}
function clearData() {
vm.data = null;
}
function create(object) {
ItemsModel.create(object)
.then(function (result) {
cancelCreate();
getAll();
});
}
function update(object) {
ItemsModel.update(object.id, object)
.then(function (result) {
cancelEditing();
getAll();
});
}
function deleteObject(id) {
ItemsModel.delete(id)
.then(function (result) {
cancelEditing();
getAll();
});
}
function initCreateForm() {
vm.newObject = {name: '', description: ''};
}
function setEdited(object) {
vm.edited = angular.copy(object);
vm.isEditing = true;
}
function isCurrent(id) {
return vm.edited !== null && vm.edited.id === id;
}
function cancelEditing() {
vm.edited = null;
vm.isEditing = false;
}
function cancelCreate() {
initCreateForm();
vm.isCreating = false;
}
vm.objects = [];
vm.edited = null;
vm.isEditing = false;
vm.isCreating = false;
vm.getAll = getAll;
vm.create = create;
vm.update = update;
vm.delete = deleteObject;
vm.setEdited = setEdited;
vm.isCurrent = isCurrent;
vm.cancelEditing = cancelEditing;
vm.cancelCreate = cancelCreate;
vm.goToBackand = goToBackand;
vm.isAuthorized = false;
$rootScope.$on('authorized', function () {
vm.isAuthorized = true;
getAll();
});
$rootScope.$on('logout', function () {
clearData();
});
if (!vm.isAuthorized) {
$rootScope.$broadcast('logout');
}
initCreateForm();
getAll();
});
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="initial-scale=1, maximum-scale=1, user-scalable=no, width=device-width">
<title></title>
<link href="lib/ionic/css/ionic.min.css" rel="stylesheet">
<link href="css/style.css" rel="stylesheet">
<link href="lib/angular-bootstrap-calendar/dist/css/angular-bootstrap-calendar.min.css" rel="stylesheet">
<!-- IF using Sass (run gulp sass first), then uncomment below and remove the CSS includes above
<link href="css/ionic.app.css" rel="stylesheet">
-->
<!-- ionic/angularjs js -->
<script src="lib/ionic/js/ionic.bundle.min.js"></script>
<!-- cordova script (this will be a 404 during development) -->
<script src="cordova.js"></script>
<script src="lib/angularbknd-sdk/dist/backand.debug.js"></script>
<!-- your app's js -->
<script src="js/app.js"></script>
<script src="js/controllers.js"></script>
<script src="js/services.js"></script>
<script src="lib/moment/moment.js"></script>
<script src="lib/angular-bootstrap-calendar/dist/js/angular-bootstrap-calendar-tpls.min.js"></script>
</head>
<body ng-app="SimpleRESTIonic">
<ion-nav-bar class="bar-stable">
<ion-nav-back-button>
</ion-nav-back-button>
</ion-nav-bar>
<ion-nav-view></ion-nav-view>
</body>
</html>
I also included moment.js in the script according to a suggestion on another question. Could anyone point me in the right direction as to what I should do to get it up and running? Thanks for your help!
Can you please put your code in a github repository and provide the link to there. it will be easier to find the problem
I am trying to use resolve to check for the authentication state and direct the user to the appropriate view.
I am trying the following (see below), but it does not result in transferring to the appropriate states as it would have done when refreshing the page.
app.js
// Ionic Starter App
// angular.module is a global place for creating, registering and retrieving Angular modules
// 'starter' is the name of this angular module example (also set in a <body> attribute in index.html)
// the 2nd parameter is an array of 'requires'
// 'starter.controllers' is found in controllers.js
angular.module('starter', ['ionic', 'starter.controllers', 'firebase'])
.run(function($ionicPlatform) {
$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) {
// org.apache.cordova.statusbar required
StatusBar.styleDefault();
}
});
})
.run(["$rootScope", "$state", function($rootScope, $state) {
$rootScope.$on("$stateChangeError", function(event, toState, toParams, fromState, fromParams, error) {
// We can catch the error thrown when the $requireAuth promise is rejected
// and redirect the user back to the home page
if (error === "AUTH_REQUIRED") {
console.log('stateChangeError')
$state.go("app.login");
}
});
}])
.config(function($stateProvider, $urlRouterProvider) {
var authResolve = {
authReturn: function($state, $q, $timeout, Auth) {
var defer = $q.defer();
var ref = Auth.refObj();
ref.onAuth(authDataCallback)
function authDataCallback(authData) {
if (authData) {
console.log("authDataCallback: User " + authData.uid + " is logged in with " + authData.provider);
defer.resolve(authData)
} else {
console.log("authDataCallback: User is logged out");
defer.reject('AUTH_REQUIRED')
}
}
$timeout(function() { // See: http://stackoverflow.com/q/24945731/247243
defer.reject('login');
}, 250);
return defer.promise;
}
};
$stateProvider
.state('app', {
url: "/app",
abstract: true,
templateUrl: "templates/menu.html",
controller: 'AppCtrl'
})
.state('app.login', {
url: "/login",
views: {
'menuContent': {
templateUrl: "templates/login.html",
controller: "LoginCtrl"
}
}
})
.state('app.profile', {
url: "/profile",
views: {
'menuContent': {
templateUrl: "templates/profile.html",
resolve: authResolve
}
}
})
// if none of the above states are matched, use this as the fallback
$urlRouterProvider.otherwise('/app/login'); //CHANGE TO HOME
});
controller.js
angular.module('starter.controllers', [])
.controller('AppCtrl', function($scope) {
})
.controller('LoginCtrl', function($scope, $timeout, $state, Auth) {
var ref = Auth.refObj();
var authData = ref.getAuth();
if (authData) {
console.log("User " + authData.uid + " is logged in with " + authData.provider);
$scope.authData = authData;
} else {
console.log("User is logged out");
}
$scope.signOut = function() {
Auth.signOut();
}
$scope.signIn = function() {
Auth.signIn();
}
})
.factory('Auth', function($firebase, $firebaseAuth, $state) {
// Register the callback to be fired every time auth state changes
var ref = new Firebase("https://lovin.firebaseio.com");
var signIn = function() {
ref.authWithPassword({
email : 'sa.ibisevic#gmail.com',
password : 'Maserati2014'
}, authHandler);
// logging users in
function authHandler(error, authData) {
if (error) {
console.log("Login Failed!", error);
$state.go("app.login")
} else {
console.log("Authenticated successfully with payload:", authData);
$state.go("app.profile")
}
}
}
var signOut = function() {
ref.unauth();
$state.go("app.login")
}
var authRef = function() {
return $firebaseAuth(ref);
}
return {
signIn: signIn,
signOut: signOut,
refObj: function() {
return ref;
},
authRef: authRef
}
})
login.html
<ion-view view-title="Login">
<ion-nav-bar class="bar-stable">
<ion-nav-buttons side="left">
<button class="button button-icon button-clear ion-navicon" menu-toggle="left">
</button>
</ion-nav-buttons>
</ion-nav-bar>
<ion-content>
<h1>{{authData.uid}}</h1>
<button class="button" ng-click="signIn()">Sign In</button>
<button class="button" ng-click="signOut()">Sign Out</button>
</ion-content>
</ion-view>
Beware that you can listen to the authentication state on the $firebaseSimpleLogin object. So you could do something like that:
$rootScope.$on('$firebaseSimpleLogin:logout', function(event) {
$state.go('login');
});
Hope this helps.