token-middleware
A Sumor Cloud Tool.
More Documentation
A token middleware for ExpressJS.
Installation
npm i @sumor/token-middleware --save
Prerequisites
Node.JS version
Require Node.JS version 18.x or above
require Node.JS ES module
As this package is written in ES module,
please change the following code in your package.json
file:
{
"type": "module"
}
Usage
Add token middleware to ExpressJS App
import express from 'express'
import tokenMiddleware from '@sumor/token-middleware'
const app = express()
app.use(tokenMiddleware)
app.use(async (req, res, next) => {
const tokenId = req.token.id
const tokenInfo = await fetchToken(tokenId)
req.token.user = tokenInfo.user
req.token.data = tokenInfo.data
req.token.permission = tokenInfo.permission
next()
})
app.get('/login', async (req, res) => {
const username = req.query.username
const password = req.query.password
req.token.id = await createToken(username, password)
res.send('Login Success')
})
app.get('/api', (req, res) => {
req.token.check('AUTH1')
res.send('Hello World')
})
permission check
req.token.permission = {
AUTH1: ['READ', 'WRITE'],
AUTH2: ['READ']
}
const hasAuth1 = req.token.has('AUTH1')
const hasAuth2 = req.token.has('AUTH2')
const hasAuth3 = req.token.has('AUTH3')
const hasAuth1Read = req.token.has('AUTH1', 'READ')
const hasAuth1Write = req.token.has('AUTH1', 'WRITE')
const hasAuth2Read = req.token.has('AUTH2', 'READ')
const hasAuth2Write = req.token.has('AUTH2', 'WRITE')
req.token.check('AUTH1')
req.token.check('AUTH2')
req.token.check('AUTH3')
req.token.check('AUTH1', 'READ')
req.token.check('AUTH1', 'WRITE')
req.token.check('AUTH2', 'READ')
req.token.check('AUTH2', 'WRITE')