User Registration & Login Example Tutorial

User Registration & Login Example Tutorial
COMMENTS ()
Tweet

Hey Guys,

In my previous post I showed you how to create a Todo Application in Angular JS.

In this tutorial I’ll show you how to develop a User Registration & Login application using AngularJS. We’ll be using the PHP Silex Framework here to create a REST API. The data from that REST API will be used for user sign-up and user authentication.

Tutorial

You can also download a zipped version of the source code used from this link 

Live Demo

A video demo of this tutorial is available here Live Demo

To run the User Registration & Login application on your local machine, follow the following 2 simple steps.

In this tutorial, we’ll first create the login form which will be authenticated using the user credentials stored in our MySQL database. On successful login, the form will redirect to the welcome page. Upon unsuccessful login or logout, the app will redirect the user to the login page. After the login form, we will develop the User Sign-up Form that takes certain data fields as input, to create a new user. We will be using the AngularJS-Toaster plugin to display messages to the user in this case. In the last part of this tutorial, I’ll show you how to setup the REST API for the application.

Below are the steps that will help you to create your first Angular JS Registration & Login application.

STEP 1: SETUP THE ANGULAR JS PROJECT STRUCTURE

There are many ways one can define the folder structure for Angular JS. I personally found it easier to follow the conventional web project directory structure, which is what I have used in this tutorial as well. Here’s what the web project directory structure looks like:

shopify

 

STEP 2: SETUP the ANGULAR JS APPLICATION (app/app.js)

This is the starting point of our Angular JS application. In this step, we will load the modules and configure the route provider (as shown in the snippet below).

var app = angular.module('authenticationApp', ['ngRoute', 'ngAnimate', 'toaster']);

app.config(['$routeProvider',
  function ($routeProvider) {
        $routeProvider.
        when('/login', {
            title: 'Login',
            templateUrl: 'views/login.html',
            controller: 'login'
        })
            .when('/logout', {
                title: 'Logout',
                templateUrl: 'views/login.html',
                controller: 'login'
            })
            .when('/signup', {
                title: 'Signup',
                templateUrl: 'views/signup.html',
                controller: 'signup'
            })
            .when('/dashboard', {
                title: 'Dashboard',
                templateUrl: 'views/dashboard.html',
                controller: 'dashboard'
            })
            .when('/', {
                title: 'Login',
                templateUrl: 'views/login.html',
                controller: 'login',
                role: '0'
            })
            .otherwise({
                redirectTo: '/login'
            });
  }]);

 

In the code snippet above, we have initialized the Angular JS app named “authenticationApp” and injected some other modules like ngRoute,toaster etc. Then, using the route provider we have defined the routes for different URLs and also defined that that login form will be using login.html as the template and its controller will be login.

STEP 3: SETUP ANGULAR JS RESTAPI SERVICE (app/restapi.js)

In this step we will setup the Angular JS RESTAPI service. As you may know, the services in an Angular JS application can be accessed throughout the application in any controller. And since Angular JS services are single-tone, their defined properties and functions can be accessed from anywhere. In this case, we’ll use the RestApiClientService to communicate with the server API (as shown in the code snippet below). This API has both POST and GET functionalities exposed.

app.factory("RestApiClientService", ['$http', 'toaster',
    function ($http, toaster) { // This service connects to our REST API

        var serviceBase = 'api/v1/web/index.php/';

        var obj = {};
        obj.toast = function (data) {
            toaster.pop(data.status, "", data.message, 10000, 'trustedHtml');
        }
        obj.get = function (q) {
            return $http.get(serviceBase + q).then(function (results) {
                return results.data;
            });
        };
        obj.post = function (q, object) {

            obj.post = function (q, object) {
                return $http.post(serviceBase + q, object).then(function (results) {
                    return results.data;
                },function(results){

                    var err = {status:"error",message:"An Internal Error Occured"};
                    return err;
                });
            };
        };

        obj.put = function (q, object) {
            return $http.put(serviceBase + q, object).then(function (results) {
                return results.data;
            });
        };
        obj.delete = function (q) {
            return $http.delete(serviceBase + q).then(function (results) {
                return results.data;
            });
        };

        return obj;
}]);

 

STEP 4: SETUP ANGULAR JS CONTROLLERS (controllers/login.js, controllers/signup.js)

Next, we’ll setup the Angular JS Controllers, since these controllers are used to communicate with the views. The login and sign-up controllers (we have used below) are used in their respective views to get the form data inside the controller on form submission. The controllers will post the form data to the server and will then display the respective Success or Error message to the user.

Login.js

/*
 * Login Controller
 */
app.controller('login', function ($scope, $rootScope, $routeParams, $location, $http, RestApiClientService) {

    //initially set those objects to null to avoid undefined error
    $scope.login = {};

    $scope.doLogin = function (customer) {
        RestApiClientService.post('login', {
            customer: customer
        }).then(function (results) {
            RestApiClientService.toast(results);
            if (results.status == "success") {
                $location.path('dashboard');
            }
        });
    };
});

 

SignUp.js

/*
 * SignUp Controller
 */
app.controller('signup', function ($scope, $rootScope, $routeParams, $location, $http, RestApiClientService) {

    $scope.signup = {};

    $scope.signup = {email:'',password:'',name:'',phone:'',address:''};

    $scope.signUp = function (customer) {
        RestApiClientService.post('signup', {
            customer: customer
        }).then(function (results) {
            RestApiClientService.toast(results);
            if (results.status == "success") {
                $location.path('dashboard');
            }
        });
    };

});

 

As you can see, the RestApiClientService we have created in  STEP 3 (above) has been injected in the controllers to communicate with the server API.

STEP 5: SETUP THE VIEWS (index.html,views/login.html,views/signup.html)

index.html

This is the main file of our application so, in this file we will be including all the .js and .css files.

login.html

The Login View (below) contains a small form with the usual fields for email and password input.

<form name="loginForm" class="form-horizontal" role="form" style="padding-top:20px;">
    <div class="form-group">
        <label class="col-sm-3 control-label no-padding-right" for="email"> Email</label>
        <div class="col-sm-7">
           <span class="block input-icon input-icon-right">
                <input type="text" class="form-control" placeholder="Email" name="email" ng-model="login.email" required focus/>
                <i class="ace-icon fa fa-user"></i>
            </span>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-3 control-label no-padding-right" for="password"> Password </label>
        <div class="col-sm-7">
           <span class="block input-icon input-icon-right">
                <input type="password" class="form-control" placeholder="Password" ng-model="login.password" required/>
                <i class="ace-icon fa fa-lock"></i>
            </span>
        </div>
    </div>
    <div class="space"></div>
     <div class="clearfix">
                                        <div class="row">
         <label class="col-sm-3 control-label no-padding-right"> </label>
        <div class="col-sm-7">
            <button type="submit" class="width-35 pull-right btn btn-sm btn-primary" ng-click="doLogin(login)" data-ng-disabled="loginForm.$invalid">
                <i class="ace-icon fa fa-key"></i>
                Login
            </button>
                                            </div>
        </div>
    </div>
        <div class="space-4"></div>
<span class="lbl col-sm-3"> </span><div class="col-sm-7">Don't have an account? <a href="#/signup">Signup</a></div>
</form>

 

signup.html

The Sign-up View also contains a small form with the usual fields for email and password input by the user.

<form name="signupForm" class="form-horizontal" role="form" style="padding-top: 20px;">
    <div class="form-group">
        <label class="col-sm-5 control-label no-padding-right" for="email">Email</label>
        <div class="col-sm-7">
            <span class="block input-icon input-icon-right">
                <input type="text" class="form-control" placeholder="Email" name="email" ng-model="signup.email" focus/>
                <span ng-show="signupForm.email.$error.email" class="help-inline">Email is not valid</span> 
            </span>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-5 control-label no-padding-right" for="password">Password</label>
        <div class="col-sm-7">
            <span class="block input-icon input-icon-right">
        <input type="password" class="form-control" name = "password" placeholder="Password" ng-model="signup.password" required/>
        <small class="errorMessage" data-ng-show="signupForm.password.$dirty && signupForm.password.$invalid"> Enter Password.</small>
    </span>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-5 control-label no-padding-right" for="password2">Confirm Password</label>
        <div class="col-sm-7">
            <span class="block input-icon input-icon-right">
        <input type="password" class="form-control" name="password2" placeholder="Password Again" ng-model="signup.password2" password-match="signup.password" required/>                                
        <small class="errorMessage" data-ng-show="signupForm.password2.$dirty && signupForm.password2.$error.required"> Enter password again.</small>

       <small class="errorMessage" data-ng-show="signupForm.password2.$dirty && signupForm.password2.$error.passwordNoMatch && !signupForm.password2.$error.required"> Password do not match.</small>

    </span>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-5 control-label no-padding-right" for="name">Name</label>
        <div class="col-sm-7">
            <span class="block input-icon input-icon-right">
        <input type="text" class="form-control" placeholder="Name" ng-model="signup.name" />
    </span>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-5 control-label no-padding-right" for="phone">Phone</label>
        <div class="col-sm-7">
            <span class="block input-icon input-icon-right">
        <input type="text" class="form-control" placeholder="Phone" name="phone" ng-model="signup.phone"/>
    </span>
        </div>
    </div>
    <div class="form-group">
        <label class="col-sm-5 control-label no-padding-right" for="address">Address</label>
        <div class="col-sm-7">
            <span class="block input-icon input-icon-right">
        <input type="text" class="form-control" placeholder="Address" ng-model="signup.address" />
    </span>
        </div>
    </div>
    <div class="form-group">
        <span class="lbl col-sm-5"> </span>
        <div class="col-sm-7">
            <button type="submit" class="width-35 pull-right btn btn-sm btn-primary" ng-click="signUp(signup)" data-ng-disabled="signupForm.$invalid">
                Sign Up
            </button>
        </div>
    </div>
    </fieldset>
    <span class="lbl col-sm-5"> </span>
    <div class="col-sm-7">Already have an account? <a href="#/login">SignIn</a>
    </div>
</form>

 

STEP 6 – SETUP THE SERVER API

All the API files required to create the REST API are already placed inside the “API” directory. The only file you’ll need to change is the “config.php” file (this file contains the database login information, so you’ll need to put your database credentials here)

<?php
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');
define('DB_HOST', 'localhost');
define('DB_NAME', 'angularcode_demo');
?>

 

Also, we’ll need to import the “script.sql” file into our MySQL database (as shown below).

CREATE TABLE IF NOT EXISTS `user` (
  `id` INT(11) NOT NULL AUTO_INCREMENT,
  `name` VARCHAR(50) NOT NULL,
  `email` VARCHAR(50) NOT NULL,
  `phone` VARCHAR(100) NOT NULL,
  `password` VARCHAR(200) NOT NULL,
  `address` VARCHAR(50) NOT NULL,
  `created` TIMESTAMP NOT NULL DEFAULT CURRENT_TIMESTAMP,
  PRIMARY KEY (`id`)
) ENGINE=INNODB  DEFAULT CHARSET=latin1 AUTO_INCREMENT=1 ;

 

Wrapping Up

In this tutorial we have learned how to create aUser Registration & Login Application using Angular JS. If you successfully completed the tutorial, you have used the PHP Silex Framework to create a REST API and an end to end application, in which you have saved the user’s details from an Angular JS sign-up form to a MySQL database and also authenticated the logged-in user.

A video demo of this tutorial is available here Live Demo. You can also download a zipped version of the source code used from this link link 

In the next tutorial we will learn how to use Angular JS Grid with Paging,Sorting,Filtering.

CALL

USA408 365 4638

VISIT

1301 Shoreway Road, Suite 160,

Belmont, CA 94002

Contact us

Whether you are a large enterprise looking to augment your teams with experts resources or an SME looking to scale your business or a startup looking to build something.
We are your digital growth partner.

Tel: +1 408 365 4638
Support: +1 (408) 512 1812