1/**
2 * Controller for the login page
3 *
4 * @module app/login/controllers/index
5 * @exports LoginController
6 * @name LoginController
7 */
8
9window.angular && (function(angular) {
10  'use strict';
11
12  angular.module('app.login').controller('LoginController', [
13    '$scope',
14    '$window',
15    'dataService',
16    'userModel',
17    '$location',
18    function($scope, $window, dataService, userModel, $location) {
19      $scope.dataService = dataService;
20      $scope.serverUnreachable = false;
21      $scope.invalidCredentials = false;
22      $scope.host = $scope.dataService.host.replace(/^https?\:\/\//ig, '');
23
24      $scope.tryLogin = function(host, username, password, event) {
25        // keyCode 13 is the 'Enter' button. If the user hits 'Enter' while in
26        // one of the 3 fields, attempt to log in.
27        if (event.keyCode === 13) {
28          $scope.login(host, username, password);
29        }
30      };
31      $scope.login = function(host, username, password) {
32        $scope.serverUnreachable = false;
33        $scope.invalidCredentials = false;
34        if (!username || username == '' || !password || password == '' ||
35            !host || host == '') {
36          return false;
37        } else {
38          $scope.dataService.setHost(host);
39          userModel.login(username, password, function(status, description) {
40            if (status) {
41              $scope.$emit('user-logged-in', {});
42              var next = $location.search().next;
43              if (next === undefined || next == null) {
44                $window.location.hash = '#/overview/server';
45              } else {
46                $window.location.href = next;
47              }
48            } else {
49              if (description === 'Unauthorized') {
50                $scope.invalidCredentials = true;
51              } else {
52                $scope.serverUnreachable = true;
53              }
54            }
55          });
56        }
57      };
58    },
59  ]);
60})(angular);
61