I have two views right now.
login
main
Right now I login and change my path to /main which works fine. When I am not logged in, and try to visit /main my web service returns "Access denied for user anonymous" which I then forward them to / which is my login view. How can I pass something so my LoginController knows they were forwarded from /main to alert them to login first?
LoginController.js
VforumJS.controller('LoginController', function($scope, $location, $routeParams, LoginModel)
{
$scope.email = "";
$scope.password = "";
$scope.fetching = false;
$scope.error = null;
$scope.login = function()
{
$scope.error = null;
$scope.fetching = true;
LoginModel.login($scope.email, $scope.password);
}
$scope.$on('LoginComplete', function(event, args)
{
log('login complete: ' + args.result);
$scope.fetching = false;
if (args.result == "success")
{
$location.path('/main');
}
else
{
$scope.error = args.result;
}
});
});
MainController.js
VforumJS.controller('MainController', function($scope, $location, $routeParams, MainModel)
{
$scope.currentTitle = '-1';
$scope.presentationData = MainModel.getPresentations();
$scope.$on('PresentationsLoaded', function(event, args)
{
log(args.result);
if (args.result != "Access denied for user anonymous")
{
//-- Parse preso data
$scope.presentationData = args.result;
}
else
{
//-- Need to login first, route them back to login screen
$location.path("/");
}
});
});
You can use $location.search() in your MainController to pass query string to the LoginController.
Inside you MainController:
if (args.result != "Access denied for user anonymous")
{
//-- Parse preso data
$scope.presentationData = args.result;
}
else
{
//-- Need to login first, route them back to login screen
$location.search({ redirectFrom: $location.path() });
$location.path("/");
}
And then in your LoginController, shortened for brevity:
VforumJS.controller('LoginController', function($scope, $location, $routeParams, LoginModel)
{
var queryString = $location.search();
$scope.$on('LoginComplete', function(event, args)
{
log('login complete: ' + args.result);
$scope.fetching = false;
if (args.result == "success")
{
if (queryString && queryString.redirectFrom) {
$location.path(queryString.redirectFrom);
} else {
$location.path('/somedefaultlocation');
}
}
else
{
$scope.error = args.result;
}
});
});
Alternatively you can use a shared service, maybe even your LoginModel to set a parameter from MainController to indicate the redirect came from it.
Update
Even better still, use $httpProvider.interceptors to register a response interceptor, and then use the same $location.search() technique described above to redirect to the login screen on authentication failure. This method is ideal as your controllers are then clean of authentication logic.
$location broadcasts $locationChangeStart and $locationChangeSuccess events, and the third param of each is oldUrl.
One solution would be to have a service that subscribes to $locationChangeStart in order to save the current and old urls.
When you hit /, your LoginController can check your service to see if the oldUrl is /main, and then act accordingly.
Related
I created an app using JHipster and try to edit the `register.html'. The code where I need help is shows below:
<div class="alert alert-success" ng-show="vm.success" data translate="register.messages.success">
<strong>Registration saved!</strong> Please check your email for confirmation.
</div>
<div class="alert alert-danger" ng-show="vm.error" data-translate="register.messages.error.fail">
<strong>Registration failed!</strong> Please try again later.
</div>
I omitted the rest of the code as they are equal to these two, only with different messages and ng-models . & the register.controller.js :
(function() {
'use strict';
angular
.module('MyApp')
.controller('RegisterController', RegisterController);
RegisterController.$inject = ['$translate', '$timeout', 'Auth', 'LoginService'];
function RegisterController ($translate, $timeout, Auth, LoginService) {
var vm = this;
vm.doNotMatch = null;
vm.error = null;
vm.errorUserExists = null;
vm.login = LoginService.open;
vm.register = register;
vm.registerAccount = {};
vm.success = null;
$timeout(function (){angular.element('#login').focus();});
function register () {
if (vm.registerAccount.password !== vm.confirmPassword) {
vm.doNotMatch = 'ERROR';
} else {
vm.registerAccount.langKey = $translate.use();
vm.doNotMatch = null;
vm.error = null;
vm.errorUserExists = null;
vm.errorEmailExists = null;
Auth.createAccount(vm.registerAccount).then(function () {
vm.success = 'OK';
}).catch(function (response) {
vm.success = null;
if (response.status === 400 && response.data === 'login already in use') {
vm.errorUserExists = 'ERROR';
} else if (response.status === 400 && response.data === 'e-mail address already in use') {
vm.errorEmailExists = 'ERROR';
} else {
vm.error = 'ERROR';
}
});
}
}
}
})();
My question is by default the error handling messages must be hidden, and once the form is valuated, they should be shown based on the condition. But I cannot figure out how to make this work...
Below is the default register.html page:
The generated register.html does not show those messages by default. It looks like you are loading just the HTML file into the browser, but you need to run the app and load the index.html from there to run the Angular code.
Run ./mvnw or ./gradlew and access the frontend at http://localhost:8080
You can also run gulp which will serve your frontend at http://localhost:9000 with live-reloading when you make changes. More info can be found in the Using JHipster in development documentation
The register page looks like the following image when ran correctly:
This is the continuation of my question
So far i didn't even get the url value. But now i can able to get the url paameter but the problem is that my page is getting redirected once showing the alert
Here is my controller and route
route
.when('/showprofile/:UserID', {
templateUrl: 'resources/views/layout/showprofile.php',
controller: 'ShowUserCtrl'
})
Controller ;
app.controller('ShowUserCtrl', function($scope, $routeParams) {
var b = $routeParams.UserID;
alert(b);
$scope.userid = $routeParams.UserID;
});
My View :
{{userid}}
The problem is My Url is like this
http://192.168.1.58/myapp/#/showprofile/18
After showing the alert 18
It makes the url like
http://192.168.1.58/myapp/#/showprofile/:UserID
How can i stop the redirection .. ??
I just want this as my final url
http://192.168.1.58/myapp/#/showprofile/18
I found that the problem is because of .run function that i have.
After removing it works good.
Here is my .run function
.run(function ($rootScope, $location, Data, $http) {
$rootScope.$on("$routeChangeStart", function (event, next, current) {
$http.post('CheckSession', {}).then(function (results)
{
console.log(results.data);
var nextUrl = next.$$route.originalPath;
if (nextUrl == '/signin' || nextUrl == '/login' || nextUrl == '/verify' || nextUrl == '/registration' || nextUrl == '/forget' || nextUrl == '/invalidtoken' || nextUrl == '/registersuccess')
{
console.log('outpages');
}
else
{
if (results.data == 1)
{
console.log('loggedin');
console.log(nextUrl);
console.log('to be redirect');
$location.path(nextUrl);
}
else {
console.log('not logged in');
$location.path('login');
}
}
});
});
});
Hi I have created a factory to get the current amount of users online from my Firebase database.
When I first load the page it works great and displays all the current users but then if I go to another page and come back it will display as 0 until a new user connects or disconnects or if I refresh.
I followed this guide:
http://www.ng-newsletter.com/advent2013/#!/day/9
App.js
angular.module('myApp', ['ngRoute', 'firebase', 'ui.bootstrap'])
.factory('PresenceService', ['$rootScope',
function($rootScope) {
var onlineUsers = 0;
// Create our references
var listRef = new Firebase('https://my-db.firebaseio.com/presence/');
// This creates a unique reference for each user
var onlineUserRef = listRef.push();
var presenceRef = new Firebase('https://my-db.firebaseio.com/.info/connected');
// Add ourselves to presence list when online.
presenceRef.on('value', function(snap) {
if (snap.val()) {
onlineUserRef.set(true);
// Remove ourselves when we disconnect.
onlineUserRef.onDisconnect().remove();
}
});
// Get the user count and notify the application
listRef.on('value', function(snap) {
onlineUsers = snap.numChildren();
$rootScope.$broadcast('onOnlineUser');
});
var getOnlineUserCount = function() {
return onlineUsers;
}
return {
getOnlineUserCount: getOnlineUserCount
}
}
]);
mainController.js
angular.module('myApp')
.controller('mainController', function($scope, authService, PresenceService, $http, $routeParams, $firebaseObject, $firebaseAuth, $location) {
$scope.totalViewers = 0;
$scope.$on('onOnlineUser', function() {
$scope.$apply(function() {
$scope.totalViewers = PresenceService.getOnlineUserCount();
});
});
// login section and auth
var ref = new Firebase("https://my-db.firebaseio.com");
$scope.authObj = $firebaseAuth(ref);
var authData = $scope.authObj.$getAuth();
if (authData) {
console.log("Logged in as:", authData.uid);
$location.path( "/user/"+authData.uid );
} else {
console.log("Logged out");
$location.path( "/" );
}
// user ref
var userRef = new Firebase("https://my-db.firebaseio.com/users/"+ authData.uid);
var syncObject = $firebaseObject(userRef);
syncObject.$bindTo($scope, "data");
});
main.html
{{totalViewers}}
Inside your controller, change yr first line as below.
//$scope.totalViewers = 0;
$scope.totalViewers = PresenceService.getOnlineUserCount();
Because each time you leave the page, its controller gets flushed and next time its getting value "zero". So, correctly you should read $scope.totalViewers from your service.
Im trying to verify that a user is logged in. Initially I went with $scope.use, $scope.user.uid, $scope.getCurrenUser() as described on Firebase docs but I think I simply have the dependencies wrong.
Code:
myApp.js
https://gist.github.com/sebbe605/2b9ff7d3b798a58a3886
firebase.js
https://gist.github.com/sebbe605/f9e7b9a75590b3938524
If I understand this correctly there is no way for the program to know that I'm referring to a Firebase user. To clarify I want .controller('templateCtrl',function($scope, $firebase) to have the ability to show a certain button if the user is logged in.
--UPDATE 1--
So, i have updated my files and for what i understand this should work. Previous code are as gits above to enhance the cluther.
myApp.js
angular.module('myApp', [
'ngRoute',
'firebase'
])
.config(['$routeProvider', function($routeProvider) {
$routeProvider
.when('/template',
{
templateUrl:'partials/template.html', controller:'templateCtrl'
});
$routeProvider
.when('/login',
{
templateUrl:'partials/login.html', controller:'signupCtrl'
});
$routeProvider
.when('/signup',
{
templateUrl:'partials/signup.html', controller:'signupCtrl'
});
$routeProvider
.when('/user',
{
templateUrl:'partials/user.html', controller:'userCtrl'
});
$routeProvider
.otherwise('/template');
}])
controllers.js
'use strict';
angular.module('myApp').controller('signupCtrl', function($scope, $http, angularFire, angularFireAuth){
$scope.loginBusy = false;
$scope.userData = $scope.userData || {};
var ref = new Firebase('https://boostme.firebaseio.com/');
angularFireAuth.initialize(ref, {scope: $scope, name: 'user'});
/*//////////////LOGIN - LOGOUT - REGISTER////////////////////*/
$scope.loginEmailText = "Email"
$scope.loginPasswordText = "Password"
$scope.login = function() {
$scope.loginMessage = "";
if ((angular.isDefined($scope.loginEmail) && $scope.loginEmail != "") && (angular.isDefined($scope.loginPassword) && $scope.loginPassword != "")) {
$scope.loginBusy = true;
angularFireAuth.login('password', {
email: $scope.loginEmail,
password: $scope.loginPassword
});
} else {
$scope.loginPassword = ""
$scope.loginPasswordText = "Incorrect email or password"
}
};
$scope.logout = function() {
$scope.loginBusy = true;
$scope.loginMessage = "";
$scope.greeting = "";
$scope.disassociateUserData();
$scope.userData = {};
angularFireAuth.logout();
};
$scope.emailText = "Email"
$scope.passwordText = "Password"
$scope.confirmPasswordText = "Confirm Password"
$scope.register = function() {
$scope.loginMessage = "";
if ((angular.isDefined($scope.email) && $scope.email != "") && (angular.isDefined($scope.password0) && $scope.password0 != "" && $scope.password0 == $scope.password1)) {
$scope.loginBusy = true;
angularFireAuth.createUser($scope.email, $scope.password0, function(err, user) {
if (user) {
console.log('New User Registered');
}
$scope.loginBusy = false;
});
} else {
$scope.password0 =""
$scope.password1 =""
$scope.passwordText = "Password Not Matching"
$scope.confirmPasswordText = "Password Not Matching"
}
};
$scope.$on('angularFireAuth:login', function(evt, user) {
$scope.loginBusy = false;
$scope.user = user;
console.log("User is Logged In");
angularFire(ref.child('users/' + $scope.user.id), $scope, 'userData').then(function(disassociate) {
$scope.userData.name = $scope.userData.name || {};
if (!$scope.userData.name.first) {
$scope.greeting = "Hello!";
} else {
$scope.greeting = "Hello, " + $scope.userData.name.first + "!";
}
$scope.disassociateUserData = function() {
disassociate();
};
});
});
$scope.$on('angularFireAuth:logout', function(evt) {
$scope.loginBusy = false;
$scope.user = {};
console.log('User is Logged Out');
});
$scope.$on('angularFireAuth:error', function(evt, err) {
$scope.greeting = "";
$scope.loginBusy = false;
$scope.loginMessage = "";
console.log('Error: ' + err.code);
switch(err.code) {
case 'EMAIL_TAKEN':
$scope.loginMessage = "That email address is already registered!";
break;
case 'INVALID_PASSWORD':
$scope.loginMessage = "Invalid username + password";
}
});
})
Output:
Error: [$injector:unpr] Unknown provider: angularFireProvider <- angularFire
http://errors.angularjs.org/1.3.0-rc.3/$injector/unpr?p0=angularFireProvider%20%3C-%20angularFire
at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:80:12
at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:3938:19
at Object.getService [as get] (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:4071:39)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:3943:45
at getService (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:4071:39)
at invoke (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:4103:13)
at Object.instantiate (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:4123:23)
at http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:7771:28
at link (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular-route.js:938:26)
at invokeLinkFn (http://ajax.googleapis.com/ajax/libs/angularjs/1.3.0-rc.3/angular.js:7549:9) <div ng-view="" class="ng-scope">
(anonymous function) angular.js:10683
(anonymous function) angular.js:7858
invokeLinkFn angular.js:7551
nodeLinkFn angular.js:7069
compositeLinkFn angular.js:6441
publicLinkFn angular.js:6320
boundTranscludeFn angular.js:6461
controllersBoundTransclude angular.js:7096
update angular-route.js:896
Scope.$broadcast angular.js:13751
(anonymous function) angular-route.js:579
processQueue angular.js:12234
(anonymous function) angular.js:12250
Scope.$eval angular.js:13436
Scope.$digest angular.js:13248
Scope.$apply angular.js:13540
done angular.js:8884
completeRequest angular.js:9099
xhr.onreadystatechange angular.js:9038
I cant figure out what the problem is. However i think there is something wrong with: but i can't tell. If more information is needed i'm happy to post it.
I initially was taking the same if-then-else approach as you do for handling privileged actions. But it turns out this is not the best approach when using Angular. Instead of having this if-then-else approach, try to reframe the problem to a solution that isolates the privileged code.
show a certain button if the user is logged in
So your original question was about showing an HTML element only when the user if logged in, which is easy with something like this in your controller:
$scope.auth = $firebaseSimpleLogin(new Firebase(FBURL));
This line binds the Firebase login status to the current scope, which makes it available to the view. No if-then-else is needed, since there is always a login status. AngularFire ensure that the view gets notified when that status changes, so all we have to do is ensure that we have the HTML markup to handle both presence and absence of authenticated users:
<div ng-controller="TrenchesCtrl" class='auth'>
<div ng-show="auth.user">
<p>You are logged in as <i class='fa fa-{{auth.user.provider}}'></i> {{auth.user.displayName}}</p>
<button ng-click="auth.$logout()">Logout</button>
</div>
<div ng-hide="auth.user">
<p>Welcome, please log in.</p>
<button ng-click="auth.$login('twitter')">Login with <i class='fa fa-twitter'> Twitter</i></button>
<button ng-click="auth.$login('github')">Login with <i class='fa fa-github'> GitHub</i></button>
</div>
</div>
See how it almost reads like an if-then-else? But then one without me writing code that tries to detect if the user is logged in. It is all declaratively handled by AngularJS and AngularFire.
perform actions only when a user is logged in
When you actually need to perform a privileged action, I've found it easiest to isolate the code like this:
function updateCard(id, update) {
var auth = $firebaseSimpleLogin(new Firebase(FBURL));
auth.$getCurrentUser().then(function(user) {
update.owned_by = user.username;
var sync = $firebase(ref.child('cards').child(id));
sync.$update(update);
});
};
Note that these are (simplified) fragments from my Trenches app (demo), which I wrote to learn more about Angular and AngularFire.
I am trying to overwrite portions of my single page app using only javascript and AngularJS.
Overwrites are based on subdomain.
Every subdomain is pointing to the same doc root.
controllers.js
controller('AppController', ['$scope','$route','$routeParams','$location', function($scope, $route, $routeParams, $location) {
$scope.$on("$routeChangeSuccess",function( $currentRoute, $previousRoute ){
render();
});
var render = function(){
//Is it actually a subdomain?
if($location.host().split(".",1).length>2){
//Use subdomain folder if it is.
var url = "views/"+$location.host().split(".",1)+"/"+$route.current.template;
var http = new XMLHttpRequest();
http.onreadystatechange=function(){
if (http.readyState==4){
//If there isn't an overwrite, use the original.
$scope.page = (http.status!=404)?url:("views/"+$route.current.template);
}
}
http.open('HEAD', url, true);
http.send();
}
else{
//Else we are on the parent domain.
$scope.page = "views/"+$route.current.template;
}
};
}])
config.js
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$locationProvider.html5Mode(true);
$routeProvider.when('/', {
template: 'home.html'
});
$routeProvider.when('/services', {
template: 'services.html'
});
$routeProvider.otherwise({redirectTo: '/'});
}]);
index.html
<html lang="en" ng-app="myApp" ng-controller="AppController">
<body>
<div ng-include src="page" class="container"></div>
</body>
</html>
Because this is a single page app, when you hit a URL directly, it's going to 404. That's why we apply rewrite rules on the server. In my case I'm using nginx:
location / {
try_files $uri /index.html;
}
This works great when I'm not on a subdomain, but then again I'm also not sending out an XMLHttpRequest. When I do use the subdomain, now we need to check for an overwrite.
The tricky part here is that the rewrite rules are forcing the XMLHttpRequest to return a 200.
Ideas on how I can have my cake and eat it too?
I decided to go with a local stradegy for two reasons:
There is no additional overhead of XML request.
404 messages wont polute console logs when resource doesn't exist.
services.js
factory('Views', function($location,$route,$routeParams,objExistsFilter) {
var viewsService = {};
var views = {
subdomain1:{
'home.html':'/views/subdomain1/home.html'
},
subdomain2:{
},
'home.html':'/views/home.html',
};
viewsService.returnView = function() {
var y = $route.current.template;
var x = $location.host().split(".");
return (x.length>2)?(objExistsFilter(views[x[0]][y]))?views[x[0]][y]:views[y]:views[y];
};
viewsService.returnViews = function() {
return views;
};
return viewsService;
}).
controllers.js
controller('AppController', ['$scope','Views', function($scope, Views) {
$scope.$on("$routeChangeSuccess",function( $currentRoute, $previousRoute ){
$scope.page = Views.returnView();
});
}]).
filters.js
filter('objExists', function () {
return function (property) {
try {
return property;
} catch (err) {
return null
}
};
});