egg-auths
v1.0.2
Published
authentication and authorization egg plugin
Downloads
7
Readme
egg-auths
Auths is a plugin of eggjs, mainly used to complete user authentication and authorization. Related APIs and modules are mainly designed with reference to Apache Shiro. It supports coarse-grained role-based control of resource access and fine-grained resource-based permission access control. In the current design, the data source (Realm) of roles and permissions is a database, and egg-sequelize is used as the ORM, user identity and credential information are persisted to the egg session.
Install
# depend egg-sequelize
$ npm i egg-auths egg-sequelize --save
Configuration
- config egg's
plugin.js
// application/config/plugin.js
sequelize: {
enable: true,
package: 'egg-sequelize',
},
auths: {
enable: true,
package: 'egg-auths'
}
- config egg's
config.default.js
// application/config/config.default.js
config.sequelize = {
dialect: 'mysql',
host: '127.0.0.1',
port: 3306,
database: 'test',
username: 'root',
password: '********',
// ORM model definition in the plugin
// plz copy related ORM models to application/app/model in production environment
baseDir: '../node_modules/egg-auths/app/model'
}
config.auths = {
// if you do not need custom any module, then just be an empty object
}
- Sync Model to DB
// application/app.js
module.exports = app => {
if (app.config.env === 'local' || app.config.env === 'unittest') {
app.beforeStart(async () => {
await app.model.sync();
});
}
};
reference to egg-sequelize,you should use sequelize-cli in production environment.
Usage
- Use in router middleware
// application/app/router.js
// include RBACAuth module
const RBACAuth = require('egg-auths/lib/index')
module.exports = app => {
const { router, controller } = app;
// get an instance
const rbac = new RBACAuth({
// you can config some properties for HTTP Response when authenticate or authorizate failed, see API document
})
// set roles or permissions then will get middleware function
router.get('/admin', rbac.checkRoles(['admin']), controller.admin.index)
router.get('/orders', rbac.checkRoles(['admin','ceo']), controller.admin.order)
router.get('/users', rbac.checkPermissions(['admin:user']), controller.admin.order)
router.get('/profile', rbac.checkLogin(), controller.admin.order)
}
- Use in program(
controller
,service
)with subject's methods and property
// application/app/controller/admin.js
const Controller = require('egg').Controller;
class AdminController extends Controller {
async index () {
let { ctx } = this
let subject = await ctx.getSubject()
subject.hasRoles(['admin','ceo'])
subject.hasPermissions(['admin:user'])
subject.isLogined // true or false
}
}