validator.js 10.2 KB
Newer Older
study夏羽's avatar
study夏羽 已提交
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432
const {
  isValidString,
  getType
} = require('./utils.js')
const {
  ERROR
} = require('./error')

const baseValidator = Object.create(null)

baseValidator.username = function (username) {
  const errCode = ERROR.INVALID_USERNAME
  if (!isValidString(username)) {
    return {
      errCode
    }
  }
  if (/^\d+$/.test(username)) {
    // 用户名不能为纯数字
    return {
      errCode
    }
  };
  if (!/^[a-zA-Z0-9_-]+$/.test(username)) {
    // 用户名仅能使用数字、字母、“_”及“-”
    return {
      errCode
    }
  }
}

baseValidator.password = function (password) {
  const errCode = ERROR.INVALID_PASSWORD
  if (!isValidString(password)) {
    return {
      errCode
    }
  }
  if (password.length < 6) {
    // 密码长度不能小于6
    return {
      errCode
    }
  }
}

baseValidator.mobile = function (mobile) {
  const errCode = ERROR.INVALID_MOBILE
  if (!isValidString(mobile)) {
    return {
      errCode
    }
  }
  if (!/^1\d{10}$/.test(mobile)) {
    return {
      errCode
    }
  }
}

baseValidator.email = function (email) {
  const errCode = ERROR.INVALID_EMAIL
  if (!isValidString(email)) {
    return {
      errCode
    }
  }
  if (!/@/.test(email)) {
    return {
      errCode
    }
  }
}

baseValidator.nickname = function (nickname) {
  const errCode = ERROR.INVALID_NICKNAME
  if (nickname.indexOf('@') !== -1) {
    // 昵称不允许含@
    return {
      errCode
    }
  };
  if (/^\d+$/.test(nickname)) {
    // 昵称不能为纯数字
    return {
      errCode
    }
  };
  if (nickname.length > 100) {
    // 昵称不可超过100字符
    return {
      errCode
    }
  }
}

const baseType = ['string', 'boolean', 'number', 'null'] // undefined不会由客户端提交上来

baseType.forEach((type) => {
  baseValidator[type] = function (val) {
    if (getType(val) === type) {
      return
    }
    return {
      errCode: ERROR.INVALID_PARAM
    }
  }
})

function tokenize(name) {
  let i = 0
  const result = []
  let token = ''
  while (i < name.length) {
    const char = name[i]
    switch (char) {
      case '|':
      case '<':
      case '>':
        token && result.push(token)
        result.push(char)
        token = ''
        break
      default:
        token += char
        break
    }
    i++
    if (i === name.length && token) {
      result.push(token)
    }
  }
  return result
}

/**
 * 处理validator名
 * @param {string} name
 */
function parseValidatorName(name) {
  const tokenList = tokenize(name)
  let i = 0
  let currentToken = tokenList[i]
  const result = {
    type: 'root',
    children: [],
    parent: null
  }
  let lastRealm = result
  while (currentToken) {
    switch (currentToken) {
      case 'array': {
        const currentRealm = {
          type: 'array',
          children: [],
          parent: lastRealm
        }
        lastRealm.children.push(currentRealm)
        lastRealm = currentRealm
        break
      }
      case '<':
        if (lastRealm.type !== 'array') {
          throw new Error('Invalid validator token "<"')
        }
        break
      case '>':
        if (lastRealm.type !== 'array') {
          throw new Error('Invalid validator token ">"')
        }
        lastRealm = lastRealm.parent
        break
      case '|':
        if (lastRealm.type !== 'array' && lastRealm.type !== 'root') {
          throw new Error('Invalid validator token "|"')
        }
        break
      default:
        lastRealm.children.push({
          type: currentToken
        })
        break
    }
    i++
    currentToken = tokenList[i]
  }
  return result
}

function getRuleCategory(rule) {
  switch (rule.type) {
    case 'array':
      return 'array'
    case 'root':
      return 'root'
    default:
      return 'base'
  }
}

function isMatchUnionType(val, rule) {
  if (!rule.children || rule.children.length === 0) {
    return true
  }
  const children = rule.children
  for (let i = 0; i < children.length; i++) {
    const child = children[i]
    const category = getRuleCategory(child)
    let pass = false
    switch (category) {
      case 'base':
        pass = isMatchBaseType(val, child)
        break
      case 'array':
        pass = isMatchArrayType(val, child)
        break
      default:
        break
    }
    if (pass) {
      return true
    }
  }
  return false
}

function isMatchBaseType(val, rule) {
  if (typeof baseValidator[rule.type] !== 'function') {
    throw new Error(`invalid schema type: ${rule.type}`)
  }
  const validateRes = baseValidator[rule.type](val)
  if (validateRes && validateRes.errCode) {
    return false
  }
  return true
}

function isMatchArrayType(arr, rule) {
  if (getType(arr) !== 'array') {
    return false
  }
  if (rule.children && rule.children.length && arr.some(item => !isMatchUnionType(item, rule))) {
    return false
  }
  return true
}

// 特殊符号 https://www.ibm.com/support/pages/password-strength-rules  ~!@#$%^&*_-+=`|\(){}[]:;"'<>,.?/
// const specialChar = '~!@#$%^&*_-+=`|\(){}[]:;"\'<>,.?/'
// const specialCharRegExp = /^[~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/]$/
// for (let i = 0, arr = specialChar.split(''); i < arr.length; i++) {
//   const char = arr[i]
//   if (!specialCharRegExp.test(char)) {
//     throw new Error('check special character error: ' + char)
//   }
// }

// 密码强度表达式
const passwordRules = {
  // 密码必须包含大小写字母、数字和特殊符号
  super: /^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/])[0-9a-zA-Z~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/]{8,16}$/,
  // 密码必须包含字母、数字和特殊符号
  strong: /^(?=.*[0-9])(?=.*[a-zA-Z])(?=.*[~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/])[0-9a-zA-Z~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/]{8,16}$/,
  // 密码必须为字母、数字和特殊符号任意两种的组合
  medium: /^(?![0-9]+$)(?![a-zA-Z]+$)(?![~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/]+$)[0-9a-zA-Z~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/]{8,16}$/,
  // 密码必须包含字母和数字
  weak: /^(?=.*[0-9])(?=.*[a-zA-Z])[0-9a-zA-Z~!@#$%^&*_\-+=`|\\(){}[\]:;"'<>,.?/]{6,16}$/,

}

function createPasswordVerifier({
  passwordStrength = ''
} = {}) {
  return function (password) {
    const passwordRegExp = passwordRules[passwordStrength]
    if (!passwordRegExp) {
      throw new Error('Invalid password strength config: ' + passwordStrength)
    }
    const errCode = ERROR.INVALID_PASSWORD
    if (!isValidString(password)) {
      return {
        errCode
      }
    }
    if (!passwordRegExp.test(password)) {
      return {
        errCode: errCode + '-' + passwordStrength
      }
    }
  }
}

class Validator {
  constructor({
    passwordStrength = ''
  } = {}) {
    this.baseValidator = baseValidator
    this.customValidator = Object.create(null)
    if (passwordStrength) {
      this.mixin(
        'password',
        createPasswordVerifier({
          passwordStrength
        })
      )
    }
  }

  mixin(type, handler) {
    this.customValidator[type] = handler
  }

  getRealBaseValidator(type) {
    return this.customValidator[type] || this.baseValidator[type]
  }

  get validator() {
    return new Proxy({}, {
      get: (_, prop) => {
        if (typeof prop !== 'string') {
          return
        }
        const realBaseValidator = this.getRealBaseValidator(prop)
        if (realBaseValidator) {
          return realBaseValidator
        }
        const rule = parseValidatorName(prop)
        return function (val) {
          if (!isMatchUnionType(val, rule)) {
            return {
              errCode: ERROR.INVALID_PARAM
            }
          }
        }
      }
    })
  }

  validate(value = {}, schema = {}) {
    for (const schemaKey in schema) {
      let schemaValue = schema[schemaKey]
      if (getType(schemaValue) === 'string') {
        schemaValue = {
          required: true,
          type: schemaValue
        }
      }
      const {
        required,
        type
      } = schemaValue
      // value内未传入了schemaKey或对应值为undefined
      if (value[schemaKey] === undefined) {
        if (required) {
          return {
            errCode: ERROR.PARAM_REQUIRED,
            errMsgValue: {
              param: schemaKey
            },
            schemaKey
          }
        } else {
          continue
        }
      }
      const validateMethod = this.validator[type]
      if (!validateMethod) {
        throw new Error(`invalid schema type: ${type}`)
      }
      const validateRes = validateMethod(value[schemaKey])
      if (validateRes) {
        validateRes.schemaKey = schemaKey
        return validateRes
      }
    }
  }
}

function checkClientInfo(clientInfo) {
  const stringNotRequired = {
    required: false,
    type: 'string'
  }
  const numberNotRequired = {
    required: false,
    type: 'number'
  }
  const numberOrStringNotRequired = {
    required: false,
    type: 'number|string'
  }
  const schema = {
    uniPlatform: 'string',
    appId: 'string',
    deviceId: stringNotRequired,
    osName: stringNotRequired,
    locale: stringNotRequired,
    clientIP: stringNotRequired,
    appName: stringNotRequired,
    appVersion: stringNotRequired,
    appVersionCode: numberOrStringNotRequired,
    channel: numberOrStringNotRequired,
    userAgent: stringNotRequired,
    uniIdToken: stringNotRequired,
    deviceBrand: stringNotRequired,
    deviceModel: stringNotRequired,
    osVersion: stringNotRequired,
    osLanguage: stringNotRequired,
    osTheme: stringNotRequired,
    romName: stringNotRequired,
    romVersion: stringNotRequired,
    devicePixelRatio: numberNotRequired,
    windowWidth: numberNotRequired,
    windowHeight: numberNotRequired,
    screenWidth: numberNotRequired,
    screenHeight: numberNotRequired
  }
  const validateRes = new Validator().validate(clientInfo, schema)
  if (validateRes) {
    if (validateRes.errCode === ERROR.PARAM_REQUIRED) {
      console.warn('- 如果使用HBuilderX运行本地云函数/云对象功能时出现此提示,请改为使用客户端调用本地云函数方式调试,或更新HBuilderX到3.4.12及以上版本。\n- 如果是缺少clientInfo.appId,请检查项目manifest.json内是否配置了DCloud AppId')
      throw new Error(`"clientInfo.${validateRes.schemaKey}" is required.`)
    } else {
      throw new Error(`Invalid client info: clienInfo.${validateRes.schemaKey}`)
    }
  }
}

module.exports = {
  Validator,
  checkClientInfo
}