| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757 |
- "use strict";
- var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- var desc = Object.getOwnPropertyDescriptor(m, k);
- if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
- desc = { enumerable: true, get: function() { return m[k]; } };
- }
- Object.defineProperty(o, k2, desc);
- }) : (function(o, m, k, k2) {
- if (k2 === undefined) k2 = k;
- o[k2] = m[k];
- }));
- var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
- Object.defineProperty(o, "default", { enumerable: true, value: v });
- }) : function(o, v) {
- o["default"] = v;
- });
- var __importStar = (this && this.__importStar) || (function () {
- var ownKeys = function(o) {
- ownKeys = Object.getOwnPropertyNames || function (o) {
- var ar = [];
- for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
- return ar;
- };
- return ownKeys(o);
- };
- return function (mod) {
- if (mod && mod.__esModule) return mod;
- var result = {};
- if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
- __setModuleDefault(result, mod);
- return result;
- };
- })();
- Object.defineProperty(exports, "__esModule", { value: true });
- exports.ClientAuthModel = void 0;
- const database_1 = require("../config/database");
- const crypto = __importStar(require("crypto"));
- class ClientAuthModel {
- static generateSalt() {
- return crypto.randomBytes(16).toString('hex');
- }
- static generatePasswordHash(password, salt, useSalt = true) {
- if (useSalt) {
- return crypto.createHash('sha256').update(password + salt).digest('hex');
- }
- else {
- return crypto.createHash('sha256').update(password).digest('hex');
- }
- }
- static generatePasswordHashPBKDF2(password, salt) {
- return crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
- }
- static verifyPassword(password, salt, hash, useSalt = true) {
- const hashVerify = this.generatePasswordHash(password, salt, useSalt);
- return hash === hashVerify;
- }
- static async verifyDynamicPassword(username, clientid, password) {
- try {
- return { valid: false };
- }
- catch (error) {
- console.error('动态密码验证失�?', error);
- return { valid: false };
- }
- }
- static async getAll(limit, offset) {
- let query = 'SELECT id, username, clientid, status, device_type, description, is_superuser, use_salt, salt, auth_method, auth_expiry, allowed_ip_ranges, allowed_time_ranges, auth_policy_id, created_at, updated_at, last_login_at FROM client_auth ORDER BY created_at DESC';
- const params = [];
- if (limit !== undefined) {
- query += ' LIMIT ?';
- params.push(limit);
- if (offset !== undefined) {
- query += ' OFFSET ?';
- params.push(offset);
- }
- }
- return await (0, database_1.executeQuery)(query, params);
- }
- static async getById(id) {
- const query = 'SELECT * FROM client_auth WHERE id = ?';
- const clients = await (0, database_1.executeQuery)(query, [id]);
- return clients.length > 0 ? clients[0] : null;
- }
- static async getByUsernameAndClientid(username, clientid) {
- const query = 'SELECT * FROM client_auth WHERE username = ? AND clientid = ?';
- const clients = await (0, database_1.executeQuery)(query, [username, clientid]);
- return clients.length > 0 ? clients[0] : null;
- }
- static async getByStatus(status) {
- const query = 'SELECT id, username, clientid, status, device_type, description, is_superuser, use_salt, salt, auth_method, auth_expiry, allowed_ip_ranges, allowed_time_ranges, auth_policy_id, created_at, updated_at, last_login_at FROM client_auth WHERE status = ? ORDER BY created_at DESC';
- return await (0, database_1.executeQuery)(query, [status]);
- }
- static async getCount() {
- const query = 'SELECT COUNT(*) as count FROM client_auth';
- const result = await (0, database_1.executeQuery)(query);
- return result[0].count;
- }
- static async getStatusStats() {
- try {
- const totalCountQuery = 'SELECT COUNT(*) as count FROM client_auth';
- const totalResult = await (0, database_1.executeQuery)(totalCountQuery);
- const total = totalResult[0].count;
- const statusQuery = `
- SELECT
- status,
- COUNT(*) as count
- FROM client_auth
- GROUP BY status
- `;
- const statusResults = await (0, database_1.executeQuery)(statusQuery);
- const superuserQuery = 'SELECT COUNT(*) as count FROM client_auth WHERE is_superuser = 1';
- const superuserResult = await (0, database_1.executeQuery)(superuserQuery);
- const superuserCount = superuserResult[0].count;
- let activeCount = 0;
- let inactiveCount = 0;
- statusResults.forEach((row) => {
- if (row.status === 'enabled') {
- activeCount = row.count;
- }
- else if (row.status === 'disabled') {
- inactiveCount = row.count;
- }
- });
- return {
- total,
- active: activeCount,
- inactive: inactiveCount,
- superuser: superuserCount
- };
- }
- catch (error) {
- console.error('获取客户端认证统计信息失�?', error);
- throw error;
- }
- }
- static async getDeviceTypeStats() {
- const query = `
- SELECT
- device_type,
- COUNT(*) as count
- FROM client_auth
- GROUP BY device_type
- ORDER BY count DESC
- `;
- return await (0, database_1.executeQuery)(query);
- }
- static async create(clientAuthData) {
- const useSalt = clientAuthData.use_salt !== undefined ? clientAuthData.use_salt : true;
- if (useSalt && !clientAuthData.salt) {
- clientAuthData.salt = this.generateSalt();
- }
- if (!useSalt) {
- clientAuthData.salt = '';
- }
- if (clientAuthData.password && !clientAuthData.password_hash) {
- clientAuthData.password_hash = this.generatePasswordHash(clientAuthData.password, clientAuthData.salt, useSalt);
- }
- const query = `
- INSERT INTO client_auth (username, clientid, password_hash, salt, use_salt, status, device_type, description, is_superuser, auth_method, auth_expiry, allowed_ip_ranges, allowed_time_ranges, auth_policy_id)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- `;
- const values = [
- clientAuthData.username,
- clientAuthData.clientid,
- clientAuthData.password_hash,
- clientAuthData.salt,
- useSalt ? 1 : 0,
- clientAuthData.status || 'enabled',
- clientAuthData.device_type || 'unknown',
- clientAuthData.description || null,
- clientAuthData.is_superuser ? 1 : 0,
- clientAuthData.auth_method || 'password',
- clientAuthData.auth_expiry || null,
- clientAuthData.allowed_ip_ranges || null,
- clientAuthData.allowed_time_ranges || null,
- clientAuthData.auth_policy_id || null
- ];
- const result = await (0, database_1.executeQuery)(query, values);
- return this.getById(result.insertId);
- }
- static async update(id, updateData) {
- const fields = [];
- const values = [];
- if (updateData.username !== undefined) {
- fields.push('username = ?');
- values.push(updateData.username);
- }
- if (updateData.clientid !== undefined) {
- fields.push('clientid = ?');
- values.push(updateData.clientid);
- }
- if (updateData.password_hash !== undefined) {
- fields.push('password_hash = ?');
- values.push(updateData.password_hash);
- }
- if (updateData.salt !== undefined) {
- fields.push('salt = ?');
- values.push(updateData.salt);
- }
- if (updateData.use_salt !== undefined) {
- fields.push('use_salt = ?');
- values.push(updateData.use_salt ? 1 : 0);
- }
- if (updateData.status !== undefined) {
- fields.push('status = ?');
- values.push(updateData.status);
- }
- if (updateData.device_type !== undefined) {
- fields.push('device_type = ?');
- values.push(updateData.device_type);
- }
- if (updateData.description !== undefined) {
- fields.push('description = ?');
- values.push(updateData.description);
- }
- if (updateData.is_superuser !== undefined) {
- fields.push('is_superuser = ?');
- values.push(updateData.is_superuser ? 1 : 0);
- }
- if (updateData.last_login_at !== undefined) {
- fields.push('last_login_at = ?');
- values.push(updateData.last_login_at);
- }
- if (updateData.auth_method !== undefined) {
- fields.push('auth_method = ?');
- values.push(updateData.auth_method);
- }
- if (updateData.auth_expiry !== undefined) {
- fields.push('auth_expiry = ?');
- values.push(updateData.auth_expiry);
- }
- if (updateData.allowed_ip_ranges !== undefined) {
- fields.push('allowed_ip_ranges = ?');
- values.push(updateData.allowed_ip_ranges);
- }
- if (updateData.allowed_time_ranges !== undefined) {
- fields.push('allowed_time_ranges = ?');
- values.push(updateData.allowed_time_ranges);
- }
- if (updateData.auth_policy_id !== undefined) {
- fields.push('auth_policy_id = ?');
- values.push(updateData.auth_policy_id);
- }
- fields.push('updated_at = CURRENT_TIMESTAMP');
- const query = `UPDATE client_auth SET ${fields.join(', ')} WHERE id = ?`;
- values.push(id);
- await (0, database_1.executeQuery)(query, values);
- return this.getById(id);
- }
- static async updatePassword(id, newPassword, useSalt = true) {
- const salt = useSalt ? this.generateSalt() : '';
- const passwordHash = this.generatePasswordHash(newPassword, salt, useSalt);
- const query = 'UPDATE client_auth SET password_hash = ?, salt = ?, use_salt = ?, updated_at = NOW() WHERE id = ?';
- const result = await (0, database_1.executeQuery)(query, [passwordHash, salt, useSalt ? 1 : 0, id]);
- return result.affectedRows > 0;
- }
- static async delete(id) {
- const query = 'DELETE FROM client_auth WHERE id = ?';
- const result = await (0, database_1.executeQuery)(query, [id]);
- return result.affectedRows > 0;
- }
- static async search(searchTerm, limit, offset) {
- let query = `
- SELECT id, username, clientid, status, device_type, description, is_superuser, use_salt, salt, created_at, updated_at, last_login_at
- FROM client_auth
- WHERE username LIKE ? OR clientid LIKE ? OR device_type LIKE ? OR description LIKE ?
- ORDER BY created_at DESC
- `;
- const params = [`%${searchTerm}%`, `%${searchTerm}%`, `%${searchTerm}%`, `%${searchTerm}%`];
- if (limit !== undefined) {
- query += ' LIMIT ?';
- params.push(limit);
- if (offset !== undefined) {
- query += ' OFFSET ?';
- params.push(offset);
- }
- }
- return await (0, database_1.executeQuery)(query, params);
- }
- static async getSearchCount(searchTerm) {
- const query = `
- SELECT COUNT(*) as count
- FROM client_auth
- WHERE username LIKE ? OR clientid LIKE ? OR device_type LIKE ? OR description LIKE ?
- `;
- const params = [`%${searchTerm}%`, `%${searchTerm}%`, `%${searchTerm}%`, `%${searchTerm}%`];
- const result = await (0, database_1.executeQuery)(query, params);
- return result[0].count;
- }
- static async getByUsername(username) {
- const query = 'SELECT * FROM client_auth WHERE username = ?';
- const clients = await (0, database_1.executeQuery)(query, [username]);
- return clients.length > 0 ? clients[0] : null;
- }
- static async getByClientId(clientid) {
- const query = 'SELECT * FROM client_auth WHERE clientid = ?';
- const clients = await (0, database_1.executeQuery)(query, [clientid]);
- return clients.length > 0 ? clients[0] : null;
- }
- static async verifyClient(username, clientid, password) {
- const clientAuth = await this.getByUsernameAndClientid(username, clientid);
- if (!clientAuth || clientAuth.status !== 'enabled') {
- return false;
- }
- const useSalt = clientAuth.use_salt !== undefined ? clientAuth.use_salt : true;
- return this.verifyPassword(password, clientAuth.salt, clientAuth.password_hash, useSalt);
- }
- static async getAuthMethods() {
- const query = 'SELECT * FROM auth_methods ORDER BY method_name';
- return await (0, database_1.executeQuery)(query);
- }
- static async getAuthMethodById(id) {
- const query = 'SELECT * FROM auth_methods WHERE id = ?';
- const methods = await (0, database_1.executeQuery)(query, [id]);
- return methods.length > 0 ? methods[0] : null;
- }
- static async getAuthMethodByName(name) {
- const query = 'SELECT * FROM auth_methods WHERE method_name = ?';
- const methods = await (0, database_1.executeQuery)(query, [name]);
- return methods.length > 0 ? methods[0] : null;
- }
- static async createAuthMethod(authMethod) {
- const query = `
- INSERT INTO auth_methods (method_name, method_type, config, is_active)
- VALUES (?, ?, ?, ?)
- `;
- const values = [
- authMethod.method_name,
- authMethod.method_type,
- authMethod.config,
- authMethod.is_active ? 1 : 0
- ];
- const result = await (0, database_1.executeQuery)(query, values);
- return this.getAuthMethodById(result.insertId);
- }
- static async updateAuthMethod(id, updateData) {
- const fields = [];
- const values = [];
- if (updateData.method_name !== undefined) {
- fields.push('method_name = ?');
- values.push(updateData.method_name);
- }
- if (updateData.method_type !== undefined) {
- fields.push('method_type = ?');
- values.push(updateData.method_type);
- }
- if (updateData.config !== undefined) {
- fields.push('config = ?');
- values.push(updateData.config);
- }
- if (updateData.is_active !== undefined) {
- fields.push('is_active = ?');
- values.push(updateData.is_active ? 1 : 0);
- }
- fields.push('updated_at = CURRENT_TIMESTAMP');
- const query = `UPDATE auth_methods SET ${fields.join(', ')} WHERE id = ?`;
- values.push(id);
- await (0, database_1.executeQuery)(query, values);
- return this.getAuthMethodById(id);
- }
- static async deleteAuthMethod(id) {
- const query = 'DELETE FROM auth_methods WHERE id = ?';
- const result = await (0, database_1.executeQuery)(query, [id]);
- return result.affectedRows > 0;
- }
- static async getAuthPolicies() {
- const query = 'SELECT * FROM auth_policies ORDER BY priority DESC, created_at ASC';
- return await (0, database_1.executeQuery)(query);
- }
- static async getAuthPolicyById(id) {
- const query = 'SELECT * FROM auth_policies WHERE id = ?';
- const policies = await (0, database_1.executeQuery)(query, [id]);
- return policies.length > 0 ? policies[0] : null;
- }
- static async createAuthPolicy(authPolicy) {
- const query = `
- INSERT INTO auth_policies (policy_name, priority, conditions, actions, is_active, description)
- VALUES (?, ?, ?, ?, ?, ?)
- `;
- const values = [
- authPolicy.policy_name,
- authPolicy.priority,
- authPolicy.conditions,
- authPolicy.actions,
- authPolicy.is_active ? 1 : 0,
- authPolicy.description || null
- ];
- const result = await (0, database_1.executeQuery)(query, values);
- return this.getAuthPolicyById(result.insertId);
- }
- static async updateAuthPolicy(id, updateData) {
- const fields = [];
- const values = [];
- if (updateData.policy_name !== undefined) {
- fields.push('policy_name = ?');
- values.push(updateData.policy_name);
- }
- if (updateData.priority !== undefined) {
- fields.push('priority = ?');
- values.push(updateData.priority);
- }
- if (updateData.conditions !== undefined) {
- fields.push('conditions = ?');
- values.push(updateData.conditions);
- }
- if (updateData.actions !== undefined) {
- fields.push('actions = ?');
- values.push(updateData.actions);
- }
- if (updateData.is_active !== undefined) {
- fields.push('is_active = ?');
- values.push(updateData.is_active ? 1 : 0);
- }
- if (updateData.description !== undefined) {
- fields.push('description = ?');
- values.push(updateData.description);
- }
- fields.push('updated_at = CURRENT_TIMESTAMP');
- const query = `UPDATE auth_policies SET ${fields.join(', ')} WHERE id = ?`;
- values.push(id);
- await (0, database_1.executeQuery)(query, values);
- return this.getAuthPolicyById(id);
- }
- static async deleteAuthPolicy(id) {
- const query = 'DELETE FROM auth_policies WHERE id = ?';
- const result = await (0, database_1.executeQuery)(query, [id]);
- return result.affectedRows > 0;
- }
- static async getClientTokens(clientid) {
- const query = 'SELECT * FROM client_tokens WHERE clientid = ? ORDER BY created_at DESC';
- return await (0, database_1.executeQuery)(query, [clientid]);
- }
- static async getClientTokenByValue(tokenValue) {
- const query = 'SELECT * FROM client_tokens WHERE token_value = ?';
- const tokens = await (0, database_1.executeQuery)(query, [tokenValue]);
- return tokens.length > 0 ? tokens[0] : null;
- }
- static async createClientToken(clientToken) {
- const query = `
- INSERT INTO client_tokens (clientid, token_type, token_value, expires_at, status)
- VALUES (?, ?, ?, ?, ?)
- `;
- const values = [
- clientToken.clientid,
- clientToken.token_type,
- clientToken.token_value,
- clientToken.expires_at,
- clientToken.status || 'active'
- ];
- const result = await (0, database_1.executeQuery)(query, values);
- const query2 = 'SELECT * FROM client_tokens WHERE id = ?';
- const tokens = await (0, database_1.executeQuery)(query2, [result.insertId]);
- return tokens[0];
- }
- static async updateClientToken(id, updateData) {
- const fields = [];
- const values = [];
- if (updateData.clientid !== undefined) {
- fields.push('clientid = ?');
- values.push(updateData.clientid);
- }
- if (updateData.token_type !== undefined) {
- fields.push('token_type = ?');
- values.push(updateData.token_type);
- }
- if (updateData.token_value !== undefined) {
- fields.push('token_value = ?');
- values.push(updateData.token_value);
- }
- if (updateData.expires_at !== undefined) {
- fields.push('expires_at = ?');
- values.push(updateData.expires_at);
- }
- if (updateData.status !== undefined) {
- fields.push('status = ?');
- values.push(updateData.status);
- }
- fields.push('updated_at = CURRENT_TIMESTAMP');
- const query = `UPDATE client_tokens SET ${fields.join(', ')} WHERE id = ?`;
- values.push(id);
- await (0, database_1.executeQuery)(query, values);
- const query2 = 'SELECT * FROM client_tokens WHERE id = ?';
- const tokens = await (0, database_1.executeQuery)(query2, [id]);
- return tokens.length > 0 ? tokens[0] : null;
- }
- static async deleteClientToken(id) {
- const query = 'DELETE FROM client_tokens WHERE id = ?';
- const result = await (0, database_1.executeQuery)(query, [id]);
- return result.affectedRows > 0;
- }
- static async getClientCertificates(clientid) {
- const query = 'SELECT * FROM client_certificates WHERE clientid = ? ORDER BY created_at DESC';
- return await (0, database_1.executeQuery)(query, [clientid]);
- }
- static async getClientCertificateByFingerprint(fingerprint) {
- const query = 'SELECT * FROM client_certificates WHERE fingerprint = ?';
- const certificates = await (0, database_1.executeQuery)(query, [fingerprint]);
- return certificates.length > 0 ? certificates[0] : null;
- }
- static async createClientCertificate(clientCertificate) {
- const query = `
- INSERT INTO client_certificates (clientid, certificate_pem, fingerprint, expires_at, status)
- VALUES (?, ?, ?, ?, ?)
- `;
- const values = [
- clientCertificate.clientid,
- clientCertificate.certificate_pem,
- clientCertificate.fingerprint,
- clientCertificate.expires_at,
- clientCertificate.status || 'active'
- ];
- const result = await (0, database_1.executeQuery)(query, values);
- const query2 = 'SELECT * FROM client_certificates WHERE id = ?';
- const certificates = await (0, database_1.executeQuery)(query2, [result.insertId]);
- return certificates[0];
- }
- static async updateClientCertificate(id, updateData) {
- const fields = [];
- const values = [];
- if (updateData.clientid !== undefined) {
- fields.push('clientid = ?');
- values.push(updateData.clientid);
- }
- if (updateData.certificate_pem !== undefined) {
- fields.push('certificate_pem = ?');
- values.push(updateData.certificate_pem);
- }
- if (updateData.fingerprint !== undefined) {
- fields.push('fingerprint = ?');
- values.push(updateData.fingerprint);
- }
- if (updateData.expires_at !== undefined) {
- fields.push('expires_at = ?');
- values.push(updateData.expires_at);
- }
- if (updateData.status !== undefined) {
- fields.push('status = ?');
- values.push(updateData.status);
- }
- fields.push('updated_at = CURRENT_TIMESTAMP');
- const query = `UPDATE client_certificates SET ${fields.join(', ')} WHERE id = ?`;
- values.push(id);
- await (0, database_1.executeQuery)(query, values);
- const query2 = 'SELECT * FROM client_certificates WHERE id = ?';
- const certificates = await (0, database_1.executeQuery)(query2, [id]);
- return certificates.length > 0 ? certificates[0] : null;
- }
- static async deleteClientCertificate(id) {
- const query = 'DELETE FROM client_certificates WHERE id = ?';
- const result = await (0, database_1.executeQuery)(query, [id]);
- return result.affectedRows > 0;
- }
- static async dynamicAuthVerify(username, clientid, authData, ipAddress) {
- try {
- const clientAuth = await this.getByUsernameAndClientid(username, clientid);
- if (!clientAuth) {
- return { success: false, reason: 'Client not found' };
- }
- if (clientAuth.status !== 'enabled') {
- return { success: false, reason: 'Client is disabled' };
- }
- if (clientAuth.auth_expiry && new Date(clientAuth.auth_expiry) < new Date()) {
- return { success: false, reason: 'Authentication expired' };
- }
- if (clientAuth.allowed_ip_ranges && ipAddress) {
- const allowedRanges = JSON.parse(clientAuth.allowed_ip_ranges);
- if (!this.isIpAllowed(ipAddress, allowedRanges)) {
- return { success: false, reason: 'IP address not allowed' };
- }
- }
- if (clientAuth.allowed_time_ranges) {
- const allowedTimeRanges = JSON.parse(clientAuth.allowed_time_ranges);
- if (!this.isTimeAllowed(allowedTimeRanges)) {
- return { success: false, reason: 'Access not allowed at this time' };
- }
- }
- let authResult = { success: false, reason: 'Authentication method not supported' };
- if (clientAuth.auth_method) {
- const authMethod = await this.getAuthMethodByName(clientAuth.auth_method);
- if (authMethod && authMethod.is_active) {
- authResult = await this.verifyByMethod(authMethod, clientAuth, authData);
- }
- }
- else {
- const useSalt = clientAuth.use_salt !== undefined ? clientAuth.use_salt : true;
- const isValid = this.verifyPassword(authData.password || '', clientAuth.salt, clientAuth.password_hash, useSalt);
- authResult = {
- success: isValid,
- reason: isValid ? 'Authentication successful' : 'Invalid password'
- };
- }
- if (!authResult.success) {
- return authResult;
- }
- if (clientAuth.auth_policy_id) {
- const policy = await this.getAuthPolicyById(clientAuth.auth_policy_id);
- if (policy && policy.is_active) {
- const policyResult = await this.applyAuthPolicy(policy, clientAuth, authData, ipAddress);
- if (!policyResult.success) {
- return policyResult;
- }
- return { success: true, policy };
- }
- }
- return { success: true };
- }
- catch (error) {
- console.error('Dynamic authentication error:', error);
- return { success: false, reason: 'Internal authentication error' };
- }
- }
- static async verifyByMethod(authMethod, clientAuth, authData) {
- const config = JSON.parse(authMethod.config);
- switch (authMethod.method_type) {
- case 'password':
- const useSalt = clientAuth.use_salt !== undefined ? clientAuth.use_salt : true;
- const isValid = this.verifyPassword(authData.password || '', clientAuth.salt, clientAuth.password_hash, useSalt);
- return {
- success: isValid,
- reason: isValid ? 'Authentication successful' : 'Invalid password'
- };
- case 'token':
- if (authData.token) {
- const token = await this.getClientTokenByValue(authData.token);
- if (token && token.status === 'active' && token.expires_at > new Date()) {
- return { success: true };
- }
- return { success: false, reason: 'Invalid or expired token' };
- }
- return { success: false, reason: 'Token required' };
- case 'certificate':
- if (authData.fingerprint) {
- const certificate = await this.getClientCertificateByFingerprint(authData.fingerprint);
- if (certificate && certificate.status === 'active' && certificate.expires_at > new Date()) {
- return { success: true };
- }
- return { success: false, reason: 'Invalid or expired certificate' };
- }
- return { success: false, reason: 'Certificate fingerprint required' };
- case 'external':
- return { success: false, reason: 'External authentication not implemented' };
- default:
- return { success: false, reason: 'Unknown authentication method' };
- }
- }
- static async applyAuthPolicy(policy, clientAuth, authData, ipAddress) {
- const conditions = JSON.parse(policy.conditions);
- const actions = JSON.parse(policy.actions);
- for (const condition of conditions) {
- let conditionMet = false;
- switch (condition.type) {
- case 'time_range':
- if (condition.value && Array.isArray(condition.value)) {
- conditionMet = this.isTimeAllowed(condition.value);
- }
- break;
- case 'ip_range':
- if (condition.value && Array.isArray(condition.value) && ipAddress) {
- conditionMet = this.isIpAllowed(ipAddress, condition.value);
- }
- break;
- case 'device_type':
- if (condition.value && clientAuth.device_type) {
- conditionMet = clientAuth.device_type === condition.value;
- }
- break;
- case 'custom':
- conditionMet = true;
- break;
- }
- if (!conditionMet) {
- if (condition.action === 'deny') {
- return { success: false, reason: `Policy condition not met: ${condition.type}` };
- }
- }
- }
- for (const action of actions) {
- switch (action.type) {
- case 'log':
- console.log(`Auth policy applied: ${policy.policy_name} for client ${clientAuth.clientid}`);
- break;
- case 'notify':
- console.log(`Notification sent for auth policy: ${policy.policy_name}`);
- break;
- case 'custom':
- break;
- }
- }
- return { success: true };
- }
- static isIpAllowed(ip, allowedRanges) {
- if (allowedRanges.includes('0.0.0.0/0')) {
- return true;
- }
- if (allowedRanges.includes(ip)) {
- return true;
- }
- return false;
- }
- static isTimeAllowed(timeRanges) {
- if (!timeRanges || timeRanges.length === 0) {
- return true;
- }
- const now = new Date();
- const currentHour = now.getHours();
- const currentDay = now.getDay();
- for (const range of timeRanges) {
- if (range.days && range.days.includes(currentDay)) {
- if (range.start_hour !== undefined && range.end_hour !== undefined) {
- if (currentHour >= range.start_hour && currentHour <= range.end_hour) {
- return true;
- }
- }
- else {
- return true;
- }
- }
- }
- return false;
- }
- static async findByUsernameAndClientId(username, clientid) {
- const query = 'SELECT * FROM client_auth WHERE username = ? AND clientid = ? AND status = ?';
- const clients = await (0, database_1.executeQuery)(query, [username, clientid, 'enabled']);
- return clients.length > 0 ? clients[0] : null;
- }
- static async findByUsername(username) {
- const query = 'SELECT * FROM client_auth WHERE username = ? LIMIT 1';
- const clients = await (0, database_1.executeQuery)(query, [username]);
- return clients.length > 0 ? clients[0] : null;
- }
- static async updateLastLogin(username, clientid) {
- const query = 'UPDATE client_auth SET last_login_at = NOW() WHERE username = ? AND clientid = ?';
- await (0, database_1.executeQuery)(query, [username, clientid]);
- }
- static async logAuthEvent(clientid, username, operationType, result, reason, ipAddress, topic, authMethod, policyId, executionTime) {
- const query = `
- INSERT INTO auth_log (clientid, username, ip_address, operation_type, result, reason, topic, auth_method, auth_policy_id, execution_time_ms)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
- `;
- const values = [
- clientid,
- username,
- ipAddress || null,
- operationType,
- result,
- reason || null,
- topic || null,
- authMethod || null,
- policyId || null,
- executionTime || null
- ];
- await (0, database_1.executeQuery)(query, values);
- }
- }
- exports.ClientAuthModel = ClientAuthModel;
- //# sourceMappingURL=clientAuth.js.map
|