LoginSignup
0
1

More than 5 years have passed since last update.

express-restify-mongoose のアクセス制御

Last updated at Posted at 2017-06-29

リクエストの認可

ログインの有無による認可は options.preMiddleware で行う。

preMiddleware: function (req, res, next) {
  if (req.isLoggedIn()) {
    next()
  } else {
    res.status(403).end()
    // Or `next(new Error('hoge hoge'))`
  }
}

フィールド単位のアクセス制御

ログインの有無やロールに応じて、一部のフィールドをレスポンスから除外することもできる。

// Server
restify.serve(router, mongoose.model('Hoge', new mongoose.schema({
  name: String,
  zip: String,
  city: String
})), {
  access: function (req) {
    return req.isLoggedIn() ? 'protected' : 'public';
  },
  protected: ['zip', 'city']
});

// Client(未ログイン時)
$http.get('/api/v1/Hoge').then(res => {
  console.log(res.data)
})
# -> [{ name: 'fuga' }, { name: 'pico' }...]
# zip/city は protected なのでレスポンスに含まれない

全てのフィールドを protected や private に指定し除外しても、空のオブジェクトが返却される。

// Server
restify.serve(router, mongoose.model('Fuga', new mongoose.schema({
  nyaa: String,
  nyannya: String
})), {
  access: function (req) {
    return req.isLoggedIn() ? 'protected' : 'public';
  },
  protected: ['nyaa', 'nyannya', '_id', '__v']
});

// Client(未ログイン時)
$http.get('/api/v1/Fuga').then(res => {
  console.log(res.data)
})
# -> [{}, {}, {}, {}...]
0
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
1