Added API key validation, JWT validation, Twitch OAuth validation, API key fetching. Needs severe clean up.

This commit is contained in:
Tom
2024-10-17 08:59:05 +00:00
commit 6c6cfd5d7e
6 changed files with 2693 additions and 0 deletions

197
src/index.ts Normal file
View File

@@ -0,0 +1,197 @@
import express, { Express, Request, Response } from "express";
import pgPromise from "pg-promise";
import rateLimit from "express-rate-limit";
import helmet from "helmet";
import dotenv from "dotenv";
import * as httpm from 'typed-rest-client/HttpClient';
dotenv.config();
if (!process.env.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,
});
const app: Express = express();
const port = process.env.PORT || 3000;
app.use(express.json());
app.use(express.urlencoded());
var jwt = require('jsonwebtoken');
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,
}, 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 user', user)
if (user) {
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,
}));
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'
}, 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;
}
}
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);
});
passport.deserializeUser((user: any, done: any) => {
done(null, user);
});
app.get('/api/auth', passport.authenticate("openidconnect", { failureRedirect: '/login' }), (req: Request, res: Response) => {
res.send('');
});
app.get('/api/auth/jwt', passport.authenticate("jwt"), (req: Request, res: Response) => {
res.send({ authenticated: true });
});
app.get('/api/loggedin', (req: any, res: Response) => {
res.send(['test test test ', req.user ? 'yes' : 'no']);
});
async function isApiKeyAuthenticated(req: any, res: any, next: any) {
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) {
console.log(data);
const user = await db.oneOrNone('SELECT id, name, role, "ttsDefaultVoice" FROM "User" WHERE id = $1', data.userId);
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;
}
}
req.user = user
}
}
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.' });
}
const apiMiddlewares = [isApiKeyAuthenticated, passport.authenticate('jwt', { session: false }), isWebAuthenticated]
app.get('/api/keys', apiMiddlewares, async (req: any, res: any, next: any) => {
const userId = req.user.id;
const data = await db.manyOrNone('SELECT id, label FROM "ApiKey" WHERE "userId" = $1', userId);
res.send(data);
});
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) {
res.send({ authenticated: false });
return;
}
console.log('twitch data', twitch.data[0])
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('userrrr', user)
const token = jwt.sign({ id: user.id }, process.env.JWT_SECRET, { expiresIn: '30d' });
res.send({ authenticated: true, token: token });
return;
}
res.send({ authenticated: false });
});
app.use(helmet());
app.use(limiter);
app.listen(port, () => {
console.log(`[server]: Server is running at http://localhost:${port}`);
});

View File