clientAuth.js 32 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757
  1. "use strict";
  2. var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
  3. if (k2 === undefined) k2 = k;
  4. var desc = Object.getOwnPropertyDescriptor(m, k);
  5. if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
  6. desc = { enumerable: true, get: function() { return m[k]; } };
  7. }
  8. Object.defineProperty(o, k2, desc);
  9. }) : (function(o, m, k, k2) {
  10. if (k2 === undefined) k2 = k;
  11. o[k2] = m[k];
  12. }));
  13. var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
  14. Object.defineProperty(o, "default", { enumerable: true, value: v });
  15. }) : function(o, v) {
  16. o["default"] = v;
  17. });
  18. var __importStar = (this && this.__importStar) || (function () {
  19. var ownKeys = function(o) {
  20. ownKeys = Object.getOwnPropertyNames || function (o) {
  21. var ar = [];
  22. for (var k in o) if (Object.prototype.hasOwnProperty.call(o, k)) ar[ar.length] = k;
  23. return ar;
  24. };
  25. return ownKeys(o);
  26. };
  27. return function (mod) {
  28. if (mod && mod.__esModule) return mod;
  29. var result = {};
  30. if (mod != null) for (var k = ownKeys(mod), i = 0; i < k.length; i++) if (k[i] !== "default") __createBinding(result, mod, k[i]);
  31. __setModuleDefault(result, mod);
  32. return result;
  33. };
  34. })();
  35. Object.defineProperty(exports, "__esModule", { value: true });
  36. exports.ClientAuthModel = void 0;
  37. const database_1 = require("../config/database");
  38. const crypto = __importStar(require("crypto"));
  39. class ClientAuthModel {
  40. static generateSalt() {
  41. return crypto.randomBytes(16).toString('hex');
  42. }
  43. static generatePasswordHash(password, salt, useSalt = true) {
  44. if (useSalt) {
  45. return crypto.createHash('sha256').update(password + salt).digest('hex');
  46. }
  47. else {
  48. return crypto.createHash('sha256').update(password).digest('hex');
  49. }
  50. }
  51. static generatePasswordHashPBKDF2(password, salt) {
  52. return crypto.pbkdf2Sync(password, salt, 10000, 64, 'sha512').toString('hex');
  53. }
  54. static verifyPassword(password, salt, hash, useSalt = true) {
  55. const hashVerify = this.generatePasswordHash(password, salt, useSalt);
  56. return hash === hashVerify;
  57. }
  58. static async verifyDynamicPassword(username, clientid, password) {
  59. try {
  60. return { valid: false };
  61. }
  62. catch (error) {
  63. console.error('动态密码验证失�?', error);
  64. return { valid: false };
  65. }
  66. }
  67. static async getAll(limit, offset) {
  68. 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';
  69. const params = [];
  70. if (limit !== undefined) {
  71. query += ' LIMIT ?';
  72. params.push(limit);
  73. if (offset !== undefined) {
  74. query += ' OFFSET ?';
  75. params.push(offset);
  76. }
  77. }
  78. return await (0, database_1.executeQuery)(query, params);
  79. }
  80. static async getById(id) {
  81. const query = 'SELECT * FROM client_auth WHERE id = ?';
  82. const clients = await (0, database_1.executeQuery)(query, [id]);
  83. return clients.length > 0 ? clients[0] : null;
  84. }
  85. static async getByUsernameAndClientid(username, clientid) {
  86. const query = 'SELECT * FROM client_auth WHERE username = ? AND clientid = ?';
  87. const clients = await (0, database_1.executeQuery)(query, [username, clientid]);
  88. return clients.length > 0 ? clients[0] : null;
  89. }
  90. static async getByStatus(status) {
  91. 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';
  92. return await (0, database_1.executeQuery)(query, [status]);
  93. }
  94. static async getCount() {
  95. const query = 'SELECT COUNT(*) as count FROM client_auth';
  96. const result = await (0, database_1.executeQuery)(query);
  97. return result[0].count;
  98. }
  99. static async getStatusStats() {
  100. try {
  101. const totalCountQuery = 'SELECT COUNT(*) as count FROM client_auth';
  102. const totalResult = await (0, database_1.executeQuery)(totalCountQuery);
  103. const total = totalResult[0].count;
  104. const statusQuery = `
  105. SELECT
  106. status,
  107. COUNT(*) as count
  108. FROM client_auth
  109. GROUP BY status
  110. `;
  111. const statusResults = await (0, database_1.executeQuery)(statusQuery);
  112. const superuserQuery = 'SELECT COUNT(*) as count FROM client_auth WHERE is_superuser = 1';
  113. const superuserResult = await (0, database_1.executeQuery)(superuserQuery);
  114. const superuserCount = superuserResult[0].count;
  115. let activeCount = 0;
  116. let inactiveCount = 0;
  117. statusResults.forEach((row) => {
  118. if (row.status === 'enabled') {
  119. activeCount = row.count;
  120. }
  121. else if (row.status === 'disabled') {
  122. inactiveCount = row.count;
  123. }
  124. });
  125. return {
  126. total,
  127. active: activeCount,
  128. inactive: inactiveCount,
  129. superuser: superuserCount
  130. };
  131. }
  132. catch (error) {
  133. console.error('获取客户端认证统计信息失�?', error);
  134. throw error;
  135. }
  136. }
  137. static async getDeviceTypeStats() {
  138. const query = `
  139. SELECT
  140. device_type,
  141. COUNT(*) as count
  142. FROM client_auth
  143. GROUP BY device_type
  144. ORDER BY count DESC
  145. `;
  146. return await (0, database_1.executeQuery)(query);
  147. }
  148. static async create(clientAuthData) {
  149. const useSalt = clientAuthData.use_salt !== undefined ? clientAuthData.use_salt : true;
  150. if (useSalt && !clientAuthData.salt) {
  151. clientAuthData.salt = this.generateSalt();
  152. }
  153. if (!useSalt) {
  154. clientAuthData.salt = '';
  155. }
  156. if (clientAuthData.password && !clientAuthData.password_hash) {
  157. clientAuthData.password_hash = this.generatePasswordHash(clientAuthData.password, clientAuthData.salt, useSalt);
  158. }
  159. const query = `
  160. 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)
  161. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  162. `;
  163. const values = [
  164. clientAuthData.username,
  165. clientAuthData.clientid,
  166. clientAuthData.password_hash,
  167. clientAuthData.salt,
  168. useSalt ? 1 : 0,
  169. clientAuthData.status || 'enabled',
  170. clientAuthData.device_type || 'unknown',
  171. clientAuthData.description || null,
  172. clientAuthData.is_superuser ? 1 : 0,
  173. clientAuthData.auth_method || 'password',
  174. clientAuthData.auth_expiry || null,
  175. clientAuthData.allowed_ip_ranges || null,
  176. clientAuthData.allowed_time_ranges || null,
  177. clientAuthData.auth_policy_id || null
  178. ];
  179. const result = await (0, database_1.executeQuery)(query, values);
  180. return this.getById(result.insertId);
  181. }
  182. static async update(id, updateData) {
  183. const fields = [];
  184. const values = [];
  185. if (updateData.username !== undefined) {
  186. fields.push('username = ?');
  187. values.push(updateData.username);
  188. }
  189. if (updateData.clientid !== undefined) {
  190. fields.push('clientid = ?');
  191. values.push(updateData.clientid);
  192. }
  193. if (updateData.password_hash !== undefined) {
  194. fields.push('password_hash = ?');
  195. values.push(updateData.password_hash);
  196. }
  197. if (updateData.salt !== undefined) {
  198. fields.push('salt = ?');
  199. values.push(updateData.salt);
  200. }
  201. if (updateData.use_salt !== undefined) {
  202. fields.push('use_salt = ?');
  203. values.push(updateData.use_salt ? 1 : 0);
  204. }
  205. if (updateData.status !== undefined) {
  206. fields.push('status = ?');
  207. values.push(updateData.status);
  208. }
  209. if (updateData.device_type !== undefined) {
  210. fields.push('device_type = ?');
  211. values.push(updateData.device_type);
  212. }
  213. if (updateData.description !== undefined) {
  214. fields.push('description = ?');
  215. values.push(updateData.description);
  216. }
  217. if (updateData.is_superuser !== undefined) {
  218. fields.push('is_superuser = ?');
  219. values.push(updateData.is_superuser ? 1 : 0);
  220. }
  221. if (updateData.last_login_at !== undefined) {
  222. fields.push('last_login_at = ?');
  223. values.push(updateData.last_login_at);
  224. }
  225. if (updateData.auth_method !== undefined) {
  226. fields.push('auth_method = ?');
  227. values.push(updateData.auth_method);
  228. }
  229. if (updateData.auth_expiry !== undefined) {
  230. fields.push('auth_expiry = ?');
  231. values.push(updateData.auth_expiry);
  232. }
  233. if (updateData.allowed_ip_ranges !== undefined) {
  234. fields.push('allowed_ip_ranges = ?');
  235. values.push(updateData.allowed_ip_ranges);
  236. }
  237. if (updateData.allowed_time_ranges !== undefined) {
  238. fields.push('allowed_time_ranges = ?');
  239. values.push(updateData.allowed_time_ranges);
  240. }
  241. if (updateData.auth_policy_id !== undefined) {
  242. fields.push('auth_policy_id = ?');
  243. values.push(updateData.auth_policy_id);
  244. }
  245. fields.push('updated_at = CURRENT_TIMESTAMP');
  246. const query = `UPDATE client_auth SET ${fields.join(', ')} WHERE id = ?`;
  247. values.push(id);
  248. await (0, database_1.executeQuery)(query, values);
  249. return this.getById(id);
  250. }
  251. static async updatePassword(id, newPassword, useSalt = true) {
  252. const salt = useSalt ? this.generateSalt() : '';
  253. const passwordHash = this.generatePasswordHash(newPassword, salt, useSalt);
  254. const query = 'UPDATE client_auth SET password_hash = ?, salt = ?, use_salt = ?, updated_at = NOW() WHERE id = ?';
  255. const result = await (0, database_1.executeQuery)(query, [passwordHash, salt, useSalt ? 1 : 0, id]);
  256. return result.affectedRows > 0;
  257. }
  258. static async delete(id) {
  259. const query = 'DELETE FROM client_auth WHERE id = ?';
  260. const result = await (0, database_1.executeQuery)(query, [id]);
  261. return result.affectedRows > 0;
  262. }
  263. static async search(searchTerm, limit, offset) {
  264. let query = `
  265. SELECT id, username, clientid, status, device_type, description, is_superuser, use_salt, salt, created_at, updated_at, last_login_at
  266. FROM client_auth
  267. WHERE username LIKE ? OR clientid LIKE ? OR device_type LIKE ? OR description LIKE ?
  268. ORDER BY created_at DESC
  269. `;
  270. const params = [`%${searchTerm}%`, `%${searchTerm}%`, `%${searchTerm}%`, `%${searchTerm}%`];
  271. if (limit !== undefined) {
  272. query += ' LIMIT ?';
  273. params.push(limit);
  274. if (offset !== undefined) {
  275. query += ' OFFSET ?';
  276. params.push(offset);
  277. }
  278. }
  279. return await (0, database_1.executeQuery)(query, params);
  280. }
  281. static async getSearchCount(searchTerm) {
  282. const query = `
  283. SELECT COUNT(*) as count
  284. FROM client_auth
  285. WHERE username LIKE ? OR clientid LIKE ? OR device_type LIKE ? OR description LIKE ?
  286. `;
  287. const params = [`%${searchTerm}%`, `%${searchTerm}%`, `%${searchTerm}%`, `%${searchTerm}%`];
  288. const result = await (0, database_1.executeQuery)(query, params);
  289. return result[0].count;
  290. }
  291. static async getByUsername(username) {
  292. const query = 'SELECT * FROM client_auth WHERE username = ?';
  293. const clients = await (0, database_1.executeQuery)(query, [username]);
  294. return clients.length > 0 ? clients[0] : null;
  295. }
  296. static async getByClientId(clientid) {
  297. const query = 'SELECT * FROM client_auth WHERE clientid = ?';
  298. const clients = await (0, database_1.executeQuery)(query, [clientid]);
  299. return clients.length > 0 ? clients[0] : null;
  300. }
  301. static async verifyClient(username, clientid, password) {
  302. const clientAuth = await this.getByUsernameAndClientid(username, clientid);
  303. if (!clientAuth || clientAuth.status !== 'enabled') {
  304. return false;
  305. }
  306. const useSalt = clientAuth.use_salt !== undefined ? clientAuth.use_salt : true;
  307. return this.verifyPassword(password, clientAuth.salt, clientAuth.password_hash, useSalt);
  308. }
  309. static async getAuthMethods() {
  310. const query = 'SELECT * FROM auth_methods ORDER BY method_name';
  311. return await (0, database_1.executeQuery)(query);
  312. }
  313. static async getAuthMethodById(id) {
  314. const query = 'SELECT * FROM auth_methods WHERE id = ?';
  315. const methods = await (0, database_1.executeQuery)(query, [id]);
  316. return methods.length > 0 ? methods[0] : null;
  317. }
  318. static async getAuthMethodByName(name) {
  319. const query = 'SELECT * FROM auth_methods WHERE method_name = ?';
  320. const methods = await (0, database_1.executeQuery)(query, [name]);
  321. return methods.length > 0 ? methods[0] : null;
  322. }
  323. static async createAuthMethod(authMethod) {
  324. const query = `
  325. INSERT INTO auth_methods (method_name, method_type, config, is_active)
  326. VALUES (?, ?, ?, ?)
  327. `;
  328. const values = [
  329. authMethod.method_name,
  330. authMethod.method_type,
  331. authMethod.config,
  332. authMethod.is_active ? 1 : 0
  333. ];
  334. const result = await (0, database_1.executeQuery)(query, values);
  335. return this.getAuthMethodById(result.insertId);
  336. }
  337. static async updateAuthMethod(id, updateData) {
  338. const fields = [];
  339. const values = [];
  340. if (updateData.method_name !== undefined) {
  341. fields.push('method_name = ?');
  342. values.push(updateData.method_name);
  343. }
  344. if (updateData.method_type !== undefined) {
  345. fields.push('method_type = ?');
  346. values.push(updateData.method_type);
  347. }
  348. if (updateData.config !== undefined) {
  349. fields.push('config = ?');
  350. values.push(updateData.config);
  351. }
  352. if (updateData.is_active !== undefined) {
  353. fields.push('is_active = ?');
  354. values.push(updateData.is_active ? 1 : 0);
  355. }
  356. fields.push('updated_at = CURRENT_TIMESTAMP');
  357. const query = `UPDATE auth_methods SET ${fields.join(', ')} WHERE id = ?`;
  358. values.push(id);
  359. await (0, database_1.executeQuery)(query, values);
  360. return this.getAuthMethodById(id);
  361. }
  362. static async deleteAuthMethod(id) {
  363. const query = 'DELETE FROM auth_methods WHERE id = ?';
  364. const result = await (0, database_1.executeQuery)(query, [id]);
  365. return result.affectedRows > 0;
  366. }
  367. static async getAuthPolicies() {
  368. const query = 'SELECT * FROM auth_policies ORDER BY priority DESC, created_at ASC';
  369. return await (0, database_1.executeQuery)(query);
  370. }
  371. static async getAuthPolicyById(id) {
  372. const query = 'SELECT * FROM auth_policies WHERE id = ?';
  373. const policies = await (0, database_1.executeQuery)(query, [id]);
  374. return policies.length > 0 ? policies[0] : null;
  375. }
  376. static async createAuthPolicy(authPolicy) {
  377. const query = `
  378. INSERT INTO auth_policies (policy_name, priority, conditions, actions, is_active, description)
  379. VALUES (?, ?, ?, ?, ?, ?)
  380. `;
  381. const values = [
  382. authPolicy.policy_name,
  383. authPolicy.priority,
  384. authPolicy.conditions,
  385. authPolicy.actions,
  386. authPolicy.is_active ? 1 : 0,
  387. authPolicy.description || null
  388. ];
  389. const result = await (0, database_1.executeQuery)(query, values);
  390. return this.getAuthPolicyById(result.insertId);
  391. }
  392. static async updateAuthPolicy(id, updateData) {
  393. const fields = [];
  394. const values = [];
  395. if (updateData.policy_name !== undefined) {
  396. fields.push('policy_name = ?');
  397. values.push(updateData.policy_name);
  398. }
  399. if (updateData.priority !== undefined) {
  400. fields.push('priority = ?');
  401. values.push(updateData.priority);
  402. }
  403. if (updateData.conditions !== undefined) {
  404. fields.push('conditions = ?');
  405. values.push(updateData.conditions);
  406. }
  407. if (updateData.actions !== undefined) {
  408. fields.push('actions = ?');
  409. values.push(updateData.actions);
  410. }
  411. if (updateData.is_active !== undefined) {
  412. fields.push('is_active = ?');
  413. values.push(updateData.is_active ? 1 : 0);
  414. }
  415. if (updateData.description !== undefined) {
  416. fields.push('description = ?');
  417. values.push(updateData.description);
  418. }
  419. fields.push('updated_at = CURRENT_TIMESTAMP');
  420. const query = `UPDATE auth_policies SET ${fields.join(', ')} WHERE id = ?`;
  421. values.push(id);
  422. await (0, database_1.executeQuery)(query, values);
  423. return this.getAuthPolicyById(id);
  424. }
  425. static async deleteAuthPolicy(id) {
  426. const query = 'DELETE FROM auth_policies WHERE id = ?';
  427. const result = await (0, database_1.executeQuery)(query, [id]);
  428. return result.affectedRows > 0;
  429. }
  430. static async getClientTokens(clientid) {
  431. const query = 'SELECT * FROM client_tokens WHERE clientid = ? ORDER BY created_at DESC';
  432. return await (0, database_1.executeQuery)(query, [clientid]);
  433. }
  434. static async getClientTokenByValue(tokenValue) {
  435. const query = 'SELECT * FROM client_tokens WHERE token_value = ?';
  436. const tokens = await (0, database_1.executeQuery)(query, [tokenValue]);
  437. return tokens.length > 0 ? tokens[0] : null;
  438. }
  439. static async createClientToken(clientToken) {
  440. const query = `
  441. INSERT INTO client_tokens (clientid, token_type, token_value, expires_at, status)
  442. VALUES (?, ?, ?, ?, ?)
  443. `;
  444. const values = [
  445. clientToken.clientid,
  446. clientToken.token_type,
  447. clientToken.token_value,
  448. clientToken.expires_at,
  449. clientToken.status || 'active'
  450. ];
  451. const result = await (0, database_1.executeQuery)(query, values);
  452. const query2 = 'SELECT * FROM client_tokens WHERE id = ?';
  453. const tokens = await (0, database_1.executeQuery)(query2, [result.insertId]);
  454. return tokens[0];
  455. }
  456. static async updateClientToken(id, updateData) {
  457. const fields = [];
  458. const values = [];
  459. if (updateData.clientid !== undefined) {
  460. fields.push('clientid = ?');
  461. values.push(updateData.clientid);
  462. }
  463. if (updateData.token_type !== undefined) {
  464. fields.push('token_type = ?');
  465. values.push(updateData.token_type);
  466. }
  467. if (updateData.token_value !== undefined) {
  468. fields.push('token_value = ?');
  469. values.push(updateData.token_value);
  470. }
  471. if (updateData.expires_at !== undefined) {
  472. fields.push('expires_at = ?');
  473. values.push(updateData.expires_at);
  474. }
  475. if (updateData.status !== undefined) {
  476. fields.push('status = ?');
  477. values.push(updateData.status);
  478. }
  479. fields.push('updated_at = CURRENT_TIMESTAMP');
  480. const query = `UPDATE client_tokens SET ${fields.join(', ')} WHERE id = ?`;
  481. values.push(id);
  482. await (0, database_1.executeQuery)(query, values);
  483. const query2 = 'SELECT * FROM client_tokens WHERE id = ?';
  484. const tokens = await (0, database_1.executeQuery)(query2, [id]);
  485. return tokens.length > 0 ? tokens[0] : null;
  486. }
  487. static async deleteClientToken(id) {
  488. const query = 'DELETE FROM client_tokens WHERE id = ?';
  489. const result = await (0, database_1.executeQuery)(query, [id]);
  490. return result.affectedRows > 0;
  491. }
  492. static async getClientCertificates(clientid) {
  493. const query = 'SELECT * FROM client_certificates WHERE clientid = ? ORDER BY created_at DESC';
  494. return await (0, database_1.executeQuery)(query, [clientid]);
  495. }
  496. static async getClientCertificateByFingerprint(fingerprint) {
  497. const query = 'SELECT * FROM client_certificates WHERE fingerprint = ?';
  498. const certificates = await (0, database_1.executeQuery)(query, [fingerprint]);
  499. return certificates.length > 0 ? certificates[0] : null;
  500. }
  501. static async createClientCertificate(clientCertificate) {
  502. const query = `
  503. INSERT INTO client_certificates (clientid, certificate_pem, fingerprint, expires_at, status)
  504. VALUES (?, ?, ?, ?, ?)
  505. `;
  506. const values = [
  507. clientCertificate.clientid,
  508. clientCertificate.certificate_pem,
  509. clientCertificate.fingerprint,
  510. clientCertificate.expires_at,
  511. clientCertificate.status || 'active'
  512. ];
  513. const result = await (0, database_1.executeQuery)(query, values);
  514. const query2 = 'SELECT * FROM client_certificates WHERE id = ?';
  515. const certificates = await (0, database_1.executeQuery)(query2, [result.insertId]);
  516. return certificates[0];
  517. }
  518. static async updateClientCertificate(id, updateData) {
  519. const fields = [];
  520. const values = [];
  521. if (updateData.clientid !== undefined) {
  522. fields.push('clientid = ?');
  523. values.push(updateData.clientid);
  524. }
  525. if (updateData.certificate_pem !== undefined) {
  526. fields.push('certificate_pem = ?');
  527. values.push(updateData.certificate_pem);
  528. }
  529. if (updateData.fingerprint !== undefined) {
  530. fields.push('fingerprint = ?');
  531. values.push(updateData.fingerprint);
  532. }
  533. if (updateData.expires_at !== undefined) {
  534. fields.push('expires_at = ?');
  535. values.push(updateData.expires_at);
  536. }
  537. if (updateData.status !== undefined) {
  538. fields.push('status = ?');
  539. values.push(updateData.status);
  540. }
  541. fields.push('updated_at = CURRENT_TIMESTAMP');
  542. const query = `UPDATE client_certificates SET ${fields.join(', ')} WHERE id = ?`;
  543. values.push(id);
  544. await (0, database_1.executeQuery)(query, values);
  545. const query2 = 'SELECT * FROM client_certificates WHERE id = ?';
  546. const certificates = await (0, database_1.executeQuery)(query2, [id]);
  547. return certificates.length > 0 ? certificates[0] : null;
  548. }
  549. static async deleteClientCertificate(id) {
  550. const query = 'DELETE FROM client_certificates WHERE id = ?';
  551. const result = await (0, database_1.executeQuery)(query, [id]);
  552. return result.affectedRows > 0;
  553. }
  554. static async dynamicAuthVerify(username, clientid, authData, ipAddress) {
  555. try {
  556. const clientAuth = await this.getByUsernameAndClientid(username, clientid);
  557. if (!clientAuth) {
  558. return { success: false, reason: 'Client not found' };
  559. }
  560. if (clientAuth.status !== 'enabled') {
  561. return { success: false, reason: 'Client is disabled' };
  562. }
  563. if (clientAuth.auth_expiry && new Date(clientAuth.auth_expiry) < new Date()) {
  564. return { success: false, reason: 'Authentication expired' };
  565. }
  566. if (clientAuth.allowed_ip_ranges && ipAddress) {
  567. const allowedRanges = JSON.parse(clientAuth.allowed_ip_ranges);
  568. if (!this.isIpAllowed(ipAddress, allowedRanges)) {
  569. return { success: false, reason: 'IP address not allowed' };
  570. }
  571. }
  572. if (clientAuth.allowed_time_ranges) {
  573. const allowedTimeRanges = JSON.parse(clientAuth.allowed_time_ranges);
  574. if (!this.isTimeAllowed(allowedTimeRanges)) {
  575. return { success: false, reason: 'Access not allowed at this time' };
  576. }
  577. }
  578. let authResult = { success: false, reason: 'Authentication method not supported' };
  579. if (clientAuth.auth_method) {
  580. const authMethod = await this.getAuthMethodByName(clientAuth.auth_method);
  581. if (authMethod && authMethod.is_active) {
  582. authResult = await this.verifyByMethod(authMethod, clientAuth, authData);
  583. }
  584. }
  585. else {
  586. const useSalt = clientAuth.use_salt !== undefined ? clientAuth.use_salt : true;
  587. const isValid = this.verifyPassword(authData.password || '', clientAuth.salt, clientAuth.password_hash, useSalt);
  588. authResult = {
  589. success: isValid,
  590. reason: isValid ? 'Authentication successful' : 'Invalid password'
  591. };
  592. }
  593. if (!authResult.success) {
  594. return authResult;
  595. }
  596. if (clientAuth.auth_policy_id) {
  597. const policy = await this.getAuthPolicyById(clientAuth.auth_policy_id);
  598. if (policy && policy.is_active) {
  599. const policyResult = await this.applyAuthPolicy(policy, clientAuth, authData, ipAddress);
  600. if (!policyResult.success) {
  601. return policyResult;
  602. }
  603. return { success: true, policy };
  604. }
  605. }
  606. return { success: true };
  607. }
  608. catch (error) {
  609. console.error('Dynamic authentication error:', error);
  610. return { success: false, reason: 'Internal authentication error' };
  611. }
  612. }
  613. static async verifyByMethod(authMethod, clientAuth, authData) {
  614. const config = JSON.parse(authMethod.config);
  615. switch (authMethod.method_type) {
  616. case 'password':
  617. const useSalt = clientAuth.use_salt !== undefined ? clientAuth.use_salt : true;
  618. const isValid = this.verifyPassword(authData.password || '', clientAuth.salt, clientAuth.password_hash, useSalt);
  619. return {
  620. success: isValid,
  621. reason: isValid ? 'Authentication successful' : 'Invalid password'
  622. };
  623. case 'token':
  624. if (authData.token) {
  625. const token = await this.getClientTokenByValue(authData.token);
  626. if (token && token.status === 'active' && token.expires_at > new Date()) {
  627. return { success: true };
  628. }
  629. return { success: false, reason: 'Invalid or expired token' };
  630. }
  631. return { success: false, reason: 'Token required' };
  632. case 'certificate':
  633. if (authData.fingerprint) {
  634. const certificate = await this.getClientCertificateByFingerprint(authData.fingerprint);
  635. if (certificate && certificate.status === 'active' && certificate.expires_at > new Date()) {
  636. return { success: true };
  637. }
  638. return { success: false, reason: 'Invalid or expired certificate' };
  639. }
  640. return { success: false, reason: 'Certificate fingerprint required' };
  641. case 'external':
  642. return { success: false, reason: 'External authentication not implemented' };
  643. default:
  644. return { success: false, reason: 'Unknown authentication method' };
  645. }
  646. }
  647. static async applyAuthPolicy(policy, clientAuth, authData, ipAddress) {
  648. const conditions = JSON.parse(policy.conditions);
  649. const actions = JSON.parse(policy.actions);
  650. for (const condition of conditions) {
  651. let conditionMet = false;
  652. switch (condition.type) {
  653. case 'time_range':
  654. if (condition.value && Array.isArray(condition.value)) {
  655. conditionMet = this.isTimeAllowed(condition.value);
  656. }
  657. break;
  658. case 'ip_range':
  659. if (condition.value && Array.isArray(condition.value) && ipAddress) {
  660. conditionMet = this.isIpAllowed(ipAddress, condition.value);
  661. }
  662. break;
  663. case 'device_type':
  664. if (condition.value && clientAuth.device_type) {
  665. conditionMet = clientAuth.device_type === condition.value;
  666. }
  667. break;
  668. case 'custom':
  669. conditionMet = true;
  670. break;
  671. }
  672. if (!conditionMet) {
  673. if (condition.action === 'deny') {
  674. return { success: false, reason: `Policy condition not met: ${condition.type}` };
  675. }
  676. }
  677. }
  678. for (const action of actions) {
  679. switch (action.type) {
  680. case 'log':
  681. console.log(`Auth policy applied: ${policy.policy_name} for client ${clientAuth.clientid}`);
  682. break;
  683. case 'notify':
  684. console.log(`Notification sent for auth policy: ${policy.policy_name}`);
  685. break;
  686. case 'custom':
  687. break;
  688. }
  689. }
  690. return { success: true };
  691. }
  692. static isIpAllowed(ip, allowedRanges) {
  693. if (allowedRanges.includes('0.0.0.0/0')) {
  694. return true;
  695. }
  696. if (allowedRanges.includes(ip)) {
  697. return true;
  698. }
  699. return false;
  700. }
  701. static isTimeAllowed(timeRanges) {
  702. if (!timeRanges || timeRanges.length === 0) {
  703. return true;
  704. }
  705. const now = new Date();
  706. const currentHour = now.getHours();
  707. const currentDay = now.getDay();
  708. for (const range of timeRanges) {
  709. if (range.days && range.days.includes(currentDay)) {
  710. if (range.start_hour !== undefined && range.end_hour !== undefined) {
  711. if (currentHour >= range.start_hour && currentHour <= range.end_hour) {
  712. return true;
  713. }
  714. }
  715. else {
  716. return true;
  717. }
  718. }
  719. }
  720. return false;
  721. }
  722. static async findByUsernameAndClientId(username, clientid) {
  723. const query = 'SELECT * FROM client_auth WHERE username = ? AND clientid = ? AND status = ?';
  724. const clients = await (0, database_1.executeQuery)(query, [username, clientid, 'enabled']);
  725. return clients.length > 0 ? clients[0] : null;
  726. }
  727. static async findByUsername(username) {
  728. const query = 'SELECT * FROM client_auth WHERE username = ? LIMIT 1';
  729. const clients = await (0, database_1.executeQuery)(query, [username]);
  730. return clients.length > 0 ? clients[0] : null;
  731. }
  732. static async updateLastLogin(username, clientid) {
  733. const query = 'UPDATE client_auth SET last_login_at = NOW() WHERE username = ? AND clientid = ?';
  734. await (0, database_1.executeQuery)(query, [username, clientid]);
  735. }
  736. static async logAuthEvent(clientid, username, operationType, result, reason, ipAddress, topic, authMethod, policyId, executionTime) {
  737. const query = `
  738. INSERT INTO auth_log (clientid, username, ip_address, operation_type, result, reason, topic, auth_method, auth_policy_id, execution_time_ms)
  739. VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
  740. `;
  741. const values = [
  742. clientid,
  743. username,
  744. ipAddress || null,
  745. operationType,
  746. result,
  747. reason || null,
  748. topic || null,
  749. authMethod || null,
  750. policyId || null,
  751. executionTime || null
  752. ];
  753. await (0, database_1.executeQuery)(query, values);
  754. }
  755. }
  756. exports.ClientAuthModel = ClientAuthModel;
  757. //# sourceMappingURL=clientAuth.js.map