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

@ -9,20 +9,20 @@ import * as httpm from 'typed-rest-client/HttpClient';
dotenv.config();
if (!process.env.CONNECTION_STRING) {
throw new Error("Cannot find connection string.");
throw new Error("Cannot find connection string.");
}
const pgp = pgPromise({});
const db = pgp(process.env.CONNECTION_STRING as string);
const limiter = rateLimit({
legacyHeaders: true,
standardHeaders: true,
windowMs: 15 * 60 * 1000,
limit: 200,
max: 2,
message: "Too many requests, please try again later.",
keyGenerator: (req: Request) => req.ip as string,
legacyHeaders: true,
standardHeaders: true,
windowMs: 15 * 60 * 1000,
limit: 200,
max: 2,
message: "Too many requests, please try again later.",
keyGenerator: (req: Request) => req.ip as string,
});
const app: Express = express();
@ -36,258 +36,267 @@ const passport = require('passport');
const JwtStrat = require('passport-jwt').Strategy;
const ExtractJwt = require('passport-jwt').ExtractJwt;
passport.use(new JwtStrat({
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
jwtFromRequest: ExtractJwt.fromAuthHeaderAsBearerToken(),
secretOrKey: process.env.JWT_SECRET,
}, async (jwt_payload: any, done: any) => {
console.log('jwt payload', jwt_payload);
const user = await db.oneOrNone('SELECT id, name, role, "ttsDefaultVoice" FROM "User" WHERE id = $1', jwt_payload.id);
console.log('jwt payload', jwt_payload);
const user = await db.oneOrNone('SELECT id, name, role, "ttsDefaultVoice" FROM "User" WHERE id = $1', jwt_payload.id);
console.log('jwt user', user);
if (user) {
const impersonationId = await db.oneOrNone('SELECT "targetId" FROM "Impersonation" WHERE "sourceId" = $1', jwt_payload.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 jwt');
}
}
done(null, user);
} else {
done(null, false);
console.log('jwt user', user);
if (user) {
const impersonationId = await db.oneOrNone('SELECT "targetId" FROM "Impersonation" WHERE "sourceId" = $1', jwt_payload.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;
}
}
done(null, user);
} else {
done(null, false);
}
}));
const session = require('express-session');
const OpenIDConnectStrategy = require('passport-openidconnect');
app.use(session({
key: 'passport',
secret: process.env.AUTH_SECRET,
resave: false,
saveUninitialized: false,
key: 'passport',
secret: process.env.AUTH_SECRET,
resave: false,
saveUninitialized: false,
}));
app.use(passport.initialize());
app.use(passport.session());
app.set('trust proxy', true);
passport.use(new OpenIDConnectStrategy({
issuer: 'https://id.twitch.tv/oauth2',
authorizationURL: 'https://id.twitch.tv/oauth2/authorize',
tokenURL: 'https://id.twitch.tv/oauth2/token',
clientID: process.env.AUTH_CLIENT_ID,
clientSecret: process.env.AUTH_CLIENT_SECRET,
callbackURL: process.env.AUTH_REDIRECT_URI,
scope: 'user_read'
issuer: 'https://id.twitch.tv/oauth2',
authorizationURL: 'https://id.twitch.tv/oauth2/authorize',
tokenURL: 'https://id.twitch.tv/oauth2/token',
clientID: process.env.AUTH_CLIENT_ID,
clientSecret: process.env.AUTH_CLIENT_SECRET,
callbackURL: process.env.AUTH_REDIRECT_URI,
scope: 'user_read'
}, async (url: any, profile: any, something: any, done: any) => {
console.log('login', 'pus:', profile, url, something);
const account: any = await db.oneOrNone('SELECT "userId" FROM "Account" WHERE "providerAccountId" = $1', profile.id);
if (account != null) {
const user: any = await db.oneOrNone('SELECT id, name, role, "ttsDefaultVoice" FROM "User" WHERE id = $1', account.userId);
if (user.name != profile.username) {
db.none('UPDATE "User" SET name = $1 WHERE id = $2', [profile.username, profile.id]);
user.name = profile.username;
}
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);
console.log('login', 'pus:', profile, url, something);
const account: any = await db.oneOrNone('SELECT "userId" FROM "Account" WHERE "providerAccountId" = $1', profile.id);
if (account != null) {
const user: any = await db.oneOrNone('SELECT id, name, role, "ttsDefaultVoice" FROM "User" WHERE id = $1', account.userId);
if (user.name != profile.username) {
db.none('UPDATE "User" SET name = $1 WHERE id = $2', [profile.username, profile.id]);
user.name = profile.username;
}
return done(new Error('Account does not exist.'), null);
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;
}
}
}
return done(null, user);
}
return done(new Error('Account does not exist.'), null);
}
));
passport.serializeUser((user: any, done: any) => {
if (!user)
return done(new Error('user is null'), null);
return done(null, user);
if (!user)
return done(new Error('user is null'), null);
return done(null, user);
});
passport.deserializeUser((user: any, done: any) => {
done(null, user);
done(null, user);
});
app.get('/api/auth', passport.authenticate("openidconnect", { failureRedirect: '/login' }), (req: Request, res: Response) => {
res.send('');
res.send('');
});
app.get('/api/auth/validate', [isApiKeyAuthenticated, isJWTAuthenticated], (req: any, res: Response, next: () => void) => {
const user = req?.user;
res.send({ authenticated: user != null, user: user });
const user = req?.user;
res.send({ authenticated: user != null, user: user });
});
async function isApiKeyAuthenticated(req: any, res: any, next: any) {
if (!req.user) {
const key = req.get('x-api-key');
if (key && !req.user) {
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 = user
}
if (key) {
const data = await db.oneOrNone('SELECT "userId" from "ApiKey" WHERE id = $1', key);
if (data) {
req.user = await db.oneOrNone('SELECT id, name, role, "ttsDefaultVoice" FROM "User" WHERE id = $1', data.userId);
}
}
next();
}
next();
}
function isWebAuthenticated(req: any, res: any, next: () => void) {
console.log('web authentication', req.user, req.sessionID, req.session);
if (req.user) {
next();
return;
}
res.status(401).send({ message: 'User is not authenticated.' });
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.' });
}
function isJWTAuthenticated(req: any, res: any, next: () => void) {
if (req.user) {
next();
return;
}
if (req.user) {
next();
return;
}
const check = passport.authenticate('jwt', { session: false });
check(req, res, next);
const check = passport.authenticate('jwt', { session: false });
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') {
res.status(403).send('You do not have the permissions for this.');
return;
}
if (req.user.role != 'ADMIN') {
res.status(403).send('You do not have the permissions for this.');
return;
}
const data = await db.manyOrNone('SELECT id, name FROM "User"');
res.send(data);
const data = await db.manyOrNone('SELECT id, name FROM "User"');
res.send(data);
});
app.put('/api/admin/impersonate', apiMiddlewares, async (req: any, res: any, next: any) => {
if (req.user.role != 'ADMIN') {
res.status(403).send('You do not have the permissions for this.');
return;
}
if (req.user.role != 'ADMIN') {
res.status(403).send('You do not have the permissions for this.');
return;
}
if (!req.body.impersonation) {
res.status(400).send('Invalid user.');
return;
}
const impersonation = await db.one('SELECT EXISTS (SELECT 1 FROM "User" WHERE id = $1)', req.body.impersonation);
if (!impersonation) {
res.status(400).send('Invalid user.');
return;
}
if (!req.body.impersonation) {
res.status(400).send('Invalid user.');
return;
}
const data = await db.oneOrNone('SELECT "targetId" FROM "Impersonation" where "sourceId" = $1', req.user.id);
if (!data?.targetId) {
const insert = await db.none('INSERT INTO "Impersonation" ("sourceId", "targetId") VALUES ($1, $2)', [req.user.id, req.body.impersonation]);
res.send(insert);
} else {
const update = await db.none('UPDATE "Impersonation" SET "targetId" = $2 WHERE "sourceId" = $1', [req.user.id, req.body.impersonation]);
res.send(update);
}
const impersonation = await db.one('SELECT EXISTS (SELECT 1 FROM "User" WHERE id = $1)', req.body.impersonation);
if (!impersonation) {
res.status(400).send('Invalid user.');
return;
}
const data = await db.oneOrNone('SELECT "targetId" FROM "Impersonation" where "sourceId" = $1', req.user.id);
if (!data?.targetId) {
const insert = await db.none('INSERT INTO "Impersonation" ("sourceId", "targetId") VALUES ($1, $2)', [req.user.id, req.body.impersonation]);
res.send(insert);
} else {
const update = await db.none('UPDATE "Impersonation" SET "targetId" = $2 WHERE "sourceId" = $1', [req.user.id, req.body.impersonation]);
res.send(update);
}
});
app.delete('/api/admin/impersonate', apiMiddlewares, async (req: any, res: any, next: any) => {
if (req.user.role != 'ADMIN') {
res.status(403).send('You do not have the permissions for this.');
return;
}
if (req.user.role != 'ADMIN') {
res.status(403).send('You do not have the permissions for this.');
return;
}
const data = await db.oneOrNone('DELETE FROM "Impersonation" where "sourceId" = $1', req.user.id);
res.send(data);
const data = await db.oneOrNone('DELETE FROM "Impersonation" where "sourceId" = $1', req.user.id);
res.send(data);
});
app.get('/api/keys', apiMiddlewares, async (req: any, res: any, next: any) => {
const userId = req.user.impersonation?.id ?? req.user.id;
const data = await db.manyOrNone('SELECT id, label FROM "ApiKey" WHERE "userId" = $1', userId);
res.send(data);
const userId = req.user.impersonation?.id ?? req.user.id;
const data = await db.manyOrNone('SELECT id, label FROM "ApiKey" WHERE "userId" = $1', userId);
res.send(data);
});
app.post('/api/keys', apiMiddlewares, async (req: any, res: any, next: any) => {
const userId = req.user.impersonation?.id ?? req.user.id;
const keys = await db.one('SELECT count(*) FROM "ApiKey" WHERE "userId" = $1', userId);
if (keys.count > 10) {
res.status(400).send('too many keys');
return;
}
const label = req.body.label;
if (!label) {
res.status(400).send('no label is attached.');
return;
}
const key = uuidv4();
await db.none('INSERT INTO "ApiKey" (id, label, "userId") VALUES ($1, $2, $3);', [key, label, userId]);
res.send({ label, key });
const userId = req.user.impersonation?.id ?? req.user.id;
const keys = await db.one('SELECT count(*) FROM "ApiKey" WHERE "userId" = $1', userId);
if (keys.count > 10) {
res.status(400).send('too many keys');
return;
}
const label = req.body.label;
if (!label) {
res.status(400).send('no label is attached.');
return;
}
const key = uuidv4();
await db.none('INSERT INTO "ApiKey" (id, label, "userId") VALUES ($1, $2, $3);', [key, label, userId]);
res.send({ label, key });
});
app.delete('/api/keys', apiMiddlewares, async (req: any, res: any, next: any) => {
if (!req.body.key) {
res.status(400).send('key has not been provided.');
return;
}
const key = await db.one('SELECT EXISTS(SELECT 1 FROM "ApiKey" WHERE id = $1)', req.body.key);
if (!key.exists) {
res.status(400).send('key does not exist.');
return;
}
res.send({ key: req.body.key });
if (!req.body.key) {
res.status(400).send('key has not been provided.');
return;
}
const key = await db.one('SELECT EXISTS(SELECT 1 FROM "ApiKey" WHERE id = $1)', req.body.key);
if (!key.exists) {
res.status(400).send('key does not exist.');
return;
}
res.send({ key: req.body.key });
});
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, {
'Content-Type': 'application/x-www-form-urlencoded'
});
const body = await response.readBody();
const data = JSON.parse(body);
if (!data || data.message) {
console.log('Failed to validate Twitch code authentication:', data);
res.send({ authenticated: false });
return;
}
console.log('Successfully validated Twitch code authentication. Attempting to read user data from Twitch.');
const resp = await rest.get('https://api.twitch.tv/helix/users', {
'Authorization': 'Bearer ' + data.access_token,
'Client-Id': process.env.AUTH_CLIENT_ID
});
const b = await resp.readBody();
const twitch = JSON.parse(b);
if (!twitch?.data) {
console.log('Failed to fetch twitch data:', twitch?.data);
res.send({ authenticated: false });
return;
}
const account: any = await db.oneOrNone('SELECT "userId" FROM "Account" WHERE "providerAccountId" = $1', twitch.data[0].id);
if (account != null) {
const user: any = await db.one('SELECT id FROM "User" WHERE id = $1', account.userId);
console.log('User fetched successfully:', user.id);
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '30d' });
res.send({ authenticated: true, token: token });
return;
}
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, {
'Content-Type': 'application/x-www-form-urlencoded'
});
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 });
return;
}
console.log('Successfully validated Twitch code authentication. Attempting to read user data from Twitch.');
const resp = await rest.get('https://api.twitch.tv/helix/users', {
'Authorization': 'Bearer ' + data.access_token,
'Client-Id': process.env.AUTH_CLIENT_ID
});
const b = await resp.readBody();
const twitch = JSON.parse(b);
if (!twitch?.data) {
console.log('Failed to fetch twitch data:', twitch?.data);
res.send({ authenticated: false });
return;
}
const account: any = await db.oneOrNone('SELECT "userId" FROM "Account" WHERE "providerAccountId" = $1', twitch.data[0].id);
if (account != null) {
const user: any = await db.one('SELECT id FROM "User" WHERE id = $1', account.userId);
console.log('User fetched successfully:', user.id);
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 });
});
app.use(helmet());
app.use(limiter);
app.listen(port, () => {
console.log(`[server]: Server is running at http://localhost:${port}`);
console.log(`[server]: Server is running at http://localhost:${port}`);
});