أداة Sumor Cloud.
مزيد من التوثيق
وسيط رمزي لـ ExpressJS.
npm i @sumor/token-middleware --save
تتطلب إصدار Node.JS 18.x أو أعلى
نظرًا لأن هذه الحزمة مكتوبة بوحدة ES،
يرجى تغيير الكود التالي في ملف package.json الخاص بك:
{
  "type": "module"
}
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)
  // سيتم إضافة الرمز تلقائيًا إلى رأس الإجابة في ملف تعريف الارتباط 't'
  res.send('Login Success')
})
// استخدام الرمز
app.get('/api', (req, res) => {
  // التحقق من الصلاحية
  req.token.check('AUTH1')
  res.send('Hello World')
})
// الحصول على الصلاحية
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') // يرمي الخطأ PERMISSION_DENIED تم رفض الإذن: AUTH3
req.token.check('AUTH1', 'READ') // نجاح
req.token.check('AUTH1', 'WRITE') // نجاح
req.token.check('AUTH2', 'READ') // نجاح
req.token.check('AUTH2', 'WRITE') // يرمي الخطأ PERMISSION_DENIED تم رفض الإذن: AUTH2=WRITE