Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Binary file added public/assets/app/charts/MDPC/MDPC_OVR.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
73 changes: 51 additions & 22 deletions server/routes/auth.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,22 +31,48 @@ const VATSIM_REDIRECT_URI = process.env.VATSIM_REDIRECT_URI ?? '';
const VATSIM_AUTH_BASE = process.env.VATSIM_AUTH_BASE ?? '';

// GET: /api/auth/discord - redirect to Discord for authentication
router.get('/discord', (_req, res) => {
router.get('/discord', (req, res) => {
if (!CLIENT_ID || !REDIRECT_URI) {
return res.status(500).json({ error: 'Discord OAuth not configured' });
}
const discordAuthUrl = `https://discord.com/api/oauth2/authorize?client_id=${encodeURIComponent(CLIENT_ID)}&redirect_uri=${encodeURIComponent(REDIRECT_URI)}&response_type=code&scope=identify`;
const callback = typeof req.query.callback === 'string' ? req.query.callback : undefined;
const state = callback ? Buffer.from(JSON.stringify({ callback })).toString('base64') : undefined;

const params = new URLSearchParams({
client_id: CLIENT_ID,
redirect_uri: REDIRECT_URI,
response_type: 'code',
scope: 'identify'
});

if (state) {
params.set('state', state);
}

const discordAuthUrl = `https://discord.com/api/oauth2/authorize?${params.toString()}`;
res.redirect(discordAuthUrl);
});

// GET: /api/auth/discord/callback - handle Discord OAuth2 callback
router.get('/discord/callback', authLimiter, async (req, res) => {
const { code } = req.query;
const { code, state } = req.query;

if (!code) {
return res.status(400).json({ error: 'Authorization code missing' });
}

let callback: string | undefined;
if (state && typeof state === 'string') {
try {
const decoded = JSON.parse(Buffer.from(state, 'base64').toString());
if (decoded && typeof decoded === 'object' && typeof decoded.callback === 'string') {
callback = decoded.callback;
}
} catch (err) {
console.error('Error decoding state:', err);
}
}

try {
const tokenResponse = await axios.post('https://discord.com/api/oauth2/token',
new URLSearchParams({
Expand All @@ -73,8 +99,8 @@ router.get('/discord/callback', authLimiter, async (req, res) => {

const discordUser = userResponse.data;

let ipAddress = getClientIp(req);
if (Array.isArray(ipAddress)) ipAddress = ipAddress[0] || '';
let ipAddress = getClientIp(req);
if (Array.isArray(ipAddress)) ipAddress = ipAddress[0] || '';
const isVpn = await detectVPN(req);

const existingUser = await getUserById(discordUser.id);
Expand Down Expand Up @@ -118,7 +144,10 @@ router.get('/discord/callback', authLimiter, async (req, res) => {
path: '/'
});

res.redirect(FRONTEND_URL + '/');
const redirectUrl = callback && callback.startsWith('/')
? FRONTEND_URL + callback
: FRONTEND_URL + '/';
res.redirect(redirectUrl);

} catch (error) {
console.error('Discord auth error:', error);
Expand Down Expand Up @@ -153,8 +182,8 @@ router.get('/roblox/callback', authLimiter, async (req, res) => {
}

try {
const decoded = jwt.verify(state, JWT_SECRET as string) as { userId: string };
const userId = (decoded).userId;
const decoded = jwt.verify(state, JWT_SECRET as string) as { userId: string };
const userId = (decoded).userId;

const tokenResponse = await axios.post('https://apis.roblox.com/oauth/v1/token',
new URLSearchParams({
Expand Down Expand Up @@ -248,13 +277,13 @@ router.get('/vatsim/callback', authLimiter, async (req, res) => {
} catch (err) {
return res.redirect(FRONTEND_URL + '/settings?error=vatsim_auth_failed');
}
let userId: string | undefined;
if (typeof decoded === 'object' && decoded !== null && 'userId' in decoded) {
userId = (decoded as { userId: string }).userId;
}
if (!userId) {
return res.redirect(FRONTEND_URL + '/settings?error=vatsim_auth_failed');
}
let userId: string | undefined;
if (typeof decoded === 'object' && decoded !== null && 'userId' in decoded) {
userId = (decoded as { userId: string }).userId;
}
if (!userId) {
return res.redirect(FRONTEND_URL + '/settings?error=vatsim_auth_failed');
}

if (!VATSIM_CLIENT_ID || !VATSIM_CLIENT_SECRET || !VATSIM_REDIRECT_URI) {
return res.redirect(FRONTEND_URL + '/settings?error=vatsim_not_configured');
Expand Down Expand Up @@ -319,8 +348,8 @@ router.get('/vatsim/callback', authLimiter, async (req, res) => {
}
}
// parsed for VATSIM callback handled
const fallbackMap: Record<number, string> = { 0: 'OBS', 1: 'S1', 2: 'S2', 3: 'S3', 4: 'C1', 5: 'C2', 6: 'C3', 7: 'I1', 8: 'I2', 9: 'I3', 10: 'SUP', 11: 'ADM' };
const fallbackShort = ratingShort || (numeric != null && Number.isFinite(numeric) ? fallbackMap[numeric as number] || null : null);
const fallbackMap: Record<number, string> = { 0: 'OBS', 1: 'S1', 2: 'S2', 3: 'S3', 4: 'C1', 5: 'C2', 6: 'C3', 7: 'I1', 8: 'I2', 9: 'I3', 10: 'SUP', 11: 'ADM' };
const fallbackShort = ratingShort || (numeric != null && Number.isFinite(numeric) ? fallbackMap[numeric as number] || null : null);

const { updateVatsimAccount } = await import('../db/users.js');
await updateVatsimAccount(userId, {
Expand Down Expand Up @@ -420,8 +449,8 @@ router.post('/vatsim/exchange', authLimiter, requireAuth, async (req, res) => {
}
}
// parsed for VATSIM exchange handled
const fallbackMap2: Record<number, string> = { 0: 'OBS', 1: 'S1', 2: 'S2', 3: 'S3', 4: 'C1', 5: 'C2', 6: 'C3', 7: 'I1', 8: 'I2', 9: 'I3', 10: 'SUP', 11: 'ADM' };
const fallbackShort = ratingShort2 || (numeric2 != null && Number.isFinite(numeric2) ? fallbackMap2[numeric2 as number] || null : null);
const fallbackMap2: Record<number, string> = { 0: 'OBS', 1: 'S1', 2: 'S2', 3: 'S3', 4: 'C1', 5: 'C2', 6: 'C3', 7: 'I1', 8: 'I2', 9: 'I3', 10: 'SUP', 11: 'ADM' };
const fallbackShort = ratingShort2 || (numeric2 != null && Number.isFinite(numeric2) ? fallbackMap2[numeric2 as number] || null : null);

const { updateVatsimAccount } = await import('../db/users.js');
if (!req.user) return res.status(401).json({ error: 'Unauthorized' });
Expand All @@ -447,8 +476,8 @@ router.post('/vatsim/exchange', authLimiter, requireAuth, async (req, res) => {
router.post('/vatsim/unlink', requireAuth, async (req, res) => {
try {
const { unlinkVatsimAccount } = await import('../db/users.js');
if (!req.user) return res.status(401).json({ error: 'Unauthorized' });
await unlinkVatsimAccount(req.user.userId);
if (!req.user) return res.status(401).json({ error: 'Unauthorized' });
await unlinkVatsimAccount(req.user.userId);
res.cookie('vatsim_force', '1', {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
Expand Down Expand Up @@ -488,7 +517,7 @@ router.get('/me', requireAuth, async (req, res) => {

const ranks: Record<string, number | null> = {};
for (const key of STATS_KEYS) {
ranks[key] = await getUserRank(req.user.userId, key);
ranks[key] = await getUserRank(req.user.userId, key);
}

res.json({
Expand Down
43 changes: 37 additions & 6 deletions server/websockets/overviewWebsocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,14 +2,23 @@ import { Server as SocketServer } from 'socket.io';
import { getAllSessions } from '../db/sessions.js';
import { getFlightsBySessionWithTime } from '../db/flights.js';
import { decrypt } from '../utils/encryption.js';
import { getUserById } from '../db/users.js';
import type { Server as HTTPServer } from 'http';

let io: SocketServer;
const activeOverviewClients = new Set<string>();

interface SessionUser {
id?: string;
username?: string;
role?: string;
position?: string;
roles?: Array<{
id: number;
name: string;
color: string;
icon: string;
priority: number;
}>;
}

export function setupOverviewWebsocket(httpServer: HTTPServer, sessionUsersIO: { activeUsers: Map<string, SessionUser[]> }) {
Expand Down Expand Up @@ -64,7 +73,7 @@ export function setupOverviewWebsocket(httpServer: HTTPServer, sessionUsersIO: {
return io;
}

async function getOverviewData(sessionUsersIO: { activeUsers: Map<string, SessionUser[]> }) {
export async function getOverviewData(sessionUsersIO: { activeUsers: Map<string, SessionUser[]> }) {
try {
const allSessions = await getAllSessions();
const pfatcSessions = allSessions.filter(session => session.is_pfatc);
Expand All @@ -89,9 +98,29 @@ async function getOverviewData(sessionUsersIO: { activeUsers: Map<string, Sessio
}
}

const controllers = sessionUsers.map(user => ({
username: user.username || 'Unknown',
role: user.role || 'APP'
const controllers = await Promise.all(sessionUsers.map(async (user) => {
let hasVatsimRating = false;
let isEventController = false;

if (user.id) {
try {
const userData = await getUserById(user.id);
hasVatsimRating = userData?.vatsim_rating_id && userData.vatsim_rating_id > 1;

if (user.roles) {
isEventController = user.roles.some(role => role.name === 'Event Controller');
}
} catch (err) {
console.error('Error fetching user data for controller badges:', err);
}
}

return {
username: user.username || 'Unknown',
role: user.position || 'APP',
hasVatsimRating,
isEventController
};
}));

activeSessions.push({
Expand All @@ -112,7 +141,9 @@ async function getOverviewData(sessionUsersIO: { activeUsers: Map<string, Sessio

const controllers = sessionUsers.map(user => ({
username: user.username || 'Unknown',
role: user.role || 'APP'
role: user.position || 'APP',
hasVatsimRating: false,
isEventController: false
}));

activeSessions.push({
Expand Down
14 changes: 14 additions & 0 deletions server/websockets/sessionUsersWebsocket.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { isAdmin } from '../middleware/admin.js';
import { validateSessionId, validateAccessId } from '../utils/validation.js';
import type { Server as HttpServer } from 'http';
import { incrementStat } from '../utils/statisticsCache.js';
import { getOverviewIO } from './overviewWebsocket.js';

const activeUsers = new Map();
const sessionATISConfigs = new Map();
Expand Down Expand Up @@ -354,6 +355,19 @@ export function setupSessionUsersWebsocket(httpServer: HttpServer) {
if (userIndex !== -1) {
users[userIndex].position = position;
io.to(sessionId).emit('sessionUsersUpdate', users);
const overviewIO = getOverviewIO();
if (overviewIO) {
// Force immediate overview data update
setTimeout(async () => {
try {
const { getOverviewData } = await import('./overviewWebsocket.js');
const overviewData = await getOverviewData({ activeUsers });
overviewIO.emit('overviewData', overviewData);
} catch (error) {
console.error('Error broadcasting overview update:', error);
}
}, 100);
}
}
}
});
Expand Down
2 changes: 1 addition & 1 deletion src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,7 @@ export default function App() {
<Route path="view/:sessionId" element={<Flights />} />
<Route path="logbook" element={<Logbook />} />
<Route path="logbook/:flightId" element={<FlightDetail />} />
<Route path="settings" element={<Settings />} />
<Route path="*" element={<NotFound />} />
</Routes>
</ProtectedRoute>
Expand All @@ -62,7 +63,6 @@ export default function App() {
<Route path="acars/:sessionId/:flightId" element={<ACARS />} />
<Route path="/flight/:shareToken" element={<PublicFlightView />} />
<Route path="/pilots/:username" element={<PilotProfile />} />
<Route path="settings" element={<Settings />} />

<Route
path="/admin/*"
Expand Down
Loading
Loading