UNPKG

@next-auth-oauth/wechatmp

Version:

基于Auth.js的微信公众号验证码登录、二维码扫描登录插件

65 lines (64 loc) 1.66 kB
export class MemoryCaptchaManager { options; cache = new Map(); constructor(options) { this.options = options || { expireTime: 60000 * 2, length: 6, }; } exists(captcha) { return Promise.resolve(this.cache.has(captcha)); } /** * 生成验证码 */ async generate(code) { this.cleanupExpired(); const captcha = code ?? Math.random() .toString() .substring(2, this.options.length + 2); this.cache.set(captcha, { expireAt: Date.now() + this.options.expireTime }); return captcha; } /** * 更新验证码绑定的数据 * @param captcha * @param data */ async updateData(captcha, data) { if (this.cache.has(captcha)) { const entry = this.cache.get(captcha); if (entry && entry.expireAt > Date.now()) { entry.data = data; return true; } } return false; } /** * 获取验证码绑定的数据 * @param captcha */ async getData(captcha) { const entry = this.cache.get(captcha); if (entry && entry.expireAt > Date.now()) { return entry.data; } } /** * 清理过期的验证码 */ async cleanupExpired() { const now = Date.now(); for (const [captcha, entry] of this.cache.entries()) { if (entry.expireAt <= now) { this.cache.delete(captcha); } } } async list() { return Array.from(this.cache.keys()); } }