Reduced database lookups when fetching impersonation data. Updated Twitch auth data on login.

This commit is contained in:
Tom
2025-01-09 16:34:14 +00:00
parent a72c7a0c1a
commit 53ff28c6f7

View File

@@ -49,7 +49,6 @@ passport.use(new JwtStrat({
const impersonation = await db.oneOrNone('SELECT id, name, role, "ttsDefaultVoice" FROM "User" WHERE id = $1', impersonationId.targetId);
if (impersonation) {
user.impersonation = impersonation;
console.log('found impersonation via jwt');
}
}
done(null, user);
@@ -86,12 +85,13 @@ passport.use(new OpenIDConnectStrategy({
db.none('UPDATE "User" SET name = $1 WHERE id = $2', [profile.username, profile.id]);
user.name = profile.username;
}
if (user.role == 'ADMIN' && user.impersonation == null) {
const impersonationId = await db.oneOrNone('SELECT "targetId" FROM "Impersonation" WHERE "sourceId" = $1', profile.id);
if (impersonationId) {
const impersonation = await db.oneOrNone('SELECT id, name, role, "ttsDefaultVoice" FROM "User" WHERE id = $1', impersonationId.targetId);
if (impersonation) {
user.impersonation = impersonation;
console.log('found impersonation via open id');
}
}
}
return done(null, user);
@@ -120,33 +120,25 @@ app.get('/api/auth/validate', [isApiKeyAuthenticated, isJWTAuthenticated], (req:
});
async function isApiKeyAuthenticated(req: any, res: any, next: any) {
if (!req.user) {
const key = req.get('x-api-key');
if (key && !req.user) {
if (key) {
const data = await db.oneOrNone('SELECT "userId" from "ApiKey" WHERE id = $1', key);
if (data) {
const user = await db.oneOrNone('SELECT id, name, role, "ttsDefaultVoice" FROM "User" WHERE id = $1', data.userId);
if (user.role == "ADMIN") {
const impersonationId = await db.oneOrNone('SELECT "targetId" FROM "Impersonation" WHERE "sourceId" = $1', data.userId);
if (impersonationId) {
const impersonation = await db.oneOrNone('SELECT id, name, role, "ttsDefaultVoice" FROM "User" WHERE id = $1', impersonationId.targetId);
if (impersonation) {
user.impersonation = impersonation;
console.log('found impersonation via api key');
req.user = await db.oneOrNone('SELECT id, name, role, "ttsDefaultVoice" FROM "User" WHERE id = $1', data.userId);
}
}
}
req.user = user
}
}
next();
}
function isWebAuthenticated(req: any, res: any, next: () => void) {
console.log('web authentication', req.user, req.sessionID, req.session);
function isNotAuthenticated(req: any, res: any, next: () => void) {
if (req.user) {
next();
return;
}
console.log('user is not authenticated.');
res.status(401).send({ message: 'User is not authenticated.' });
}
@@ -160,7 +152,20 @@ function isJWTAuthenticated(req: any, res: any, next: () => void) {
check(req, res, next);
}
const apiMiddlewares = [isApiKeyAuthenticated, isJWTAuthenticated, isWebAuthenticated]
async function updateImpersonation(req: any, res: any, next: () => void) {
if (req.user && req.user.role == 'ADMIN') {
const impersonationId = await db.oneOrNone('SELECT "targetId" FROM "Impersonation" WHERE "sourceId" = $1', req.user.id);
if (impersonationId) {
const impersonation = await db.oneOrNone('SELECT id, name, role, "ttsDefaultVoice" FROM "User" WHERE id = $1', impersonationId.targetId);
if (impersonation) {
req.user.impersonation = impersonation;
}
}
}
next();
}
const apiMiddlewares = [isApiKeyAuthenticated, isJWTAuthenticated, updateImpersonation, isNotAuthenticated]
app.get('/api/admin/users', apiMiddlewares, async (req: any, res: any, next: any) => {
if (req.user.role != 'ADMIN') {
@@ -246,7 +251,6 @@ app.delete('/api/keys', apiMiddlewares, async (req: any, res: any, next: any) =>
});
app.post("/api/auth/twitch/callback", async (req: any, res: any) => {
console.log(req.headers['user-agent']);
const query = `client_id=${process.env.AUTH_CLIENT_ID}&client_secret=${process.env.AUTH_CLIENT_SECRET}&code=${req.body.code}&grant_type=authorization_code&redirect_uri=${process.env.AUTH_REDIRECT_URI}`
const rest = new httpm.HttpClient(null);
const response = await rest.post('https://id.twitch.tv/oauth2/token', query, {
@@ -254,6 +258,7 @@ app.post("/api/auth/twitch/callback", async (req: any, res: any) => {
});
const body = await response.readBody();
const data = JSON.parse(body);
console.log('twitch auth data', data);
if (!data || data.message) {
console.log('Failed to validate Twitch code authentication:', data);
res.send({ authenticated: false });
@@ -280,8 +285,12 @@ app.post("/api/auth/twitch/callback", async (req: any, res: any) => {
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '30d' });
res.send({ authenticated: true, token: token });
var now = Date.now();
await db.none('UPDATE "Account" SET refresh_token = COALESCE($1, refresh_token), access_token = $2, id_token = COALESCE($3, id_token), expires_at = $4, scope = $5 WHERE "userId" = $6', [data.refresh_token, data.access_token, data.id_token, now + data.exp * 1000, data.scope, account.userId]);
return;
}
res.send({ authenticated: false });
});