2023-02-14 21:49:04 +02:00
|
|
|
const { BeanModel } = require("redbean-node/dist/bean-model");
|
|
|
|
const { R } = require("redbean-node");
|
2023-02-15 00:41:06 +02:00
|
|
|
const dayjs = require("dayjs");
|
2023-02-14 21:49:04 +02:00
|
|
|
|
|
|
|
class APIKey extends BeanModel {
|
|
|
|
/**
|
|
|
|
* Get the current status of this API key
|
2023-02-15 21:31:22 +02:00
|
|
|
* @returns {string} active, inactive or expired
|
2023-02-14 21:49:04 +02:00
|
|
|
*/
|
|
|
|
getStatus() {
|
2023-02-15 00:41:06 +02:00
|
|
|
let current = dayjs();
|
|
|
|
let expiry = dayjs(this.expires);
|
|
|
|
if (expiry.diff(current) < 0) {
|
2023-02-14 21:49:04 +02:00
|
|
|
return "expired";
|
|
|
|
}
|
2023-02-15 00:41:06 +02:00
|
|
|
|
|
|
|
return this.active ? "active" : "inactive";
|
2023-02-14 21:49:04 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns an object that ready to parse to JSON
|
2023-08-11 09:46:41 +02:00
|
|
|
* @returns {object} Object ready to parse
|
2023-02-14 21:49:04 +02:00
|
|
|
*/
|
|
|
|
toJSON() {
|
|
|
|
return {
|
|
|
|
id: this.id,
|
|
|
|
key: this.key,
|
|
|
|
name: this.name,
|
|
|
|
userID: this.user_id,
|
|
|
|
createdDate: this.created_date,
|
|
|
|
active: this.active,
|
|
|
|
expires: this.expires,
|
|
|
|
status: this.getStatus(),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Returns an object that ready to parse to JSON with sensitive fields
|
|
|
|
* removed
|
2023-08-11 09:46:41 +02:00
|
|
|
* @returns {object} Object ready to parse
|
2023-02-14 21:49:04 +02:00
|
|
|
*/
|
|
|
|
toPublicJSON() {
|
|
|
|
return {
|
|
|
|
id: this.id,
|
|
|
|
name: this.name,
|
|
|
|
userID: this.user_id,
|
|
|
|
createdDate: this.created_date,
|
|
|
|
active: this.active,
|
|
|
|
expires: this.expires,
|
|
|
|
status: this.getStatus(),
|
|
|
|
};
|
|
|
|
}
|
|
|
|
|
|
|
|
/**
|
|
|
|
* Create a new API Key and store it in the database
|
2023-08-11 09:46:41 +02:00
|
|
|
* @param {object} key Object sent by client
|
2023-02-14 21:49:04 +02:00
|
|
|
* @param {int} userID ID of socket user
|
2023-08-11 09:46:41 +02:00
|
|
|
* @returns {Promise<bean>} API key
|
2023-02-14 21:49:04 +02:00
|
|
|
*/
|
|
|
|
static async save(key, userID) {
|
|
|
|
let bean;
|
|
|
|
bean = R.dispense("api_key");
|
|
|
|
|
|
|
|
bean.key = key.key;
|
|
|
|
bean.name = key.name;
|
|
|
|
bean.user_id = userID;
|
|
|
|
bean.active = key.active;
|
|
|
|
bean.expires = key.expires;
|
|
|
|
|
|
|
|
await R.store(bean);
|
|
|
|
|
|
|
|
return bean;
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
module.exports = APIKey;
|