generated from azures04/Base-REST-API
Introduce bootstrap entrypoint and prestartup to ping DB and generate/manage RSA keypair. Add security module for key IO. Implement JWT-based access and refresh tokens (tokensService) with refresh_tokens table and repo. Add auth, provider and user services, and refresh-token management. Update repositories (users, credentials, providers, servers) with SQL fixes and new helper methods. Move DDL execution to bootstrap (remove from server). Update package.json main and add dependencies (bcryptjs, jsonwebtoken). Update .env.example and .gitignore accordingly.
71 lines
2.1 KiB
JavaScript
71 lines
2.1 KiB
JavaScript
const { pool } = require("../modules/database")
|
|
const { DefaultError } = require("../errors/errors")
|
|
|
|
async function create(userId, tokenHash, expiresAt) {
|
|
try {
|
|
const sql = "INSERT INTO refresh_tokens (userId, tokenHash, expiresAt) VALUES (?, ?, ?)"
|
|
const rows = await pool.query(sql, [userId, tokenHash, expiresAt])
|
|
return rows.affectedRows > 0
|
|
} catch (error) {
|
|
throw new DefaultError(500, "Internal Server Error", error)
|
|
}
|
|
}
|
|
|
|
async function findByTokenHash(tokenHash) {
|
|
try {
|
|
const sql = "SELECT * FROM refresh_tokens WHERE tokenHash = ?"
|
|
const rows = await pool.query(sql, [tokenHash])
|
|
return rows[0] || null
|
|
} catch (error) {
|
|
throw new DefaultError(500, "Internal Server Error", error)
|
|
}
|
|
}
|
|
|
|
async function findByUserId(userId) {
|
|
try {
|
|
const sql = "SELECT * FROM refresh_tokens WHERE userId = ?"
|
|
const rows = await pool.query(sql, [userId])
|
|
return rows[0] || []
|
|
} catch (error) {
|
|
throw new DefaultError(500, "Internal Server Error", error)
|
|
}
|
|
}
|
|
|
|
async function removeByTokenHash(tokenHash) {
|
|
try {
|
|
const sql = "DELETE FROM refresh_tokens WHERE tokenHash = ?"
|
|
const rows = await pool.query(sql, [tokenHash])
|
|
return rows.affectedRows > 0
|
|
} catch (error) {
|
|
throw new DefaultError(500, "Internal Server Error", error)
|
|
}
|
|
}
|
|
|
|
async function removeByUserId(userId) {
|
|
try {
|
|
const sql = "DELETE FROM refresh_tokens WHERE userId = ?"
|
|
const rows = await pool.query(sql, [userId])
|
|
return rows.affectedRows > 0
|
|
} catch (error) {
|
|
throw new DefaultError(500, "Internal Server Error", error)
|
|
}
|
|
}
|
|
|
|
async function removeExpired() {
|
|
try {
|
|
const sql = "DELETE FROM refresh_tokens WHERE expiresAt < NOW()"
|
|
const rows = await pool.query(sql)
|
|
return rows.affectedRows
|
|
} catch (error) {
|
|
throw new DefaultError(500, "Internal Server Error", error)
|
|
}
|
|
}
|
|
|
|
module.exports = {
|
|
create,
|
|
findByTokenHash,
|
|
findByUserId,
|
|
removeByTokenHash,
|
|
removeByUserId,
|
|
removeExpired,
|
|
} |