Add full login functionality

Change-Id: I33a9df05b2cad2015c7ccd16580b560d85aefe13
Signed-off-by: Iftekharul Islam <iislam@us.ibm.com>
diff --git a/src/js/app.js b/src/js/app.js
index f19efae..7ba15cd 100644
--- a/src/js/app.js
+++ b/src/js/app.js
@@ -37,6 +37,10 @@
         'redirectTo': '/login'
       });
  }])
+ .config(['$httpProvider', function($httpProvider){
+     //console.log($httpProvider.interceptors);
+     $httpProvider.interceptors.push('apiInterceptor');
+ }])
  .run(['$rootScope', '$location', 'dataService', 'userModel',
     function($rootScope, $location, dataService, userModel){
     $rootScope.dataService = dataService;
@@ -71,5 +75,10 @@
             dataService.showNavigation = false;
         }
     });
+
+    $rootScope.$on('timedout-user', function(){
+      sessionStorage.removeItem('LOGIN_ID');
+      $location.path('/login');
+    });
     }
  ]);
diff --git a/src/js/controllers.js b/src/js/controllers.js
index 1c2dd82..03318e4 100644
--- a/src/js/controllers.js
+++ b/src/js/controllers.js
@@ -10,15 +10,21 @@
     }; 
     $scope.login = function(username, password){
         $scope.error = false;
+
         if(!username || username == "" ||
            !password || password == ""){
             return false;
         }else{
-            if(userModel.login(username, password)){
-                $window.location.hash = '#/system-overview';
-            }else{
-                $scope.error = true;
-            }
+            userModel.login(username, password, function(status, unreachable){
+                if(status){
+                    $scope.$emit('user-logged-in',{});
+                    $window.location.hash = '#/system-overview';
+                }else{
+                    if(!unreachable){
+                       $scope.error = true;
+                   }
+               };
+            });
         }
     }
  }])
@@ -75,34 +81,25 @@
     };
     $scope.warmReboot = function(){
         //@TODO:show progress
-        dataService.loading = true;
+        dataService.setBootingState();
         APIUtils.hostPowerOff(function(response){
             if(response){
-                dataService.setPowerOffState();
                 APIUtils.hostPowerOn(function(response){
                     if(response){
                         dataService.setPowerOnState();
                     }else{
                         //@TODO:show error message
                     }
-                    //@TODO:hide progress, set proper server state
-                    dataService.loading = false;
                 });
             }else{
-                //@TODO:hide progress & show error message
-                dataService.loading = false;
             }
         });
     };
     $scope.testState = function(){
-        //@TODO:show progress
-        dataService.loading = true;
-
         $timeout(function(){
             dataService.setPowerOffState();
             $timeout(function(){
                 dataService.setPowerOnState();
-                dataService.loading = false;
             }, 2000);
         }, 1000);
     };
@@ -127,14 +124,12 @@
 
     $scope.orderlyShutdown = function(){
         //@TODO:show progress
-        dataService.loading = true;
         APIUtils.hostPowerOff(function(response){
             if(response){
                 dataService.setPowerOffState();
             }else{
                 //@TODO:hide progress & show error message
             }
-            dataService.loading = false;
         });
     };
     $scope.orderlyShutdownConfirm = function(){
diff --git a/src/js/directives.js b/src/js/directives.js
index 913d686..801f67d 100644
--- a/src/js/directives.js
+++ b/src/js/directives.js
@@ -10,35 +10,44 @@
         'scope': {
             'path': '='
         },
-        'controller': ['$scope','dataService', 'userModel', '$location', function($scope, dataService, userModel, $location){
-            $scope.server_status = 01;
+        'controller': ['$rootScope', '$scope','dataService', 'userModel', '$location', function($rootScope, $scope, dataService, userModel, $location){
             $scope.dataService = dataService;
 
             $scope.loadServerStatus = function(){
-                $scope.dataService.loading = true;
-                APIUtils.login(function(){
-                    APIUtils.getHostState(function(status){
-                        if(status == 'xyz.openbmc_project.State.Host.HostState.Off'){
-                            dataService.setPowerOffState();
-                        }else if(status == 'xyz.openbmc_project.State.Host.HostState.Running'){
-                            dataService.setPowerOnState();
-                        }else{
-                            dataService.setBootingState();
-                        }
-                        dataService.loading = false;
-                    });
+
+                APIUtils.getHostState(function(status){
+                    if(status == 'xyz.openbmc_project.State.Host.HostState.Off'){
+                        dataService.setPowerOffState();
+                    }else if(status == 'xyz.openbmc_project.State.Host.HostState.Running'){
+                        dataService.setPowerOnState();
+                    }else{
+                        dataService.setBootingState();
+                    }
                 });
             }
             $scope.loadServerStatus();
 
             $scope.logout = function(){
-                userModel.logout();
-                $location.path('/logout');
-            };
+                userModel.logout(function(status, error){
+                    if(status){
+                       $location.path('/logout');
+                    }else{
+                        console.log(error);
+                    }
+                });
+            }
 
             $scope.refresh = function(){
                 $scope.loadServerStatus();
             }
+
+            var loginListener = $rootScope.$on('user-logged-in', function(event, arg){
+                $scope.loadServerStatus();
+            });
+
+            $scope.$on('$destroy', function(){
+                loginListener();
+            });
         }]
     };
  }])
@@ -53,8 +62,7 @@
         },
         'controller': ['$scope', 'dataService', function($scope, dataService){
             $scope.$watch('showNavigation', function(){
-                var paddingTop = 0;
-                $scope.toggle = false;
+                var padingTop = 0;
                 $scope.firstLevel = 'overview';
                 $scope.secondLevel = 'system_overview';
                 if($scope.showNavigation){
@@ -63,7 +71,6 @@
                 dataService.bodyStyle = {'padding-top': paddingTop + 'px'};
                 $scope.navStyle = {'top': paddingTop + 'px'};
             });
-
         }]
     };
  })
@@ -92,7 +99,7 @@
             scope.$watch('confirm', function(){
                 if(scope.confirm){
                     $timeout(function(){
-                        angular.element(e[0].parentNode).css({'min-height': e[0].querySelector('.inline__confirm').offsetHeight + 'px'});
+                        angular.element(e[0].parentNode).css({'min-height': e[0].querySelector('.power__confirm').offsetHeight + 'px'});
                     }, 0);
                 }else{
                     angular.element(e[0].parentNode).css({'min-height': 0+ 'px'});
diff --git a/src/js/services.js b/src/js/services.js
index dbf8dc4..23bfffb 100644
--- a/src/js/services.js
+++ b/src/js/services.js
@@ -10,52 +10,50 @@
 **/
 angular
  .module('app.services', [])
- .service('dataService', ['APIUtils', function(APIUtils){
-    this.app_version = "openBMC V.0.0.1";
-    this.server_health = 'Error';
-    this.server_state = 'Unreachable';
-    this.server_status = -2;
-    this.chassis_state = 'On';
-    this.server_id = "Server 9.3.164.147";
-    this.last_updated = new Date();
-    
-    this.loading = false;
-    this.loading_message = "";
-    this.showNavigation = false;
-    this.bodyStyle = {};
-    this.path = '';
+ .service('apiInterceptor', ['$q', '$rootScope', 'dataService', function($q, $rootScope, dataService){
+    return {
+        'request': function(config){
+            dataService.server_unreachable = false;
+            dataService.loading = true;
+            return config;
+        },
+        'response': function(response){
+            dataService.loading = false;
+            dataService.last_updated = new Date();
 
-    this.setPowerOnState = function(){
-        this.server_state = APIUtils.HOST_STATE_TEXT.on;
-        this.server_status = APIUtils.HOST_STATE.on;
-    },
+            if(response == null){
+                dataService.server_unreachable = true;
+            }
 
-    this.setPowerOffState = function(){
-        this.server_state = APIUtils.HOST_STATE_TEXT.off;
-        this.server_status = APIUtils.HOST_STATE.off;
-    },
+            if(response && response.status == 'error' &&
+               dataService.path != '/login'){
+                $rootScope.$emit('timedout-user', {});
+            }
 
-    this.setBootingState = function(){
-        this.server_state = APIUtils.HOST_STATE_TEXT.booting;
-        this.server_status = APIUtils.HOST_STATE.booting;
-    },
-
-    this.setUnreachableState = function(){
-        this.server_state = APIUtils.HOST_STATE_TEXT.unreachable;
-        this.server_status = APIUtils.HOST_STATE.unreachable;
-    }
+            return response;
+        },
+        'responseError': function(rejection){
+            dataService.server_unreachable = true;
+            dataService.loading = false;
+            return $q.reject(rejection);
+        }
+    };
  }])
- .factory('APIUtils', ['$http', function($http){
-    var SERVICE = {
+ .service('Constants', function(){
+    return {
         LOGIN_CREDENTIALS: {
-            username: "root",
-            password: "0penBmc",
+            username: "test",
+            password: "testpass",
         },
         API_CREDENTIALS: {
-            user: 'root',
-            password: '0penBmc',
             host: 'https://9.3.164.147'
         },
+        API_RESPONSE: {
+            ERROR_STATUS: 'error',
+            ERROR_MESSAGE: '401 Unauthorized',
+            SUCCESS_STATUS: 'ok',
+            SUCCESS_MESSAGE: '200 OK'
+        },
         CHASSIS_POWER_STATE: {
             on: 'On',
             off: 'Off'
@@ -71,7 +69,53 @@
             off: -1,
             booting: 0,
             unreachable: -2
-        },
+        }
+    };
+ })
+ .service('dataService', ['Constants', function(Constants){
+    this.app_version = "openBMC V.0.0.1";
+    this.server_health = 'Error';
+    this.server_state = 'Unreachable';
+    this.server_status = -2;
+    this.chassis_state = 'On';
+    this.server_id = "Server 9.3.164.147";
+    this.last_updated = new Date();
+
+    this.loading = false;
+    this.server_unreachable = false;
+    this.loading_message = "";
+    this.showNavigation = false;
+    this.bodyStyle = {};
+    this.path = '';
+
+    this.setPowerOnState = function(){
+        this.server_state = Constants.HOST_STATE_TEXT.on;
+        this.server_status = Constants.HOST_STATE.on;
+    },
+
+    this.setPowerOffState = function(){
+        this.server_state = Constants.HOST_STATE_TEXT.off;
+        this.server_status = Constants.HOST_STATE.off;
+    },
+
+    this.setBootingState = function(){
+        this.server_state = Constants.HOST_STATE_TEXT.booting;
+        this.server_status = Constants.HOST_STATE.booting;
+    },
+
+    this.setUnreachableState = function(){
+        this.server_state = Constants.HOST_STATE_TEXT.unreachable;
+        this.server_status = Constants.HOST_STATE.unreachable;
+    }
+ }])
+ .factory('APIUtils', ['$http', 'Constants', function($http, Constants){
+    var SERVICE = {
+        LOGIN_CREDENTIALS: Constants.LOGIN_CREDENTIALS,
+        API_CREDENTIALS: Constants.API_CREDENTIALS,
+        API_RESPONSE: Constants.API_RESPONSE,
+        CHASSIS_POWER_STATE: Constants.CHASSIS_POWER_STATE,
+        HOST_STATE_TEXT: Constants.HOST_STATE,
+        HOST_STATE: Constants.HOST_STATE,
         getChassisState: function(callback){
           $http({
             method: 'GET',
@@ -106,7 +150,7 @@
             console.log(error);
           });
         },
-        login: function(callback){
+        login: function(username, password, callback){
           $http({
             method: 'POST',
             url: SERVICE.API_CREDENTIALS.host + "/login",
@@ -115,12 +159,36 @@
                 'Content-Type': 'application/json'
             },
             withCredentials: true,
-            data: JSON.stringify({"data": [SERVICE.API_CREDENTIALS.user, SERVICE.API_CREDENTIALS.password]})
+            data: JSON.stringify({"data": [username, password]})
           }).success(function(response){
             if(callback){
                 callback(response);
             }
           }).error(function(error){
+            if(callback){
+                callback(null, true);
+            }
+            console.log(error);
+          });
+        },
+        logout: function(callback){
+          $http({
+            method: 'POST',
+            url: SERVICE.API_CREDENTIALS.host + "/logout",
+            headers: {
+                'Accept': 'application/json',
+                'Content-Type': 'application/json'
+            },
+            withCredentials: true,
+            data: JSON.stringify({"data": []})
+          }).success(function(response){
+            if(callback){
+                callback(response);
+            }
+          }).error(function(error){
+            if(callback){
+                callback(null, error);
+            }
             console.log(error);
           });
         },
@@ -279,25 +347,33 @@
  }])
  .factory('userModel',['APIUtils',function(APIUtils){
     return {
-        login : function(username, password){
-            if(username == APIUtils.LOGIN_CREDENTIALS.username &&
-               password == APIUtils.LOGIN_CREDENTIALS.password){
-                sessionStorage.setItem('LOGIN_ID', username);
-                return true;
-            }else{
-                return false;
-            }
+        login : function(username, password, callback){
+            APIUtils.login(username, password, function(response, error){
+                if(response && 
+                   response.status == APIUtils.API_RESPONSE.SUCCESS_STATUS){
+                    sessionStorage.setItem('LOGIN_ID', username);
+                    callback(true);
+                }else{
+                    callback(false, error);
+                }
+            });
         },
         isLoggedIn : function(){
             if(sessionStorage.getItem('LOGIN_ID') === null){
                 return false;
             }
-
             return true;
         },
-        logout : function(){
-            sessionStorage.removeItem('LOGIN_ID');
-            return true;
+        logout : function(callback){
+            APIUtils.logout(function(response, error){
+                if(response &&
+                   response.status == APIUtils.API_RESPONSE.SUCCESS_STATUS){
+                    sessionStorage.removeItem('LOGIN_ID');
+                    callback(true);
+                }else{
+                    callback(false, error);
+                }
+            });
         }
     };
  }]);
diff --git a/src/login.html b/src/login.html
index 3525a61..122cd84 100644
--- a/src/login.html
+++ b/src/login.html
@@ -18,17 +18,18 @@
                 <li><p class="login__info-label">Status message</p><!--<p>BMC was reset by user</p>--></li>
             </ul>
         </div>
-        <div class="columns large-6">
+        <div class="columns large-6 disabled">
             <form id="login__form" role="form" action="" >
                 <label for="username">Username</label>
-                <input type="text" id="username" name="username" required ng-model="username" ng-class="{error: error}" ng-keydown="tryLogin(username, password, $event)">
+                <input type="text" id="username" name="username" required ng-model="username" ng-class="{error: error}" ng-keydown="tryLogin(username, password, $event)" ng-disabled="dataService.loading">
 
                 <label for="password">Password</label>
-                <input type="password" id="password" name="password" class="" required ng-model="password" ng-keydown="tryLogin(username, password, $event)">
+                <input type="password" id="password" name="password" class="" required ng-model="password" ng-keydown="tryLogin(username, password, $event)" ng-disabled="dataService.loading">
 
-                <input id="login__submit" class="btn-primary submit" type="button" value="Log in" role="button" ng-click="login(username, password)" ng-class="{error: error}">
+                <input id="login__submit" class="btn-primary submit" type="button" value="Log in" role="button" ng-click="login(username, password)" ng-class="{error: error}" ng-disabled="dataService.loading">
 
                 <p class="login__error-msg" role="alert" ng-if="error">Incorrect username or password</p>
+                <p class="login__error-msg" role="alert" ng-if="dataService.server_unreachable">Server Unreachable</p>
             </form>
         </div>
     </div>