@adonisjs/auth
Version:
Official authentication provider for Adonis framework
61 lines (60 loc) • 2.87 kB
JavaScript
import { t as E_INVALID_CREDENTIALS } from "../../errors-sGy-K8pd.js";
import { RuntimeException } from "@adonisjs/core/exceptions";
import { beforeSave } from "@adonisjs/lucid/orm";
function __decorate(decorators, target, key, desc) {
var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
return c > 3 && r && Object.defineProperty(target, key, r), r;
}
function withAuthFinder(hash, options) {
let normalizedOptions = {
uids: ["email"],
passwordColumnName: "password",
...options
};
let hashFactory = typeof hash === "function" ? hash : () => hash.use();
return function(superclass) {
class UserWithUserFinder extends superclass {
static async hashPassword(user) {
if (user.$dirty[normalizedOptions.passwordColumnName]) user[normalizedOptions.passwordColumnName] = await hashFactory().make(user[normalizedOptions.passwordColumnName]);
}
static findForAuth(uids, value) {
const query = this.query();
uids.forEach((uid) => query.orWhere(uid, value));
return query.limit(1).first();
}
static async verifyCredentials(uid, password) {
if (!uid || !password) throw new E_INVALID_CREDENTIALS("Invalid user credentials");
const user = await this.findForAuth(normalizedOptions.uids, uid);
if (!user) {
await hashFactory().make(password);
throw new E_INVALID_CREDENTIALS("Invalid user credentials");
}
if (await user.verifyPassword(password)) return user;
throw new E_INVALID_CREDENTIALS("Invalid user credentials");
}
verifyPassword(plainPassword) {
const passwordHash = this[normalizedOptions.passwordColumnName];
if (!passwordHash) throw new RuntimeException(`Cannot verify password. The value for "${normalizedOptions.passwordColumnName}" column is undefined or null`);
return hashFactory().verify(passwordHash, plainPassword);
}
async validatePassword(plainPassword, passwordFieldName) {
if (!await this.verifyPassword(plainPassword)) {
const error = /* @__PURE__ */ new Error("Validation Error");
Object.defineProperty(error, "code", { value: "E_VALIDATION_ERROR" });
Object.defineProperty(error, "status", { value: 422 });
Object.defineProperty(error, "messages", { value: [{
field: passwordFieldName ?? "currentPassword",
message: "The current password is incorrect",
rule: "current_password"
}] });
throw error;
}
}
}
__decorate([beforeSave()], UserWithUserFinder, "hashPassword", null);
return UserWithUserFinder;
};
}
export { withAuthFinder };