67 lines
2.5 KiB
JavaScript
67 lines
2.5 KiB
JavaScript
"use strict";
|
|
Object.defineProperty(exports, "__esModule", { value: true });
|
|
exports.create = create;
|
|
exports.findByTokenHash = findByTokenHash;
|
|
exports.deleteByTokenHash = deleteByTokenHash;
|
|
exports.deleteByUserId = deleteByUserId;
|
|
exports.deleteExpired = deleteExpired;
|
|
exports.countActiveByUserId = countActiveByUserId;
|
|
exports.deleteOldestSessions = deleteOldestSessions;
|
|
const connection_1 = require("../db/connection");
|
|
/**
|
|
* Stores a new refresh token for a user.
|
|
*/
|
|
async function create(userId, tokenHash, expiresAt, meta) {
|
|
await (0, connection_1.query)(`INSERT INTO refresh_tokens (user_id, token_hash, expires_at, ip_address, user_agent)
|
|
VALUES ($1, $2, $3, $4, $5)`, [userId, tokenHash, expiresAt, meta?.ipAddress ?? null, meta?.userAgent ?? null]);
|
|
}
|
|
/**
|
|
* Finds a non-expired refresh token by its hash.
|
|
*/
|
|
async function findByTokenHash(tokenHash) {
|
|
const rows = await (0, connection_1.query)('SELECT user_id FROM refresh_tokens WHERE token_hash = $1 AND expires_at > NOW()', [tokenHash]);
|
|
return rows[0] || null;
|
|
}
|
|
/**
|
|
* Deletes a single refresh token by its hash (logout / rotation).
|
|
*/
|
|
async function deleteByTokenHash(tokenHash) {
|
|
const rows = await (0, connection_1.query)('DELETE FROM refresh_tokens WHERE token_hash = $1 RETURNING id', [tokenHash]);
|
|
return rows.length > 0;
|
|
}
|
|
/**
|
|
* Deletes all refresh tokens for a user (e.g. on logout or password change).
|
|
*/
|
|
async function deleteByUserId(userId) {
|
|
await (0, connection_1.query)('DELETE FROM refresh_tokens WHERE user_id = $1', [userId]);
|
|
}
|
|
/**
|
|
* Removes all refresh tokens that have passed their expiration time.
|
|
*/
|
|
async function deleteExpired() {
|
|
await (0, connection_1.query)('DELETE FROM refresh_tokens WHERE expires_at <= NOW()');
|
|
}
|
|
/**
|
|
* Counts non-expired refresh tokens for a user (active sessions).
|
|
*/
|
|
async function countActiveByUserId(userId) {
|
|
const rows = await (0, connection_1.query)('SELECT COUNT(*)::text AS count FROM refresh_tokens WHERE user_id = $1 AND expires_at > NOW()', [userId]);
|
|
return parseInt(rows[0]?.count ?? '0', 10);
|
|
}
|
|
/**
|
|
* Deletes the oldest active refresh tokens for a user (session eviction).
|
|
*/
|
|
async function deleteOldestSessions(userId, count) {
|
|
if (count <= 0)
|
|
return 0;
|
|
const rows = await (0, connection_1.query)(`DELETE FROM refresh_tokens
|
|
WHERE id IN (
|
|
SELECT id FROM refresh_tokens
|
|
WHERE user_id = $1 AND expires_at > NOW()
|
|
ORDER BY created_at ASC
|
|
LIMIT $2
|
|
)
|
|
RETURNING id`, [userId, count]);
|
|
return rows.length;
|
|
}
|
|
//# sourceMappingURL=refreshTokenRepository.js.map
|