使用后端服务器

时间:2015-10-28 11:02:23

标签: angularjs ionic-framework ionic

我尝试使用angularjs创建基于Ionic app的身份验证机制。系统看起来像这样:

enter image description here

移动用户由后端服务器上的管理员创建。创建的移动用户可以登录该应用程序。

我得到Example并为我的应用实现了它。

constants.js

angular.module('starter')
    .constant('AUTH_EVENTS', {
      notAuthenticated: 'auth-not-authenticated',
      notAuthorized: 'auth-not-authorized'
    })
    .constant('USER_ROLES', {
      admin: 'admin_role',
      public: 'public_role'
    });

dashController.js

myApp.controller('DashCtrl', function ($scope, $state, $http, $ionicPopup, AuthService, $location, $window) {
    $scope.logout = function () {
        AuthService.logout();
        $window.location.href = '/index.html';
    };
    $scope.performValidRequest = function () {
        $http.get('http://localhost:8100/valid').then(
            function (result) {
                $scope.response = result;
            });
    };
    $scope.performUnauthorizedRequest = function () {
        $http.get('http://localhost:8100/notauthorized').then(
            function (result) {
                // No result here..
            }, function (err) {
                $scope.response = err;
            });
    };
    $scope.performInvalidRequest = function () {
        $http.get('http://localhost:8100/notauthenticated').then(
            function (result) {
                // No result here..
            }, function (err) {
                $scope.response = err;
            });
    };
});

loginAppController.js

myApp.controller('LoginAppCtrl', function ($scope, $state, $ionicPopup, AuthService, AUTH_EVENTS, $location, $window) {
    $scope.username = AuthService.username();

    $scope.$on(AUTH_EVENTS.notAuthorized, function (event) {
        var alertPopup = $ionicPopup.alert({
            title: 'Unauthorized!',
            template: 'You are not allowed to access this resource.'
        });
    });
    $scope.$on(AUTH_EVENTS.notAuthenticated, function (event) {
        AuthService.logout();
        $window.location.href = '/loginPage.html';
        var alertPopup = $ionicPopup.alert({
            title: 'Session Lost!',
            template: 'Sorry, You have to login again.'
        });
    });
    $scope.setCurrentUsername = function (name) {
        $scope.username = name;
    };
})

loginController.js

myApp.controller('LoginCtrl', function ($scope, $state, $ionicPopup, AuthService, $location, $window) {
    $scope.data = {};

    $scope.login = function (data) {
        AuthService.login(data.username, data.password).then(function (authenticated) {
            $window.location.href = '/index.html';
            $scope.setCurrentUsername(data.username);
        }, function (err) {
            var alertPopup = $ionicPopup.alert({
                title: 'Login failed!',
                template: 'Please check your credentials!'
            });
        });
    };
})

loginService.js

angular.module('starter')

myApp.service('AuthService', function ($q, $http, USER_ROLES) {
    var LOCAL_TOKEN_KEY = 'yourTokenKey';
    var username = '';
    var isAuthenticated = false;
    var role = '';
    var authToken;

    function loadUserCredentials() {
        var token = window.localStorage.getItem(LOCAL_TOKEN_KEY);
        if (token) {
            useCredentials(token);
        }
    }

    function storeUserCredentials(token) {
        window.localStorage.setItem(LOCAL_TOKEN_KEY, token);
        useCredentials(token);
    }

    function useCredentials(token) {
        username = token.split('.')[0];
        isAuthenticated = true;
        authToken = token;

        if (username == 'admin') {
            role = USER_ROLES.admin
        }
        if (username == 'user') {
            role = USER_ROLES.public
        }

        // Set the token as header for your requests!
        $http.defaults.headers.common['X-Auth-Token'] = token;
    }

    function destroyUserCredentials() {
        authToken = undefined;
        username = '';
        isAuthenticated = false;
        $http.defaults.headers.common['X-Auth-Token'] = undefined;
        window.localStorage.removeItem(LOCAL_TOKEN_KEY);
    }

    var login = function (name, pw) {
        return $q(function (resolve, reject) {
            if ((name == 'admin' && pw == '1') || (name == 'user' && pw == '1')) {
                // Make a request and receive your auth token from your server
                storeUserCredentials(name + '.yourServerToken');
                resolve('Login success.');
            } else {
                reject('Login Failed.');
            }
        });
    };

    var logout = function () {
        destroyUserCredentials();
    };

    var isAuthorized = function (authorizedRoles) {
        if (!angular.isArray(authorizedRoles)) {
            authorizedRoles = [authorizedRoles];
        }
        return (isAuthenticated && authorizedRoles.indexOf(role) !== -1);
    };

    loadUserCredentials();

    return {
        login: login,
        logout: logout,
        isAuthorized: isAuthorized,
        isAuthenticated: function () {
            return isAuthenticated;
        },
        username: function () {
            return username;
        },
        role: function () {
            return role;
        }
    };
})

app.js

var myApp = angular.module('starter', ['ionic', 'ngMockE2E'])
.run(function($ionicPlatform, $ionicPopup) {
    $ionicPlatform.ready(function() {
        // Hide the accessory bar by default (remove this to show the accessory bar above the keyboard
        // for form inputs)
        if (window.cordova && window.cordova.plugins.Keyboard) {
            cordova.plugins.Keyboard.hideKeyboardAccessoryBar(true);
        }
        if (window.StatusBar) {
            StatusBar.styleDefault();
        }
    });
})

.run(function($httpBackend) {
    $httpBackend.whenGET('http://localhost:8100/valid')
      .respond({message: 'This is my valid response!'});
    $httpBackend.whenGET('http://localhost:8100/notauthenticated')
      .respond(401, {message: "Not Authenticated"});
    $httpBackend.whenGET('http://localhost:8100/notauthorized')
      .respond(403, {message: "Not Authorized"});
    $httpBackend.whenGET(/.*/).passThrough();
})

  .run(function ($rootScope, $state, AuthService, AUTH_EVENTS, $location, $window) {
    $rootScope.$on('$stateChangeStart', function (event,next, nextParams, fromState) {

      if ('data' in next && 'authorizedRoles' in next.data) {
        var authorizedRoles = next.data.authorizedRoles;
        if (!AuthService.isAuthorized(authorizedRoles)) {
          event.preventDefault();
          $state.go($state.current, {}, {reload: true});
          $rootScope.$broadcast(AUTH_EVENTS.notAuthorized);
        }
      }

      if (!AuthService.isAuthenticated()) {
        if (next.name !== 'login') {
          event.preventDefault();
          $window.location.href = '/loginPage.html';
        }
      }
    });
  })

HTML:

<ion-content style="text-align: left" ng-controller="LoginCtrl">
    <span class="item item-input item-stacked-label"
          style="font-weight: bold">Name and password:</span>
        <label class="item item-input">
            <span class="input-label">Name:</span>
            <input name="name" placeholder="Name!" autofocus="true" required="true"
                   type="text"
                   ng-model="data.username"/>
        </label>
        <label class="item item-input">
            <span class="input-label">Password:</span>
            <input name="password" placeholder="Password!" required="true" type="password"
                   ng-model="data.password"/>
        </label>
        <button id="button-1" class="button button-block button-positive" ng-click="login(data)">Login</button>
 </ion-content>

在相关article中,我将这些步骤作为答案:

  

1)使用$ http.post();

向服务器发送用户名密码      

2)服务器验证凭据。并返回一个令牌   凭证是正确的。

     

3)App在本地存储此令牌并将其传递给服务器以供日后使用   请求作为登录用户的识别手段。

     

理想情况下,您应该在您的服务上实现基于SOAP或REST的服务   服务器并在您的应用中使用这些服务。

该示例适用于localy。但是应该在哪里更改,以便我可以使用存储在备份服务器上的用户和密码进行身份验证?

0 个答案:

没有答案