banana
/
definma-api
Archived
2
Fork 0
This repository has been archived on 2023-03-02. You can view files and clone it, but cannot push or open issues or pull requests.
definma-api/src/routes/validate/user.ts

108 lines
2.9 KiB
TypeScript

import Joi from '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)
.messages({'string.pattern.base': 'name must only contain a-z0-9_.'}),
email: Joi.string()
.email({minDomainSegments: 2})
.lowercase()
.max(128),
pass: Joi.string()
.min(8)
.max(128),
level: Joi.string()
.valid(...Object.values(globals.levels)),
location: Joi.string()
.alphanum()
.max(128),
devices: Joi.array()
.items(Joi.string()
.allow('')
.max(128)
),
models: Joi.array()
.items(IdValidate.get()),
status: Joi.string()
.valid(...Object.values(globals.status))
};
private static specialUsernames: string[] = ['admin', 'user', 'key', 'new', 'passreset']; // names a user cannot take
static input (data, param) { // validate input, set param to 'new' to make all attributes required
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(),
devices: this.user.devices.required(),
models: this.user.models.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,
devices: this.user.devices
}).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,
devices: this.user.devices,
models: this.user.models
}).validate(data);
}
else {
return{error: 'No parameter specified!', value: {}};
}
}
static output (data, param = '') { // validate output and strip unwanted properties, returns null if not valid
data = IdValidate.stringify(data);
const validate: {[key: string]: object} = {
_id: IdValidate.get(),
name: this.user.name,
email: this.user.email,
level: this.user.level,
location: this.user.location,
devices: this.user.devices,
models: this.user.models
}
if (param === 'admin') {
validate.status = this.user.status;
}
const {value, error} = Joi.object(validate).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;
}
static username() {
return this.user.name;
}
}