是否有将passport.js集成到sails.js的文档或教程?

时间:2016-04-25 15:36:07

标签: sails.js passport.js

每个教程或未完成的文档都不起作用。这就是我在这里问的原因:是否有一个简单的教程,对于护照和帆来说真的有用吗?

1 个答案:

答案 0 :(得分:2)

按照以下步骤将两个护照与风帆js整合在一起 第一: - 在依赖项下的application_directory / package.json中列出这些依赖项 //application_directory/package.json

{
...
  "dependencies": {
    ...
    "passport": "~0.1.16",
    "passport-local": "~0.1.6",
    "bcrypt": "~0.7.6"
  }
...
}

<强> 2 - 要创建用户模型,请运行以下命令:

sails generate model user

3- model user.js将如下所示

var bcrypt = require('bcrypt');

module.exports = {

  attributes: {
    username: {
      type: 'string',
      required: true,
      unique: true
    },
    password: {
      type: 'string',
      required: true
    },
    toJSON: function() {
      var obj = this.toObject();
      delete obj.password;
      return obj;
    }
  },

  beforeCreate: function(user, cb) {
    bcrypt.genSalt(10, function(err, salt) {
      bcrypt.hash(user.password, salt, function(err, hash) {
        if (err) {
          console.log(err);
          cb(err);
        }else{
          user.password = hash;
          cb(null, user);
        }
      });
    });
  }

};

4 - 要在风帆中创建控制器,请输入命令

sails generate controller

AuthController将如下所示:

var passport = require('passport');
module.exports = {

  login: function (req, res) {
    res.view();
  },
  process: function(req, res){
    passport.authenticate('local', function(err, user, info) {
      if ((err) || (!user)) {
        return res.send({
        message: 'login failed'
        });
        res.send(err);
      }
      req.logIn(user, function(err) {
        if (err) res.send(err);
        return res.send({
          message: 'login successful'
        });
      });
    })(req, res);
  },
  logout: function (req,res){
    req.logout();
    res.send('logout successful');
  }
};

module.exports.blueprints = {
  actions: true,
  rest: true,

  shortcuts: true

};

5 - 将以下代码添加到application_directory / config / routes.js

module.exports.routes = {
  // (This would also work if you had a file at: `/views/home.ejs`)
  '/': {
    view: 'home/index'
  },

  '/login': {
    controller: 'AuthController',
    action: 'login'
  },
  '/logout': {
    controller: 'AuthController',
    action: 'logout'
  }
  ......
}

6 - 在application_directory / config中创建一个文件passport.js并将以下代码添加到

var passport = require('passport'),
LocalStrategy = require('passport-local').Strategy;
module.exports = {
  express: {
    customMiddleware: function(app){
      console.log('Express midleware for passport');
      app.use(passport.initialize());
      app.use(passport.session());
    }
  }
};

7 - 在/ api / services /内创建一个文件passport.js并将以下代码添加到

var passport = require('passport'),
  LocalStrategy = require('passport-local').Strategy,
  bcrypt = require('bcrypt'); &lt; /code&gt;
//helper functions
function findById(id, fn) {
  User.findOne(id).done(function (err, user) {
    if (err) {
      return fn(null, null);
    } else {
      return fn(null, user);
    }
  });
}

function findByUsername(u, fn) {
  User.findOne({
    username: u
  }).done(function (err, user) {
    // Error handling
    if (err) {
      return fn(null, null);
      // The User was found successfully!
    } else {
      return fn(null, user);
    }
  });
}

passport.serializeUser(function (user, done) {
  done(null, user.id);
});

passport.deserializeUser(function (id, done) {
  findById(id, function (err, user) {
    done(err, user);
  });
});

passport.use(new LocalStrategy(
  function (username, password, done) {
    // asynchronous verification, for effect...
    process.nextTick(function () {
      findByUsername(username, function (err, user) {
        if (err)
          return done(null, err);
        if (!user) {
          return done(null, false, {
            message: 'Unknown user ' + username
          });
        }
        bcrypt.compare(password, user.password, function (err, res) {
          if (!res)
            return done(null, false, {
              message: 'Invalid Password'
            });
          var returnUser = {
            username: user.username,
            createdAt: user.createdAt,
            id: user.id
          };
          return done(null, returnUser, {
            message: 'Logged In Successfully'
          });
        });
      })
    });
  }
));

8 - 修改/ api / policies /

中的authenticated.js文件
/**
 * Allow any authenticated user.
 */

    module.exports = function (req, res, ok) {

      // User is allowed, proceed to controller

          var is_auth = req.isAuthenticated()
          if (is_auth) return next();
          // User is not allowed
          else return res.redirect("/login");
        };