/** * @file 密码相关 * * @todo 补充单元测试 */ /** * 密码强度 */ export enum PasswordStrengthEnum { Weak = 'weak', Normal = 'normal', Strong = 'strong', } /** * 根据各权重值计算密码强度 * PRD: https://www.yuque.com/preview/yuque/0/2020/rp/581946/1599734639863-5ef078e3-0aa5-4ff9-8a4a-0669104c8f08.rp?from=https%3A%2F%2Fwww.yuque.com%2Fkovru3%2Fhtekrb%2Fvbsldx * * @param pwd - 密码 * @returns 强度 */ export const getPasswordStrength = ( pwd: string, ): PasswordStrengthEnum | null => { if (!pwd) return null let weight = 0 // 16 - 30,权重 10 if (pwd.length > 15) { weight += 10 } // 7 - 15,权重 6 if (pwd.length > 6 && pwd.length < 16) { weight += 6 } // === 6,权重 1 if (pwd.length === 6) { weight += 1 } // 包含一种,权重 + 2 const has1 = /[a-z]/.test(pwd) const has2 = /[A-Z]/.test(pwd) const has3 = /[0-9]/.test(pwd) const has4 = /[~!@$^*()-._<>]/.test(pwd) const charFlag = [has1, has2, has3, has4].filter(Boolean) weight += 2 * charFlag.length // 后一个字符和前一个字符一样,权重 - 1 const pwdCharList = pwd.split('') for (let i = 1; i < pwdCharList.length; i += 1) { if (pwdCharList[i] === pwdCharList[i - 1]) { weight -= 1 } } if (weight < 9) return PasswordStrengthEnum.Weak if (weight > 12) return PasswordStrengthEnum.Strong return PasswordStrengthEnum.Normal } /** * 生成易读的随机密码 * * @param length - 密码长度 * @returns 密码 */ export function generateRandomSimplePassword(length = 8) { const usedStr = 'abcdefghjklmnpqrstuvwxyz23456789' let len = length let result = '' while (len) { len -= 1 const value = usedStr[Math.floor(Math.random() * usedStr.length)] result += value } return result }