UNPKG

modpacksio-common

Version:

Common code for Modpacks.io services

52 lines (49 loc) 2.02 kB
const sanitizeHtml = require('sanitize-html'); const bcrypt = require('bcrypt'); const SALT_ROUNDS = process.env.SALT_ROUNDS ? process.env.SALT_ROUNDS : 5; // Source: https://emailregex.com/ const EMAIL_REGEX = /(?:[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*|"(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21\x23-\x5b\x5d-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])*")@(?:(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?|\[(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?|[a-z0-9-]*[a-z0-9]:(?:[\x01-\x08\x0b\x0c\x0e-\x1f\x21-\x5a\x53-\x7f]|\\[\x01-\x09\x0b\x0c\x0e-\x7f])+)\])/; // Source: https://stackoverflow.com/a/19605207 // Conditions: 1 uppercase, 1 lowercase, 1 digit, 1 special character, 8+ total characters. const PASSWORD_REGEX = /^(?=.*?[A-Z])(?=.*?[a-z])(?=.*?[0-9])(?=.*?[#?!@$%^&*-]).{8,}$/; module.exports = Object.freeze({ EMAIL_REGEX, PASSWORD_REGEX, sanitize, softSanitize, hash, compare, isEmail: text => EMAIL_REGEX.test(text), isPassword: password => PASSWORD_REGEX.test(password) }); function sanitize(piece) { if (!piece) return piece; if (piece instanceof Object) { for (let key in piece) if (/^\$/.test(key)) delete piece[key]; } else return sanitizeHtml(piece.toString(), { allowedTags: [] }); return piece; } function softSanitize(piece) { if (!piece) return piece; if (piece instanceof Object) { for (let key in piece) if (/^\$/.test(key)) delete piece[key]; } else { const html = sanitizeHtml(piece.toString()); if (html) return html.replace(/&lt;/g, '<').replace(/&gt;/g, '>'); return html; } return piece; } async function hash(password) { const salt = await bcrypt.genSalt(SALT_ROUNDS); return await bcrypt.hash(password, salt); } async function compare(raw, hashed) { return await bcrypt.compare(raw, hashed); }