使用loopback-component-passport将环回用户角色设置为内置模型

时间:2016-02-15 18:02:26

标签: angularjs node.js loopbackjs strongloop

我正在尝试使用基于条件的用户角色的npm loopback-component-passport来创建环回用户,

  1. 如果用户拥有属性isAdmin:true,则他应该具有admin
  2. 的角色
  3. 如果用户拥有属性isAdmin:false,则他应该具有user
  4. 的角色

    这是我的代码:

    if (form.$valid) {
            AuthService.register({
              name: $scope.user.name,
              email: $scope.user.email,
              password: $scope.user.password,
              isAdmin: $scope.user.isAdmin
            })
              .then(function() {
                // Account created, redirect to home
                $state.go('home');
              })
              .catch(function(err) {
                err = err.data;
                $scope.errors = {};
    
                // Update validity of form fields that match the mongoose errors
                angular.forEach(err.errors, function(error, field) {
                  form[field].$setValidity('mongoose', false);
                  $scope.errors[field] = error.message;
                });
            });
    }
    

    工厂:

    angular
      .module('app')
      .factory('AuthService', ['User', '$q', '$rootScope', function(User, $q, $rootScope) {
        function login(email, password) {
          return User
            .login({email: email, password: password})
            .$promise
            .then(function(response) {
              $rootScope.currentUser = {
                id: response.user.id,
                tokenId: response.id,
                email: email
              };
            });
        }
    
        function logout() {
          return User
            .logout()
            .$promise
            .then(function() {
              $rootScope.currentUser = null;
            });
        }
    
        function register(user) {
          return User.create(user).$promise;
        }
    
        return {
          login: login,
          logout: logout,
          register: register
        };
      }]);
    

    护照策略:

     "local": {
        "provider": "local",
        "module": "passport-local",
        "usernameField": "email",
        "passwordField": "password",
        "authPath": "/auth/local",
        "successRedirect": "/auth/account",
        "failureRedirect": "/local",
        "failureFlash": true
          },
       ... 
       ...
    

    模型config.json

    { 
      "User": {
        "dataSource": "db"
      },
      "AccessToken": {
        "dataSource": "db",
        "public": false
      },
      "ACL": {
        "dataSource": "db",
        "public": false
      },
      "RoleMapping": {
        "dataSource": "db",
        "public": false
      },
      "Role": {
        "dataSource": "db",
        "public": false
      }
    }
    

    但现在我不知道如何添加角色,以便我可以区分用户角色的用户。如何在loopback-component-passport的内置模型中设置用户角色?

1 个答案:

答案 0 :(得分:1)

最初创建一个文件并在DB中添加角色 服务器/引导/ role.js

module.exports = function(app) {
  var Role = app.models.Role;
  Role.create([
      {name: 'admin'},
      {name: 'user'}]
    , function(err, role) {
      if (err) throw err;
      console.log('Created roles:', role);
    });
};

使用Model钩子方法 的 This is output result

服务器/引导/ user.js的

module.exports = function(app) {
  var User = app.models.user;
  var Role = app.models.Role;
  var RoleMapping = app.models.RoleMapping;
  User.observe('after save', function setDefaultUsername(ctx, next) {
    if (ctx.instance) {
      if (ctx.isNewInstance) {
        var userRole = ctx.instance.isAdmin ? 'admin' : 'user';
        Role.findOne({where: {name: userRole}}, function(err, role) {
          if (err) {
            return console.log(err);
          }
          RoleMapping.create({
            principalType: RoleMapping.USER,
            principalId: ctx.instance.id,
            roleId: role.id
          }, function(err, roleMapping) {
            if (err) {
              return console.log(err);
            }
          });
        });
      }
    }
    next();
  });
};

查看post

上的完整示例