add some methods to permission class

This commit is contained in:
b1ek 2023-03-05 19:01:03 +10:00
parent 45d276c5af
commit 99184b9568
Signed by: blek
GPG Key ID: 14546221E3595D0C
1 changed files with 72 additions and 7 deletions

View File

@ -1,17 +1,82 @@
const { Model, DataTypes } = require('sequelize'); const { Model, DataTypes } = require('sequelize');
const { sequelize } = require('.'); const { sequelize } = require('.');
class Permission extends Model { /** @type {{data: Permission[], updated: number, expired: function}} */
let cached = {
data: undefined,
updated: 0,
expired: () => {
return (Date.now() - updated) >= 1000
}
}
class Permission extends Model {
static async cache() {
if (!cached.expired()) return;
cached.data = await Permission.findAll();
cached.updated = Date.now();
}
/**
* Get value from cache
* @param {number} user
* @param {string} permission
* @returns {Permission?}
*/
static async findFromCache(user, permission) {
await this.cache();
for (const perm of cached.data) {
if (perm.user == userid && perm.permission == permission)
return perm;
}
return null;
}
/**
* Get a permission for user
* @param {number} user
* @param {string} permission
* @returns {boolean}
*/
static async forUser(user, permission) {
await this.cache();
const data = await this.findFromCache(user, permission);
if (!data) return false;
return data.value != 0;
}
/**
* Set a permission for user
* @param {number} user
* @param {string} permission
* @param {number} value
* @returns {Permission}
*/
static async set(user, permission, value) {
const existing = await Permission.findOne({where: {user, permission}});
let perm;
if (!existing) perm = await Permission.create({user, permission, value});
else perm = await Permission.update({user, permission, value}, {where: {user, permission}});
await this.cache();
return perm;
}
static async userAllowed(user, permission) {
return this.forUser(user, permission);
}
} }
Permission.structure = { Permission.structure = {
// id: { id: {
// type: DataTypes.BIGINT, type: DataTypes.BIGINT,
// primaryKey: true, primaryKey: true,
// autoIncrement: true, autoIncrement: true,
// allowNull: false allowNull: false
// }, },
user: { user: {
type: DataTypes.BIGINT, type: DataTypes.BIGINT,
allowNull: false allowNull: false