How to Build an AngularJS Single-page App for Login with Authentication

Abhigyan Singh 12th Jul 2020

AngularJS is one of the most famous front-end development frameworks preferred by developers these days. It makes easier to develop single page application containing dynamic contents without any hurdle. In this article, I’m going to develop a simple sign-in application containing common fields- username and password for making a login. For those who have just landed their development journey over the Angular, it might be typical to understand. They can learn AngularJS with best Angular Course accessible over the internet. Thus, they can explore this cool framework from the basic to an advanced level developing an application in the end. Now let’s learn how to develop a simple login page with AngularJS.

Directory Structure:

  • Index.js
  • mainPage.html
  • appController.js
  • app.html
  • app.html
  • login.html
  • loginController.js
  • service.js
  • style.css

This directory makes you understand our whole app structure. It includes login, home and its controller.

Suppose a user provides the basic username and password details and click on the sign in button, the credentials will be authenticated through the service.js program. Once successfully authenticated, it will redirect to the main home page written below in mainPage.js file. If the provided credentials are wrong it will show an error message ‘incorrect username/password!’

If authentication fails, he will be blocked on the login page notifying with an error message and the user will be asked to enter correct credentials. Here below, I’m describing the role of all these files.

app.html

app.html is the starting point of our application. It will load all the views. All the enclosed scripts for executing application will load here.

<!doctype html>
<html ng-app="newApp" >
<head>
<meta charset="utf-8">
<title>
Sample Login App
</title>
<script>
document.write('<base href="' + document.location + '" />');
</script>
<link href="//netdna.bootstrapcdn.com/twitter-bootstrap/2.3.1/css/bootstrap-combined.min.css" rel="stylesheet">
<link rel="stylesheet" href="style.css">
<script src="https://code.angularjs.org/1.2.13/angular.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/angular-ui-router/0.2.8/angular-ui-router.min.js">
</script>

<script src="index.js"></script>
<script src="loginController.js"></script>
<script src="appController.js"></script>
<script src="Service.js"></script>
</head>
<body>
<div class="container" width="120px">
<h2>
Angular Sample Login
</h2>
<div ui-view></div>
</div>

</body>
</html>

Index.js :

We require a JS file to keep all the information about routes and other configurations for running this application. All the routes are configured through UI routers used in the program. The code for index.js is:

(function()
{
var app = angular.module('newApp', ['ui.router']);

app.run(function($rootScope, $location, $state, LoginTest)
{
console.clear();
console.log('executing');
if(!LoginTest.isAuthenticated())
{
$state.transitionTo('login');
}
});

app.config(['$stateProvider', '$urlRouterProvider',
function($stateProvider, $urlRouterProvider)
{
$stateProvider
.state('login', {
url : '/login',
templateUrl : 'login.html',
controller : 'loginController'
})
.state('mainPage', {
url : '/mainPage',
templateUrl : 'mainPage.html',
controller : 'appController'
});

$urlRouterProvider.otherwise('/login');
}]);

})();

login.html :

Now we need to load views for the main page. So we require login page with required credentials field where a user will provide the input and press login button.

<div class="col-md-12">
<p><strong>Login Page</strong></p>

<form ng-submit="formSubmit()" class="form">
<div class="col-md-4">
<div class="form-group">
<input type="text" class="form-control" ng-model="username" placeholder="username" required=""/>
</div>

<div class="form-group">
<input type="password" class="form-control" ng-model="password" placeholder="password" required=""/>
</div>

<div class="form-group">
<button type="submit" class="btn btn-success">Login</button>
<span class="text-danger" style="color:red">{{ error }}</span>
</div>

</div>
</form>
</div>

loginController.js :

Now, its time to implement our business logic through the controller. It is the javascript document for dealing with the login.html functionalities.

var app = angular.module('newApp');
app.controller('LoginController', function($scope, $rootScope, $stateParams, $state, LoginTest) {
$rootScope.title = "Sample Login App";

$scope.formSubmit = function()
{
if(LoginService.login($scope.username, $scope.password))
{
$rootScope.userName = $scope.username;
$scope.error = '';
$scope.username = '';
$scope.password = '';
$state.transitionTo('mainPage');
}
else
{
$scope.error = "Incorrect username/password !";
} };
});

mainPage.html :

Now is the time to design our main page where a user will fall after the successful login. It contains a statement saying welcome here, the user’s name and a logout button.

<div class="col-md-12" style="width:500px;">
<div align="right"><a ui-sref="login">Logout</a></div>
<h4>Welcome {{user}}! </h4>
<p><strong>Welcome Here</strong></p>
</div>

Controller.js :

Now we need to create a controller for handling our main page. We will call it controller.js here. It will handle the functionalities of the main page.

var app = angular.module('newApp');

app.controller('Controller',
function($scope, $rootScope, $stateParams, $state, Service) {
$scope.user = $rootScope.userName;

});

Service.js :

As we are keeping user credential through a scope object binding it with a variable. We need to authenticate these details once after the user press a login button. We are using service.js file for dealing with authentication which is shown below. We require a database server for authenticating these provided credentials of a user.

var app = angular.module('newApp');
  
  app.factory('Service', function() {
    var admin = 'admin';
    var pass = 'password';
    var isAuthenticated = false;
    
    return {
      login : function(username, password) {
        isAuthenticated = username === admin && password === pass;
        return isAuthenticated;
      },
      isAuthenticated : function() {
        return isAuthenticated;
      }
    };
    
  });

Now, is the time for final execution. Start your server and connect it with the database. Rest is assured- you got your login page running without any hurdle.

Authored By Abhigyan Singh

He is a continuous blogger and has blogged on different topic. He loves to surf Internet and always trying to get new Idea about new Technology and Innovations and sharing these great information to all the technology lovers.

ALSO ON DISCUSS DESK