Files

93 lines
1.8 KiB
JavaScript
Raw Permalink Normal View History

2020-02-19 15:55:06 +11:00
// Objection Docs:
// http://vincit.github.io/objection.js/
2025-09-02 21:43:00 +10:00
import bcrypt from "bcrypt";
import { Model } from "objection";
import db from "../db.js";
import { convertBoolFieldsToInt, convertIntFieldsToBool } from "../lib/helpers.js";
import now from "./now_helper.js";
import User from "./user.js";
2020-02-19 15:55:06 +11:00
Model.knex(db());
2020-02-19 15:55:06 +11:00
2025-09-02 21:43:00 +10:00
const boolFields = ["is_deleted"];
2024-10-10 15:53:11 +10:00
2025-09-02 21:43:00 +10:00
function encryptPassword() {
if (this.type === "password" && this.secret) {
return bcrypt.hash(this.secret, 13).then((hash) => {
this.secret = hash;
});
2020-02-19 15:55:06 +11:00
}
return null;
}
class Auth extends Model {
2025-09-02 21:43:00 +10:00
$beforeInsert(queryContext) {
this.created_on = now();
this.modified_on = now();
2020-02-19 15:55:06 +11:00
// Default for meta
2025-09-02 21:43:00 +10:00
if (typeof this.meta === "undefined") {
2020-02-19 15:55:06 +11:00
this.meta = {};
}
return encryptPassword.apply(this, queryContext);
}
2025-09-02 21:43:00 +10:00
$beforeUpdate(queryContext) {
this.modified_on = now();
2020-02-19 15:55:06 +11:00
return encryptPassword.apply(this, queryContext);
}
2024-10-10 15:53:11 +10:00
$parseDatabaseJson(json) {
2025-09-02 21:43:00 +10:00
const thisJson = super.$parseDatabaseJson(json);
return convertIntFieldsToBool(thisJson, boolFields);
2024-10-10 15:53:11 +10:00
}
$formatDatabaseJson(json) {
2025-09-02 21:43:00 +10:00
const thisJson = convertBoolFieldsToInt(json, boolFields);
return super.$formatDatabaseJson(thisJson);
2024-10-10 15:53:11 +10:00
}
2020-02-19 15:55:06 +11:00
/**
* Verify a plain password against the encrypted password
*
* @param {String} password
* @returns {Promise}
*/
2025-09-02 21:43:00 +10:00
verifyPassword(password) {
2020-02-19 15:55:06 +11:00
return bcrypt.compare(password, this.secret);
}
2025-09-02 21:43:00 +10:00
static get name() {
return "Auth";
2020-02-19 15:55:06 +11:00
}
2025-09-02 21:43:00 +10:00
static get tableName() {
return "auth";
2020-02-19 15:55:06 +11:00
}
2025-09-02 21:43:00 +10:00
static get jsonAttributes() {
return ["meta"];
2020-02-19 15:55:06 +11:00
}
2025-09-02 21:43:00 +10:00
static get relationMappings() {
2020-02-19 15:55:06 +11:00
return {
user: {
2025-09-02 21:43:00 +10:00
relation: Model.HasOneRelation,
2020-02-19 15:55:06 +11:00
modelClass: User,
2025-09-02 21:43:00 +10:00
join: {
from: "auth.user_id",
to: "user.id",
2020-02-19 15:55:06 +11:00
},
filter: {
2025-09-02 21:43:00 +10:00
is_deleted: 0,
},
},
2020-02-19 15:55:06 +11:00
};
}
}
2025-09-02 21:43:00 +10:00
export default Auth;