import Joi from '@hapi/joi'; import globals from '../../globals'; import IdValidate from './id'; export default class UserValidate { // validate input for user private static user = { name: Joi.string() .lowercase() .pattern(new RegExp('^[a-z0-9-_.]+$')) .max(128), email: Joi.string() .email({minDomainSegments: 2}) .lowercase() .max(128), pass: Joi.string() .pattern(new RegExp('^(?=.*[0-9])(?=.*[a-z])(?=.*[A-Z])(?=.*[!"#%&\'()*+,-.\\/:;<=>?@[\\]^_`{|}~])(?=\\S+$).{8,}$')) .max(128), level: Joi.string() .valid(...globals.levels), location: Joi.string() .alphanum() .max(128), device_name: Joi.string() .allow('') .max(128), }; private static specialUsernames = ['admin', 'user', 'key', 'new', 'passreset']; // names a user cannot take static input (data, param) { if (param === 'new') { return Joi.object({ name: this.user.name.required(), email: this.user.email.required(), pass: this.user.pass.required(), level: this.user.level.required(), location: this.user.location.required(), device_name: this.user.device_name.required() }).validate(data); } else if (param === 'change') { return Joi.object({ name: this.user.name, email: this.user.email, pass: this.user.pass, location: this.user.location, device_name: this.user.device_name }).validate(data); } else if (param === 'changeadmin') { return Joi.object({ name: this.user.name, email: this.user.email, pass: this.user.pass, level: this.user.level, location: this.user.location, device_name: this.user.device_name }).validate(data); } else { return{error: 'No parameter specified!', value: {}}; } } static output (data) { // validate output from database for needed properties, strip everything else data = IdValidate.stringify(data); const {value, error} = Joi.object({ _id: IdValidate.get(), name: this.user.name, email: this.user.email, level: this.user.level, location: this.user.location, device_name: this.user.device_name }).validate(data, {stripUnknown: true}); return error !== undefined? null : value; } static isSpecialName (name) { // true if name belongs to special names return this.specialUsernames.indexOf(name) > -1; } }