Angular JS Simple Login using Ui-Router

Getting Started

I've used CDN for Bootstrap, Angular JS and Ui-Router so you need internet connection for them to work.

Creating our Database

First we are going to create our MySQL Database and insert user data that we are going to use in this tutorial. 1. Open phpMyAdmin. 2. Click databases, create a database and name it as angular. 3. After creating a database, click the SQL and paste the below codes. See image below for detailed instruction.
  1. CREATE TABLE `members` (
  2. `memid` int(11) NOT NULL AUTO_INCREMENT,
  3. `username` varchar(30) NOT NULL,
  4. `password` varchar(30) NOT NULL,
  5. `firstname` varchar(30) NOT NULL,
  6. `lastname` varchar(30) NOT NULL,
  7. `address` text NOT NULL,
  8. PRIMARY KEY(`memid`)
  1. INSERT INTO `members` (`memid`, `username`, `password`, `firstname`, `lastname`, `address`) VALUES
  2. (1, 'neovic', 'devierte', 'Neovic', 'Devierte', 'Silay City'),
  3. (2, 'julyn', 'divinagracia', 'Julyn', 'Divinagracia', 'E.B. Magalona'),
  4. (3, 'gemalyn', 'cepe', 'Gemalyn', 'Cepe', 'Bohol');
database sql

index.html

This is the main view of our app. In here, we have declared all our dependencies and the javascripts that we have created.
  1. <!DOCTYPE html>
  2. <html ng-app="app">
  3. <meta charset="utf-8">
  4. <title>Angular JS Simple Login using Ui-Router</title>
  5. <link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
  6. <script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
  7. <script src="https://cdnjs.cloudflare.com/ajax/libs/angular-ui-router/1.0.3/angular-ui-router.min.js"></script>
  8. </head>
  9. <div class="container">
  10. <h1 class="page-header text-center">Angular JS Simple Login using Ui-Router</h1>
  11. <div ui-view></div>
  12. </div>
  13. <!-- Main Angular Script -->
  14. <script src="js/app.js"></script>
  15. <!-- Controllers -->
  16. <script src="js/controllers/loginCtrl.js"></script>
  17. <script src="js/controllers/homeCtrl.js"></script>
  18. <!-- Services -->
  19. <script src="js/services/loginService.js"></script>
  20. <script src="js/services/sessionService.js"></script>
  21. </body>
  22. </html>

login.html

This template contains our login form and can be considered as the index view of our app.
  1. <div class="col-md-4 col-md-offset-4">
  2. <div class="login-panel panel panel-primary">
  3. <div class="panel-heading">
  4. <h3 class="panel-title"><span class="glyphicon glyphicon-lock"></span> Login
  5. </h3>
  6. </div>
  7. <div class="panel-body">
  8. <form name="logform" ng-submit="login()">
  9. <div class="form-group">
  10. <input class="form-control" placeholder="Username" type="text" autofocus ng-model="user.username" required>
  11. </div>
  12. <div class="form-group">
  13. <input class="form-control" placeholder="Password" type="password" ng-model="user.password" required>
  14. </div>
  15. <button type="submit" class="btn btn-lg btn-primary btn-block" ng-disabled="logform.$invalid"><span class="glyphicon glyphicon-log-in"></span> Login</button>
  16. </form>
  17. </div>
  18. </div>
  19.  
  20. <div class="alert alert-danger text-center" ng-show="errorLogin">
  21. <button type="button" class="close" ng-click="clearMsg()"><span aria-hidden="true">&times;</span></button>
  22. {{ errorMsg }}
  23. </div>
  24. </div>

home.html

This is our landing page for a successful login and shows the user that logged into our app.
  1. <div class="row">
  2. <div class="col-md-4 col-md-offset-4">
  3. <h2>Welcome to Homepage </h2>
  4. <h4>User Info:</h4>
  5. <p>Firstname: {{ user.firstname }}</p>
  6. <p>Lastname: {{ user.lastname }}</p>
  7. <p>Address: {{ user.address }}</p>
  8. <p>Username: {{ user.username }}</p>
  9. <p>Password: {{ user.password }}</p>
  10. <a href="" class="btn btn-danger" ng-click="logout()"><span class="glyphicon glyphicon-log-out"></span> Logout</a>
  11. </div>
  12. </div>

app.js

This is the main angular js script of our app where we assign our app name and the routes of our app.
  1. var app = angular.module('app', ['ui.router']);
  2.  
  3. app.config(function($stateProvider, $urlRouterProvider) {
  4.  
  5. $urlRouterProvider.otherwise('/login');
  6.  
  7. $stateProvider
  8.  
  9. .state('login', {
  10. url: '/login',
  11. templateUrl: 'login.html',
  12. controller: 'loginCtrl'
  13. })
  14.  
  15. .state('home', {
  16. url: '/home',
  17. templateUrl: 'home.html',
  18. controller: 'homeCtrl'
  19. })
  20.  
  21. });

loginCtrl.js

This is the controller for our login.html template.
  1. 'use strict';
  2.  
  3. app.controller('loginCtrl', function($scope, loginService, $location){
  4. //redirect back to home if user is logged in
  5. var connected = loginService.islogged();
  6. connected.then(function(response){
  7. if(response.data == 'true'){
  8. $location.path('/home');
  9. }
  10. });
  11.  
  12. $scope.errorLogin = false;
  13.  
  14. $scope.login = function(){
  15. loginService.login($scope.user, $scope);
  16. }
  17.  
  18. $scope.clearMsg = function(){
  19. $scope.errorLogin = false;
  20. }
  21. });

homeCtrl.js

This is the controller for our home.html template.
  1. 'use strict';
  2.  
  3. app.controller('homeCtrl', function($scope, loginService, $location){
  4. //redirect user if not loggedin
  5. var connected = loginService.islogged();
  6. connected.then(function(response){
  7. if(response.data == 'false'){
  8. $location.path('/login');
  9. }
  10. });
  11.  
  12. //logout
  13. $scope.logout = function(){
  14. loginService.logout();
  15. }
  16.  
  17. //fetch login user
  18. var userrequest = loginService.fetchuser();
  19. userrequest.then(function(response){
  20. $scope.user = response.data[0];
  21. });
  22.  
  23. });

loginService.js

This is our service that is responsible for our request relating to login members.
  1. 'use strict';
  2.  
  3. app.factory('loginService', function($http, $location, sessionService){
  4. return{
  5. login: function(user, $scope){
  6. var validate = $http.post('login.php', user);
  7. validate.then(function(response){
  8. var uid = response.data.user;
  9. if(uid){
  10. sessionService.set('user',uid);
  11. $location.path('/home');
  12.  
  13. }
  14.  
  15. else{
  16. $scope.successLogin = false;
  17. $scope.errorLogin = true;
  18. $scope.errorMsg = response.data.message;
  19. }
  20. });
  21. },
  22. logout: function(){
  23. sessionService.destroy('user');
  24. $location.path('/login');
  25. },
  26. islogged: function(){
  27. var checkSession = $http.post('session.php');
  28. return checkSession;
  29. },
  30. fetchuser: function(){
  31. var user = $http.get('fetch.php');
  32. return user;
  33. }
  34. }
  35. });

sessionService.js

This is our service that is responsible for the sessions in our app both for local storage session and PHP session.
  1. 'use strict';
  2.  
  3. app.factory('sessionService', function($http){
  4. return{
  5. set: function(key, value){
  6. return sessionStorage.setItem(key, value);
  7. },
  8. get: function(key){
  9. return sessionStorage.getItem(key);
  10. },
  11. destroy: function(key){
  12. $http.post('logout.php');
  13. return sessionStorage.removeItem(key);
  14. }
  15. };
  16. });

login.php

This is our PHP api that checks the user that logged into our app.
  1. <?php
  2.  
  3.  
  4. $conn = new mysqli("localhost", "root", "", "angular");
  5.  
  6. if ($conn->connect_error) {
  7. die("Connection failed: " . $conn->connect_error);
  8. }
  9.  
  10. $out = array('error' => false);
  11.  
  12. $user = json_decode(file_get_contents('php://input'));
  13.  
  14. $username = $user->username;
  15. $password = $user->password;
  16.  
  17. $sql = "SELECT * FROM members WHERE username='$username' AND password='$password'";
  18. $query = $conn->query($sql);
  19.  
  20. if($query->num_rows>0){
  21. $row = $query->fetch_array();
  22. $out['message'] = 'Login Successful';
  23. $out['user'] = uniqid('ang_');
  24. $_SESSION['user'] = $row['memid'];
  25. }
  26. else{
  27. $out['error'] = true;
  28. $out['message'] = 'Invalid Login';
  29. }
  30.  
  31. echo json_encode($out);
  32.  
  33. ?>

session.php

This is our PHP api that checks for PHP session.
  1. <?php
  2. if(isset($_SESSION['user'])){
  3. echo 'true';
  4. }
  5. else{
  6. echo 'false';
  7. }
  8. ?>

fetch.php

This is our PHP api that fetches logged in user details.
  1. <?php
  2.  
  3. $conn = new mysqli("localhost", "root", "", "angular");
  4.  
  5. $output = array();
  6. $sql = "SELECT * FROM members WHERE memid = '".$_SESSION['user']."'";
  7. $query=$conn->query($sql);
  8. while($row=$query->fetch_array()){
  9. $output[] = $row;
  10. }
  11.  
  12. echo json_encode($output);
  13. ?>

logout.php

Lastly, this is our PHP api that destroys our current user PHP session. That ends this tutorial. Happy Coding :)

Add new comment