Skip to content

Commit

Permalink
UNTRACKED(chore): replace pg with knex in sessions db functions (#118)
Browse files Browse the repository at this point in the history
* chore: replace pg with knex in sessions

* fix error in refresh token
  • Loading branch information
mikelax authored Sep 4, 2024
1 parent ef5c6a3 commit 89caa16
Show file tree
Hide file tree
Showing 14 changed files with 150 additions and 123 deletions.
97 changes: 59 additions & 38 deletions database/layer/admin-session.js
Original file line number Diff line number Diff line change
@@ -1,46 +1,55 @@
const crypto = require('node:crypto')
const { PGPool } = require('./pg_pool')
const pool = new PGPool()

function getAdminSessionView () {
return `SELECT p.key AS personakey, s.event_id, s.authorization_time, s.scope, s.idp_token
FROM usher.tenants t
JOIN usher.personas p ON p.tenantkey = t.key
JOIN usher.sessions s ON s.personakey = p.key`
}

function getAdminTenantPersonaView () {
return `SELECT p.key as personakey
FROM usher.tenants t
JOIN usher.personas p ON p.tenantkey = t.key`
}
const { usherDb } = require('./knex')

async function getSessionPersonaKey (subClaim, userContext = '', issClaim) {
const sql = getAdminSessionView() + ' WHERE sub_claim = $1 AND p.user_context = $2 AND iss_claim = $3'
const sessionKeyResult = await pool.query(sql, [subClaim, userContext, issClaim])
return (sessionKeyResult.rows.length === 0 ? null : sessionKeyResult.rows[0].personakey)
const results = await usherDb('tenants as t')
.join('personas as p', 't.key', '=', 'p.tenantkey')
.join('sessions as s', 'p.key', '=', 's.personakey')
.select('p.key as personakey', 's.event_id', 's.authorization_time', 's.scope', 's.idp_token')
.where('sub_claim', subClaim)
.where('p.user_context', userContext)
.where('iss_claim', issClaim)

return (results.length === 0 ? null : results[0].personakey)
}

async function getPersonaKey (subClaim, userContext = '', issClaim) {
const sql = getAdminTenantPersonaView() + ' WHERE sub_claim = $1 AND p.user_context = $2 AND iss_claim = $3'
const personaKeyResult = await pool.query(sql, [subClaim, userContext, issClaim])
return personaKeyResult.rows.length === 0 ? null : personaKeyResult.rows[0].personakey
const results = await usherDb('tenants as t')
.join('personas as p', 't.key', '=', 'p.tenantkey')
.select('p.key as personakey')
.where('sub_claim', subClaim)
.where('p.user_context', userContext)
.where('iss_claim', issClaim)

return results.length === 0 ? null : results[0].personakey
}

/**
* Gets the most recent session record for the given User
* @param {string} subClaim
* @param {string} userContext
* @param {string} issClaim
* @returns An object representing the session record or null if no session exists
*/
async function getSessionBySubIss (subClaim, userContext, issClaim) {
const personaKey = await getSessionPersonaKey(subClaim, userContext, issClaim)
if (!personaKey) {
return null
}
const sql = 'SELECT * FROM usher.sessions WHERE personakey = $1'
const sessionRowResult = await pool.query(sql, [personaKey])
return sessionRowResult.rows[0]
const results = await usherDb('sessions').select().where('personakey', personaKey)
.orderBy('authorization_time', 'desc')
.first()
return results || null // force null return if no results instead of undefined
}

/**
* Get a session record by a given session `event_id`
* @param {string} eventId The session event_id to look up
* @returns An object representing the session record
*/
async function getSessionByEventId (eventId) {
const sql = 'SELECT * FROM usher.sessions WHERE event_id = $1'
const sessionRowResult = await pool.query(sql, [eventId])
return sessionRowResult.rows.length === 0 ? null : sessionRowResult.rows[0]
const results = await usherDb('sessions').select().where('event_id', eventId)
return results.length === 0 ? null : results[0]
}

async function insertSessionBySubIss (
Expand All @@ -63,10 +72,16 @@ async function insertSessionBySubIss (
}

async function insertSessionByPersonaKey (personakey, eventId, authorizationTime, idpExpirationTime, scope, idpToken) {
const sql = `INSERT INTO usher.sessions
(personakey, event_id, authorization_time, idp_expirationtime, scope, idp_token)
VALUES ($1, $2, $3, $4, $5, $6)`
return pool.query(sql, [personakey, eventId, authorizationTime, idpExpirationTime, scope, idpToken])
const results = await usherDb('sessions').insert({
personakey,
event_id: eventId,
authorization_time: authorizationTime,
idp_expirationtime: idpExpirationTime,
scope,
idp_token: idpToken
})
.returning('*')
return results?.[0]
}

async function updateSessionBySubIss (subClaim, userContext, issClaim, authorizationTime, idpExpirationTime, scope, idpToken) {
Expand All @@ -75,9 +90,16 @@ async function updateSessionBySubIss (subClaim, userContext, issClaim, authoriza
throw new Error(`Session does not exist for persona (sub_claim=${subClaim} user_context = ${userContext} iss_claim=${issClaim})`)
}

const sql = 'UPDATE usher.sessions SET authorization_time = $1, idp_expirationtime = $2, scope = $3, idp_token = $4 WHERE personakey = $5'
const results = await pool.query(sql, [authorizationTime, idpExpirationTime, scope, idpToken, personaKey])
return results.rows
const [results] = await usherDb('sessions')
.where('personakey', personaKey)
.update({
authorization_time: authorizationTime,
idp_expirationtime: idpExpirationTime,
scope,
idp_token: idpToken
})
.returning('*')
return results
}

/**
Expand Down Expand Up @@ -110,10 +132,9 @@ async function deleteSessionBySubIss (subClaim, userContext, issClaim) {
return deleteReturn
}

async function deleteSessionByPersonaKey (personakey) {
const sql = 'DELETE FROM usher.sessions WHERE personakey = $1'
const deleteReturn = await pool.query(sql, [personakey])
if (deleteReturn.rowCount === 1) {
async function deleteSessionByPersonaKey (personaKey) {
const deleteResults = await usherDb('sessions').where('personakey', personaKey).del()
if (deleteResults === 1) {
return 'Delete successful'
} else {
return 'Delete unsuccessful'
Expand Down
54 changes: 25 additions & 29 deletions database/layer/view-select-entities.js
Original file line number Diff line number Diff line change
@@ -1,41 +1,37 @@
const { PGPool } = require('./pg_pool')
const pool = new PGPool()
const { usherDb } = require('./knex')

function getTenantsView () {
return `SELECT t.name AS tenantname, t.iss_claim, t.jwks_uri
FROM usher.tenants t`
}
async function selectIssuerJWKS (issClaim = '*') {
/**
*
* @param {string} issClaim ISS Claim to look up tenant by
* @returns
*/
async function selectIssuerJWKS (issClaim) {
try {
let sql = getTenantsView() + ' where 1=1'
const params = []
let paramCount = 0
if (issClaim !== '*') {
params.push(issClaim)
paramCount++
sql += ' and iss_claim = $' + paramCount
}
sql += ' LIMIT 1'
const results = await pool.query(sql, params)
return results.rows
const results = await usherDb('tenants')
.select('name as tenantname', 'iss_claim', 'jwks_uri')
.where('iss_claim', issClaim)
.limit(1)
return results
} catch (error) {
throw error.message
}
}

/**
* Get a list of clients, if clientId is not provided, return all clients
* @param {*} clientId
* @returns
*/
async function selectClients (clientId = '*') {
try {
let sql = `SELECT c.client_id, c.name as clientname, c.description, c.secret
FROM usher.clients c where 1=1 `
const params = []
let paramCount = 0
if (clientId !== '*') {
params.push(clientId)
paramCount++
sql += ' and client_id = $' + paramCount
}
const results = await pool.query(sql, params)
return results.rows
const results = await usherDb('clients')
.select('client_id', 'name as clientname', 'description', 'secret')
.modify((queryBuilder) => {
if (clientId !== '*') {
queryBuilder.where('client_id', clientId)
}
})
return results
} catch (error) {
throw error.message
}
Expand Down
58 changes: 24 additions & 34 deletions database/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

6 changes: 3 additions & 3 deletions database/package.json
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
{
"name": "@dmgt-tech/the-usher-server-database",
"version": "2.1.1",
"version": "2.1.2",
"description": "Database layer for TheUsher",
"scripts": {
"test": "mocha --exit",
Expand All @@ -24,9 +24,9 @@
"dependencies": {
"dotenv": "16.4.5",
"knex": "3.1.0",
"pg": "8.11.3"
"pg": "8.12.0"
},
"devDependencies": {
"mocha": "^10.7.0"
"mocha": "^10.7.3"
}
}
5 changes: 5 additions & 0 deletions database/test/db-client.test.js
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,11 @@ describe('Clients', function () {
const CLIENT_ACTUAL1 = await viewSelectEntities.selectClients('test-client1')
assert.strictEqual(JSON.stringify(CLIENT_ACTUAL1), JSON.stringify(CLIENT_EXPECTED1))
})

it('Should return multiple clients', async function () {
const results = await viewSelectEntities.selectClients()
assert(results.length >= 1, 'Expected more than one client')
})
})

describe('Test Client Roles requests', function () {
Expand Down
Loading

0 comments on commit 89caa16

Please sign in to comment.