UNPKG

modpacksio-common

Version:

Common code for Modpacks.io services

101 lines (93 loc) 3.24 kB
const Schema = require('mongoose').Schema; const id = require('../id'); const permission = require('../permission'); // 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])+)\])/; const icons = ['https://i.imgur.com/DISt7j6.png', 'https://i.imgur.com/gV5yjzG.png', 'https://i.imgur.com/Ldw4ITJ.png', 'https://i.imgur.com/KDj4QRV.png', 'https://i.imgur.com/Yt5vjBW.png', 'https://i.imgur.com/qhFTgTR.png', 'https://i.imgur.com/tUgdmEV.png', 'https://i.imgur.com/C12dO93.png', 'https://i.imgur.com/HqJ0UuY.png', 'https://i.imgur.com/UMhLly3.png']; const token = new Schema({ created: Number, address: String, token: String }, { _id: false, id: false }); const user = new Schema({ _id: { type: Number, alias: 'id', default: id.nextId() }, created: { type: Number, default: new Date().getTime() }, name: { first: String, last: String }, username: { type: String, minlength: [ 2, 'Username must have at least 2 characters.' ], maxlength: [ 16, 'Username must have a maximum of 16 characters.' ] }, email: { type: String, required: [ true, 'An email must be provided.' ], validate: { validator: email => EMAIL_REGEX.test(email), message: props => `${props.value} does not follow correct email format.` } }, verification: { type: String, default: '' }, icon: { type: String, default: icons[icons.length * Math.random() | 0] }, password: String, ips: [{ type: String }], permissions: [String], auth: [token], _shard: { type: String, default: __shardId } }); // Helper Functions user.methods.hasPermission = function (perm) { return permission.hasPermission(this.permissions, perm); }; user.methods.createToken = async function (ip) { const token = { created: new Date().getTime(), address: ip, token: id.nextToken() }; this.auth.push(token); await this.save(); return token; }; // Return Methods user.methods.toPrivate = function (perms = false, ips = false, shard = false) { const raw = this.toObject({ virtuals: true, versionKey: false }); raw.auth = raw.auth.map(({ token, ...auth }) => ({ ...auth })); delete raw._id; delete raw.password; if (!ips) delete raw.ips; if (!perms) delete raw.permissions; if (!shard) delete raw._shard; return raw; }; user.methods.toPublic = function () { return { id: this._id, created: this.created, username: this.username, icon: this.icon }; }; // Static Methods user.statics.findByToken = function (token) { return this.findOne({ 'auth.token': token }); }; module.exports = user;