AngularJS Route with Spring Security - angularjs

I was following a Spring Security/AngularJS tutorial to learn the mechanics of it. I was pretty confident that I had the business logic in place to route from a CSS login page to a CSS-based dashboard page. Here is my index.html:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
<meta name="description" content="">
<meta name="author" content="">
<link rel="icon" href="../img/favicon.ico">
<title>Sample App</title>
<!-- Bootstrap core CSS -->
<link href="../css/bootstrap.min.css" rel="stylesheet">
<!-- Custom styles for this template -->
<link href="../css/signin.css" rel="stylesheet">
</head>
<body ng-app="hello">
<div ng-controller="loginController as controller" class="container">
<form role="form" class="form-signin" ng-submit="controller.login()">
<h2 class="form-signin-heading">Please sign in</h2>
<label for="inputUsername" class="sr-only">Username</label>
<input type="text" id="username" name="username" ng-model="controller.credentials.username"
class="form-control" placeholder="Username" required autofocus>
<label for="inputPassword" class="sr-only">Password</label>
<input type="password" id="password" name="password" ng-model="controller.credentials.password"
class="form-control" placeholder="Password" required>
<div class="checkbox">
<label>
<input type="checkbox" value="remember-me"> Remember me
</label>
</div>
<button class="btn btn-lg btn-primary btn-block" type="submit">Sign in</button>
</form>
</div> <!-- /container -->
<script src="js/angular-bootstrap.js" type="text/javascript"></script>
<script src="../js/sample.js"></script>
</body>
</html>
Here is the sample.js file:
angular.module('hello', [ 'ngRoute' ]).config(
function($routeProvider, $httpProvider) {$routeProvider
.when('/', {
templateUrl : 'index.html',
controller : 'loginController',
controllerAs: 'controller'
})
.when('/dashboard', {
templateUrl : 'dashboard.html',
controller : 'dashboardController',
controllerAs: 'controller'
})
.otherwise('/');
$httpProvider.defaults.headers.common['X-Requested-With'] = 'XMLHttpRequest';
}).controller('loginController', function($rootScope, $http, $location, $route) {
var self = this;
self.tab = function(route) {
return $route.current && route === $route.current.controller;
};
var authenticate = function(credentials, callback) {
var headers = credentials ? {
authorization : "Basic "
+ btoa(credentials.username + ":"
+ credentials.password)
} : {};
$http.get('user', {
headers : headers
}).then(function(response) {
if (response.data.name) {
$rootScope.authenticated = true;
} else {
$rootScope.authenticated = false;
}
callback && callback($rootScope.authenticated);
}, function() {
$rootScope.authenticated = false;
callback && callback(false);
});
}
authenticate();
self.credentials = {};
self.login = function() {
authenticate(self.credentials, function(authenticated) {
if (authenticated) {
console.log("Login succeeded")
$location.path("/dashboard");
self.error = false;
$rootScope.authenticated = true;
} else {
console.log("Login failed")
$location.path("/");
self.error = true;
$rootScope.authenticated = false;
}
})
};
self.logout = function() {
$http.post('logout', {}).finally(function() {
$rootScope.authenticated = false;
$location.path("/");
});
}
}).controller('dashboardController', function ($scope, $http, $location) {
$scope.go = function () {
$location.path('/dashboard');
}
});
The login page (index.html) loads fine when I start the server. If I login, the URL changes to "http://localhost:8080/?username=user&password=password" but nothing else happens. Ideally the username and password would not be in the URL....so I would love to know how to eliminate that portion. But the main issues are getting the dashboard.html page to load when authenticated and also to pass the username to the dashboard.html page so I can use it in the context. What am I missing/doing wrong?

Related

Angularjs. Error: $controller:ctrlreg A controller with this name is not registered

I'm getting the following error on the chrome console:
The controller with the name 'registerCtrl' is not registered.
for some reason, my registerCtrl is not being recognized when routing to the root or /register.
for some reason, my registerCtrl is not being recognized when routing to the root or /register.
Index.html
<html ng-app="testApp">
<head>
<base href="/">
<title></title>
<link href="Content/bootstrap.css" rel="stylesheet" />
<script src="Scripts/jquery-3.2.1.min.js"></script>
<script src="Scripts/angular.min.js"></script>
<script src="Scripts/angular-route.min.js"></script>
<script src="app/app.js"></script>
<script src="app/register/registerCtrl.js"></script>
<script src="app/adminDashBoard/adminDashBoardCtrl.js"></script>
<script src="app/services/hubProxy.js"></script>
<script src="Scripts/bootstrap.min.js"></script>
<script src="app/directives/alerts/alertDir.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
app.js(boostrap)
(function () {
var app = angular.module('testApp', ["ngRoute"]);
app.config(function ($routeProvider, $locationProvider) {
$routeProvider
.when("/", {
templateUrl: "/app/register/register.html",
controller: 'registerCtrl'
})
.when("/register", {
templateUrl: "/app/register/register.html",
controller: 'registerCtrl'
})
.when("/adminDashBoard", {
templateUrl: "/app/adminDashBoard/adminDashBoard.html",
controller:'adminDashboardCtrl'
})
});
})();
registerCtrl
(function () {
var registerController = function ($scope, hubProxy) {
var hub = hubProxy("", "UserRegisterHub");
$scope.registerUser = function () {
// call hub and pass these details
if ($scope.userName !== "" && $scope.emailAddress !== "") {
hub.invoke("RegisterUser", function (result) {
// confirm user use boostrap alert
$scope.showAlert = true;
});
}
}
$scope.userName = "yoyoy";
$scope.email = "";
};
angular.module("testApp").controller('RegisterCtrl', registerController);
})();
register.Html
<div>
<a ng-href="adminDashBoard">Admin Dashboard</a>
<alert showAlert="true"></alert>
<label>{{userName}}</label>
<form name="register">
<div>
<label>Name</label>
<input type="text" required="" ng-model="userName" />
</div>
<div>
<label>Email</label>
<input type="text" required="" ng-model="email" />
</div>
<div>
<input type="submit" ng-click="registerUser()" value="submit" />
</div>
</form>
</div>
Any ideas? thanks

AngularJS controller dont work after adding a service as dependency

hello i'm working on my small project using angular , during the creating my second controller with second service i have a problem , when i inject my own service as a dependency in the controller it dont work and all of expressions in html file are not resolved (before adding a service all works) here is my code
after adding AccSrv to AccCtrl the problem occurs
angular.module('myApp', ['ngRoute', 'membersService']).config(
['$httpProvider', '$routeProvider', function ($httpProvider, $routeProvider) {
$routeProvider.when('/home', {
templateUrl: 'partials/home.html',
controller: 'MembersCtrl'
}).when('/account', {
templateUrl: 'partials/account.html',
controller: 'AccCtrl'
}).otherwise({
redirectTo: '/home'
});
}]);
<!DOCTYPE html>
<html lang="en" ng-app="myApp">
<head>
<title>myApp</title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<meta name="format-detection" content="telephone=no"/>
<link rel="stylesheet" href="css/screen.css" type="text/css"/>
<script src="js/libs/angular.js"></script>
<script src="js/libs/angular-route.js"></script>
<script src="js/libs/angular-resource.js"></script>
<script src="js/app.js"></script>
<script src="js/services/MemberSrv.js"></script>
<script src="js/controllers/MemberCtrl.js"></script>
<script src="js/services/AccSrv.js"></script>
<script src="js/controllers/AccCtrl.js"></script>
</head>
<body>
<div ng-view></div>
</body>
</html>
<!DOCTYPE html>
<html lang="en" ng-app="myApp" ng-controller="AccCtrl">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<p>{{hello}}</p>
<p>{{world}}</p>
<form name="accForm" ng-submit="createAccount()">
<div>
<label for="email">Email</label>
<input type="text" name="email" id="email" ng-bind="newAccount.email"/>
</div>
<div>
<label for="password">Password</label>
<input type="password" name="password" id="password" ng-bind="newAccount.password"/>
</div>
<div>
<input type="submit" id="registerAccount" value="Sign-up"/>
</div>
</form>
<form name="accForm" ng-submit="getAccountByEmail()">
<div>
<label for="getemail">CheckEmail</label>
<input type="text" name="getemail" id="getemail" ng-bind="ExistingAccount.email"/>
</div>
<div>
<input type="submit" id="check" value="Check"/>
</div>
</form>
<table>
<tr>
<td>{{ExistingAccount.id}}</td>
<td>{{ExistingAccount.email}}</td>
<td>{{ExistingAccount.password}}</td>
<td>{{ExistingAccount.creationDate}}</td>
</tr>
</table>
</body>
</html>
angular.module('AccountService', []).service('AccSrv', ['$http', function ($http) {
this.getAccountByEmail = function (email) {
var req = {
method: 'GET',
url: "http://localhost:8080/gadziksy-web/rest/account/" + email
};
return $http(req);
};
}]);
var myApp = angular.module('myApp');
myApp.controller('AccCtrl',['$scope','$http' ,'AccSrv' , function ($scope , $http , AccSrv) {
$scope.hello = 'hello';
$scope.world = 'world';
$scope.ExistingAccount = {
"id": '',
"email": '',
"password": '',
"creationDate": ''
};
$scope.getAccount = function () {
return AccSrv.getAccountByEmail($scope.ExistingAccount.email).then(function (data) {
$scope.ExistingAccount = data.data;
})
}
}]);
The problem is that your service is being defined in a module that you are not including anywhere:
angular.module('AccountService', []).service('AccSrv'...etc
should be
myApp.service('AccSrv'...etc
Otherwise you will need to include the AccountService MODULE as a dependency of myApp.
#yBrodsky is correct you need to change
angular.module('AccountService', []).service('AccSrv', ['$http', function ($http) {
To:
angular.module('myApp').service('AccSrv', ['$http', function ($http) {

Angular Routing is not working after logging in

I am trying to login using username and password and displaying a home page.
Homepage contains hyperlink, clicking that should direct to someother content which is not happening.
Can someone help me in this regard.
var app = angular.module('plunker', ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider.
when('/login', {
templateUrl: 'pages/login.html',
controller: 'AppCtrl'
}).
when('/home',{
templateUrl: 'pages/country-list.html',
controller:'CountryListCtrl'
}).
when('/:countryName',{
templateUrl: 'pages/country-detail.html',
controller:'CountryDetailCtrl'
}).
otherwise({
redirectTo: '/login'
});
});
app.run(['$rootScope', '$location', 'Auth', function ($rootScope, $location, Auth) {
$rootScope.$on('$routeChangeStart', function (event) {
console.log('Auth logged:'+Auth.isLoggedIn());
if (!Auth.isLoggedIn()) {
console.log('DENY');
event.preventDefault();
$location.path('/login');
}
else {
console.log('ALLOW');
$location.path('/home');
}
});
}]);
app.factory('Auth', function(){
var user;
console.log('user'+user);
return{
setUser : function(aUser){
user = aUser;
},
isLoggedIn : function(){
return(user)? user : false;
}
}
});
app.controller('AppCtrl', ['$rootScope','$scope','$location', 'Auth',function($rootScope,$scope,$location, Auth) {
$scope.$watch(Auth.isLoggedIn, function (value, oldValue) {
console.log('value'+value);
console.log('not value'+!value);
console.log('oldValue'+oldValue);
if(!value && oldValue) {
console.log("Disconnect");
$location.path('/login');
}
if(value) {
console.log("Connect");
//Do something when the user is connected
}
}, true);
$rootScope.user = {};
$scope.login = function (username, password) {
if ( username === 'admin' && password === '1234') {
$rootScope.user.name= username;
$rootScope.user.password= password;
Auth.setUser($scope.user);
$location.path( '/home' );
} else {
$scope.loginError = "Invalid username/password combination";
};
};
}]);
app.controller('CountryListCtrl', function ($scope, $http){
$http.get('json/countries.json').success(function(data) {
$scope.countries = data;
});
});
app.controller('CountryDetailCtrl', function ($scope, $routeParams,$location){
console.log('countrName route'+$routeParams.countryName);
$scope.name = $routeParams.countryName;
console.log('countrName $scope.name'+$scope.name);
});
index.html
<!DOCTYPE html>
<html ng-app="plunker">
<head>
<meta charset="utf-8" />
<title>AngularJS Plunker</title>
<link rel="stylesheet" href="css/style.css" />
<script src="js/angular.min.js"></script>
<script src="js/angular-route.min.js"></script>
<script src="js/app.js"></script>
</head>
<body ng-controller="AppCtrl">
<div ng-view></div>
</body>
</html>
Login.html
<h1>Login Page</h1>
<form ng-submit="login(username, password)" class="ng-scope ng-pristine ng-valid">
<label>User name</label>
<input type="text" ng-model="username" class="ng-pristine ng-valid">
<label>Password</label>
<input type="password" ng-model="password" class="ng-pristine ng-valid">
<br/>
{{loginError}} {{loggedUser}}
<br/><br/>
<button class="btn btn-success" ng-click="">Submit</button>
<button class="btn btn-warning" ng-click="cancel()">Cancel</button>
</form>
country-list.html
<h1>Country List</h1>
<div>Welcome :<strong>{{user.name}}</strong></div>
<span class="logout">Logout</span>
<ul>
<li ng-repeat="country in countries">{{country.name}}</li>
</ul>
country-detail.html
<h1>Country Detail</h1>
<h1>{{name}}</h1>
Problem is with CountryDetailCtrl I guess. but cosnole values are coming fine.
Can someone let me know where I am going wrong.
no need in $rootScope here just use one call of
if (!Auth.isLoggedIn()) {
console.log('DENY');
$location.path('/login');
return; // not to execute your controller function further
}
on start of each of you view controllers, that should be protected, "return" will stop execution of controller code written bellow.

AngularJS POST and GET 404 Error

Using AngularJS, I'm trying to post data from a form into an ng-repeat and save to a database. When I click submit, I get the 404 error for post and get. Can someone help show me where I went wrong?
Here's my html:
<html ng-app="Inventory-App">
<head>
<meta charset="utf-8">
<title></title>
<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=0">
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/2.2.3/jquery.js" charset="utf-8"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
<!-- SEMANTIC -->
<link rel="stylesheet" type="text/css" href="../semantic/dist/semantic.min.css">
<script src="../semantic/dist/semantic.min.js"></script>
<!-- MY STUFF -->
<link rel="stylesheet" href="../css/styles.css" media="screen" title="no title" charset="utf-8">
<script src="../scripts/script.js" charset="utf-8"></script>
<script src="../scripts/services/itemsAPI.js" charset="utf-8"></script>
<script src="../scripts/controllers/main.js" charset="utf-8"></script>
<script src="../scripts/app.js" charset="utf-8"></script>
</head>
<body ng-controller="MainController">
<nav>
<h1>Cabinet.me</h1>
<p>An Inventory of Your Kitchen</p>
</nav>
<div class="ui container">
<form class="ui form">
<div class="field">
<label>Item</label>
<input type="text" placeholder="Item" ng-model="post.name">
</div>
<div class="field">
<label>Details (if any)</label>
<input type="text" placeholder="Details" ng-model="post.details">
</div>
<div class="field">
<label>Amount</label>
<select class="ui dropdown" ng-model="post.amount">
<option value="">Amount</option>
<option value="1">High</option>
<option value="1">Medium</option>
<option value="0">Low</option>
</select>
</div>
<button class="ui button" type="submit" ng-click="createItem(post)">Submit</button>
</form>
<div class="ui divider"></div>
<div class="ui cards">
<div class="card" ng-repeat="item in items | orderBy: 'created_at':true">
<div class="content">
<div class="header">{{item.name}}</div>
<div class="meta">Availability: {{item.amount}}</div>
<div class="description">
{{item.details}}
</div>
<button class="ui secondary button">
Delete
</button>
</div>
</div>
</div>
</div>
</body>
</html>
Here's my Controller:
angular
.module('mainController', ['itemsAPI'])
.controller('MainController', ['$scope', '$http', 'itemsAPI',
function( $scope, $http, itemsAPI ) {
$scope.items = [];
// $scope.itemData = '';
$scope.createItem = function(post){
var newItem = {
item : {
name: post.name,
details: post.details,
amount: post.amount
}
}
itemsAPI.create(newItem).then(function(response){
console.log(response);
$scope.items.push(response.data);
})
itemsAPI.getAll().then(function(response){
$scope.items = response.data;
});
}
$scope.removeItem = function(item){
itemsAPI.remove(item._id).then(function(response){
if (response.status == 203) {
$scope.items = $scope.items.filter(function(i){
return i._id != item._id;
});
}
});
}
}]);
Here's the itemsAPI code:
angular
.module('itemsAPI', [])
.factory('itemsAPI', ['$http',
function($http) {
return {
getAll: function(){
return $http.get('/items');
},
create: function(newItem){
return $http.post('/items', newItem);
},
remove: function(id){
return $http.delete('/items/' + id);
}
}
}])
And my API route:
var express = require('express');
var router = express.Router();
var Item = require('../../models/item');
// Get
router.get('/', function(req, res, next) {
Item.find(function(err, items) {
if (err) {
next(err);
}else {
res.json(items);
}
})
});
router.post('/', function(req, res, next) {
Item.create(req.body.item, function(err, item) {
if (err) {
next(err);
}else {
res.json(item);
}
});
});
router.delete('/:id', function(req, res, next) {
Item.findByIdAndRemove(req.params.id, function(err) {
if (err) {
next(err);
}else {
res.status(203).end();
}
})
});
module.exports = router;
I appreciate any help I can get!
Replace this
router.post('/', function(req, res){
with
router.post('/items', function(req, res){
in inventory/server/routes/api/items.js
Edit:
I'm mistaken. You use '/api/items' route in app.js and not necessary to add 'items' path as I wrote above. But on the client side you try to post your data on the '/items' route not on '/api/items'.

simple routing in angularjs

I have the following two files in Angular, wanting to create a simple Login application. The first one is Login.html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title> AngularJS Login SPA</title>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.5/angular.min.js"></script>
<script src="angular-route.min.js"></script>
<script src="controller.js"></script>
</head>
<body ng-app="mainApp">
<div ng-controller="loginCtrl">
<form action="/" id="myLogin">
Username: <input type="text" name="username" id="username" ng-model="username"><br/>
Password: <input type="password" name="password" id="password" ng-model="password"><br/>
<button type="button" ng-click="submit()">Login</button>
</form>
</div>
</body>
</html>
and the second one is controller.js:
var app = angular.module("mainApp", ['ngRoute']);
app.config(function($routeProvider) {
$routeProvider
.when ('/', {
templateUrl: 'login.html'
})
.when ('#/dashboard',{
resolve:{
"check":function($location, $rootScope){
if (!$rootScope.loggedIn)
{
$location.path('/dashboard');
}
else{
}
}
},
templateUrl: 'dashboard.html'
})
.otherwise ({
redirectTo: '/'
})
});
app.controller('loginCtrl', function($scope, $location, $rootScope){
$scope.submit = function(){
if($scope.username == 'admin' && $scope.password == 'admin')
{
$rootScope.uname = $scope.username;
$rootScope.password = $scope.password;
$rootScope.loggedIn = true;
$location.path('/dashboard');
}
else{
alert('wrong stuff');
}
};
});
The thing is after I succesfully enter the texts 'admin' and 'admin' on username and password (if I click otherwise it correctly shows me an alert), the address changes to .../index.html#/dashboard but it doesn't load me the page dashboard.html, a simple page I created for this app, located in the same folder where index.html is.
Any idea on how it can show me dashboard.html after I succesfully login with the two texts?
Any help could be highly appreciated.
I found out what was the problem.
I had to test the application in Mozilla because Google Chrome doesn't support SPAs (Single Page Applications) that can match a running server.

Resources