分布式验证码服务
类型
server hook
验证码发送和校验,支持集群管理验证码。
特性
- 使用简单;
- 支持单机、redis等集群管理验证码;
- 自定义验证码有效时间和重发间隔时间;
- 验证码防覆盖;
- 自定义验证码规则;
使用
基础用法
// 创建
const { sendCaptcha, verifyCaptcha } = createCaptchaProvider({
store: RedisAdapter()
});
// 发送验证码
const key = '1234567890';
await sendCaptcha(
(code, mobile) => alova.Post('/sms/send', { code, mobile }),
// 手机号作为存储键
{ key }
);
// 验证验证码
const captchaFromUserInput = '1234';
const isValid = await verifyCaptcha(captchaFromUserInput, key);
console.log(isValid ? '验证通过' : '验证 码错误');
设置验证码存储器
在使用之前,需要通过store配置设置验证码的存储器,它是alova的存储适配器,如果是单机下可以使用文件存储适配器、分布式集群下可以使用redis适配器,你可以在存储适配器中选择合适的适配器,也可以自定义存储适配器。
const redisAdapter = new RedisStorageAdapter({
host: 'localhost',
port: '6379',
username: 'default',
password: 'my-top-secret',
db: 0
});
createCaptchaProvider({
store: redisAdapter
});
验证码过期时间
通过expireTime配置设置验证码有效期,单位毫秒,默认300000(5分钟)。
createCaptchaProvider({
expireTime: 10 * 60 * 1000
});