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