egg-easy-captcha

2.0.1 • Public • Published

egg-easy-captcha

NPM version build status Test coverage David deps Known Vulnerabilities npm download

Install

$ npm i egg-easy-captcha --save

Usage

// {app_root}/config/plugin.js
exports.easyCaptcha = {
  enable: true,
  package: 'egg-easy-captcha',
};

Configuration

// {app_root}/config/config.default.js
exports.easyCaptcha = {
  client: {
    // 验证码宽度
    width: 150,
    // 验证码高度
    height: 50,
    // 字体大小
    fontSize: 56,
    // 预置格式化字符
    charPreset: 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789',
    // 干扰线条的数量
    noise: 1,
    // 验证码的字符是否有颜色,默认没有,如果设定了背景,则默认有
    color: false,
    // 验证码图片背景颜色
    background: '',
    // 加载字体,覆盖内置的字体。
    loadFont: '',
    // 验证码默认有效期(ms单位),默认10分钟
    pexpire: 600000,
    // 配置默认使用redis的Key
    redisKey: 'eggEasyCaptcha',
  }
};

see config/config.default.js for more detail.

Example

获取图形验证码

  /**
   * 获取图形验证码
   */
  async getImageCaptcha() {
    const ctx = this.ctx;
    const { constant } = this.app;
    const { statusCode } = constant;
    // 限制接口访问频率
    const limit = await ctx.Limit({ max: 6, time: '60s' })
    if (limit) {
      ctx.body = {
        statusCode:statusCode.COMMON.IP_LIMIT_ERROR
      }
      return;
    }
    // 获取图形验证码
    const imageCaptcha = this.app.easyCaptcha.create()
    if (!imageCaptcha) {
      ctx.body = {
        statusCode: statusCode.COMMON.CAPTCHA_SYSTEM_ERROR
      }
      return;
    }
    // 将图形验证码进行返回
    ctx.set('Content-Type', 'image/svg+xml')
    ctx.set('captcha-validate-id', imageCaptcha.id);
    ctx.body = imageCaptcha.data
  }

验证图形验证码

  /**
   * 验证图形验证码
   */
  async validateImageCaptcha() {
    const ctx = this.ctx;
    const { constant } = this.app;
    const { statusCode } = constant;
    const { captchaText } = ctx.qeury;
    // 验证图形验证码
    try {
      const validateCaptcha = await this.app.easyCaptcha.validate(ctx.get('captcha-validate-id'),captchaText);
        ctx.body = {
          statusCode: statusCode.COMMON.SUCCESS
        }
    } catch (err) {
        ctx.body = {
          statusCode: statusCode.COMMON.CAPTCHA_FAIL
        }
    }
  }

Questions & Suggestions

Please open an issue here.

License

MIT

Package Sidebar

Install

npm i egg-easy-captcha

Weekly Downloads

3

Version

2.0.1

License

MIT

Unpacked Size

13.1 kB

Total Files

9

Last publish

Collaborators

  • sothx