fix(auth): use Plex PIN flow instead of OAuth2 code exchange
Plex auth uses PIN-based flow, not standard OAuth2 authorization_code.
- backend/auth: POST /api/v2/pins to create PIN, GET /api/v2/pins/{id} to get authToken
- frontend/login: store pinId in sessionStorage before redirect
- frontend/callback: send pinId to backend instead of query code
- backend/index: fix dotenv path resolution for tsx (__dirname returns '.')
This commit is contained in:
+99
-86
@@ -1,78 +1,89 @@
|
|||||||
import express from 'express';
|
import express from "express";
|
||||||
import cors from 'cors';
|
import cors from "cors";
|
||||||
import helmet from 'helmet';
|
import helmet from "helmet";
|
||||||
import morgan from 'morgan';
|
import morgan from "morgan";
|
||||||
import rateLimit from 'express-rate-limit';
|
import rateLimit from "express-rate-limit";
|
||||||
import { createServer } from 'http';
|
import { createServer } from "http";
|
||||||
import { Server } from 'socket.io';
|
import { Server } from "socket.io";
|
||||||
import dotenv from 'dotenv';
|
import dotenv from "dotenv";
|
||||||
|
import fs from "fs";
|
||||||
|
import path from "path";
|
||||||
|
|
||||||
dotenv.config();
|
const envPath =
|
||||||
|
["../.env", "../../.env", ".env"]
|
||||||
|
.map((p) => path.resolve(process.cwd(), p))
|
||||||
|
.find((p) => fs.existsSync(p)) || ".env";
|
||||||
|
|
||||||
import { prisma } from './utils/prisma';
|
dotenv.config({ path: envPath });
|
||||||
import { errorHandler } from './middleware/errorHandler';
|
|
||||||
import { authRouter } from './routes/auth';
|
import { prisma } from "./utils/prisma";
|
||||||
import { userRouter } from './routes/users';
|
import { errorHandler } from "./middleware/errorHandler";
|
||||||
import { walletRouter } from './routes/wallet';
|
import { authRouter } from "./routes/auth";
|
||||||
import { transactionsRouter } from './routes/transactions';
|
import { userRouter } from "./routes/users";
|
||||||
import { adminRouter } from './routes/admin';
|
import { walletRouter } from "./routes/wallet";
|
||||||
import { tautulliRouter } from './routes/tautulli';
|
import { transactionsRouter } from "./routes/transactions";
|
||||||
import { overseerRouter } from './routes/overseer';
|
import { adminRouter } from "./routes/admin";
|
||||||
import { webhookRouter } from './routes/webhooks';
|
import { tautulliRouter } from "./routes/tautulli";
|
||||||
import { setupSocketHandlers } from './services/socket';
|
import { overseerRouter } from "./routes/overseer";
|
||||||
|
import { webhookRouter } from "./routes/webhooks";
|
||||||
|
import { setupSocketHandlers } from "./services/socket";
|
||||||
|
|
||||||
const app = express();
|
const app = express();
|
||||||
const httpServer = createServer(app);
|
const httpServer = createServer(app);
|
||||||
const allowedOrigins = [
|
const allowedOrigins = [
|
||||||
process.env.FRONTEND_URL,
|
process.env.FRONTEND_URL,
|
||||||
'https://coop.hobokenchicken.com',
|
"https://coop.hobokenchicken.com",
|
||||||
'http://172.20.1.238:3000'
|
"http://172.20.1.238:3000",
|
||||||
].filter(Boolean) as string[];
|
].filter(Boolean) as string[];
|
||||||
|
|
||||||
const io = new Server(httpServer, {
|
const io = new Server(httpServer, {
|
||||||
cors: {
|
cors: {
|
||||||
origin: allowedOrigins,
|
origin: allowedOrigins,
|
||||||
credentials: true
|
credentials: true,
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Security middleware
|
// Security middleware
|
||||||
app.use(helmet({
|
app.use(
|
||||||
crossOriginResourcePolicy: { policy: "cross-origin" }
|
helmet({
|
||||||
}));
|
crossOriginResourcePolicy: { policy: "cross-origin" },
|
||||||
app.use(cors({
|
}),
|
||||||
origin: allowedOrigins,
|
);
|
||||||
credentials: true
|
app.use(
|
||||||
}));
|
cors({
|
||||||
|
origin: allowedOrigins,
|
||||||
|
credentials: true,
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
// Rate limiting
|
// Rate limiting
|
||||||
const limiter = rateLimit({
|
const limiter = rateLimit({
|
||||||
windowMs: 15 * 60 * 1000, // 15 minutes
|
windowMs: 15 * 60 * 1000, // 15 minutes
|
||||||
max: 100 // limit each IP to 100 requests per windowMs
|
max: 100, // limit each IP to 100 requests per windowMs
|
||||||
});
|
});
|
||||||
app.use(limiter);
|
app.use(limiter);
|
||||||
|
|
||||||
// Body parsing
|
// Body parsing
|
||||||
app.use(express.json({ limit: '10mb' }));
|
app.use(express.json({ limit: "10mb" }));
|
||||||
app.use(express.urlencoded({ extended: true }));
|
app.use(express.urlencoded({ extended: true }));
|
||||||
|
|
||||||
// Logging
|
// Logging
|
||||||
app.use(morgan('combined'));
|
app.use(morgan("combined"));
|
||||||
|
|
||||||
// Health check
|
// Health check
|
||||||
app.get('/health', (_req, res) => {
|
app.get("/health", (_req, res) => {
|
||||||
res.json({ status: 'ok', timestamp: new Date().toISOString() });
|
res.json({ status: "ok", timestamp: new Date().toISOString() });
|
||||||
});
|
});
|
||||||
|
|
||||||
// API routes
|
// API routes
|
||||||
app.use('/api/auth', authRouter);
|
app.use("/api/auth", authRouter);
|
||||||
app.use('/api/users', userRouter);
|
app.use("/api/users", userRouter);
|
||||||
app.use('/api/wallet', walletRouter);
|
app.use("/api/wallet", walletRouter);
|
||||||
app.use('/api/transactions', transactionsRouter);
|
app.use("/api/transactions", transactionsRouter);
|
||||||
app.use('/api/admin', adminRouter);
|
app.use("/api/admin", adminRouter);
|
||||||
app.use('/api/tautulli', tautulliRouter);
|
app.use("/api/tautulli", tautulliRouter);
|
||||||
app.use('/api/overseer', overseerRouter);
|
app.use("/api/overseer", overseerRouter);
|
||||||
app.use('/webhooks', webhookRouter);
|
app.use("/webhooks", webhookRouter);
|
||||||
|
|
||||||
// Error handling
|
// Error handling
|
||||||
app.use(errorHandler);
|
app.use(errorHandler);
|
||||||
@@ -84,49 +95,51 @@ setupSocketHandlers(io);
|
|||||||
const PORT = process.env.PORT || 3001;
|
const PORT = process.env.PORT || 3001;
|
||||||
|
|
||||||
async function startServer() {
|
async function startServer() {
|
||||||
try {
|
try {
|
||||||
// Connect to database
|
// Connect to database
|
||||||
await prisma.$connect();
|
await prisma.$connect();
|
||||||
console.log('✅ Connected to database');
|
console.log("✅ Connected to database");
|
||||||
|
|
||||||
// Ensure default settings exist
|
// Ensure default settings exist
|
||||||
const settings = await prisma.systemSettings.findFirst();
|
const settings = await prisma.systemSettings.findFirst();
|
||||||
if (!settings) {
|
if (!settings) {
|
||||||
await prisma.systemSettings.create({
|
await prisma.systemSettings.create({
|
||||||
data: {
|
data: {
|
||||||
id: 'default'
|
id: "default",
|
||||||
}
|
},
|
||||||
});
|
});
|
||||||
console.log('✅ Created default system settings');
|
console.log("✅ Created default system settings");
|
||||||
}
|
}
|
||||||
|
|
||||||
httpServer.listen(PORT, () => {
|
httpServer.listen(PORT, () => {
|
||||||
console.log(`🚀 Server running on port ${PORT}`);
|
console.log(`🚀 Server running on port ${PORT}`);
|
||||||
console.log(`📊 API URL: ${process.env.API_URL || `http://localhost:${PORT}`}`);
|
console.log(
|
||||||
});
|
`📊 API URL: ${process.env.API_URL || `http://localhost:${PORT}`}`,
|
||||||
} catch (error) {
|
);
|
||||||
console.error('Failed to start server:', error);
|
});
|
||||||
process.exit(1);
|
} catch (error) {
|
||||||
}
|
console.error("Failed to start server:", error);
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
// Graceful shutdown
|
// Graceful shutdown
|
||||||
process.on('SIGTERM', async () => {
|
process.on("SIGTERM", async () => {
|
||||||
console.log('SIGTERM received, shutting down gracefully');
|
console.log("SIGTERM received, shutting down gracefully");
|
||||||
await prisma.$disconnect();
|
await prisma.$disconnect();
|
||||||
httpServer.close(() => {
|
httpServer.close(() => {
|
||||||
console.log('Server closed');
|
console.log("Server closed");
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
process.on('SIGINT', async () => {
|
process.on("SIGINT", async () => {
|
||||||
console.log('SIGINT received, shutting down gracefully');
|
console.log("SIGINT received, shutting down gracefully");
|
||||||
await prisma.$disconnect();
|
await prisma.$disconnect();
|
||||||
httpServer.close(() => {
|
httpServer.close(() => {
|
||||||
console.log('Server closed');
|
console.log("Server closed");
|
||||||
process.exit(0);
|
process.exit(0);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
startServer();
|
startServer();
|
||||||
|
|||||||
+202
-183
@@ -1,192 +1,211 @@
|
|||||||
import { Router } from 'express';
|
import { Router } from "express";
|
||||||
import axios from 'axios';
|
import axios from "axios";
|
||||||
import jwt from 'jsonwebtoken';
|
import jwt from "jsonwebtoken";
|
||||||
import { prisma } from '../utils/prisma';
|
import { prisma } from "../utils/prisma";
|
||||||
import { asyncHandler } from '../middleware/errorHandler';
|
import { asyncHandler } from "../middleware/errorHandler";
|
||||||
|
|
||||||
const router = Router();
|
const router = Router();
|
||||||
|
|
||||||
// Plex OAuth configuration
|
const PLEX_CLIENT_ID = process.env.PLEX_CLIENT_ID || "";
|
||||||
const PLEX_CLIENT_ID = process.env.PLEX_CLIENT_ID || '';
|
const PLEX_REDIRECT_URI = process.env.PLEX_REDIRECT_URI || "";
|
||||||
const PLEX_CLIENT_SECRET = process.env.PLEX_CLIENT_SECRET || '';
|
const JWT_SECRET = process.env.JWT_SECRET || "secret";
|
||||||
const PLEX_REDIRECT_URI = process.env.PLEX_REDIRECT_URI || '';
|
|
||||||
const JWT_SECRET = process.env.JWT_SECRET || 'secret';
|
|
||||||
|
|
||||||
// Step 1: Get Plex OAuth URL
|
if (!PLEX_CLIENT_ID) {
|
||||||
router.get('/plex/url', asyncHandler(async (_req, res) => {
|
console.error("ERROR: PLEX_CLIENT_ID not set");
|
||||||
const params = new URLSearchParams({
|
}
|
||||||
client_id: PLEX_CLIENT_ID,
|
|
||||||
redirect_uri: PLEX_REDIRECT_URI,
|
|
||||||
response_type: 'code',
|
|
||||||
scope: 'openid profile',
|
|
||||||
'X-Plex-Product': 'CoopCoins',
|
|
||||||
'X-Plex-Client-Identifier': PLEX_CLIENT_ID,
|
|
||||||
'X-Plex-Device': 'Web Browser',
|
|
||||||
'X-Plex-Platform': 'Web'
|
|
||||||
});
|
|
||||||
|
|
||||||
const authUrl = `https://app.plex.tv/auth#?${params.toString()}`;
|
|
||||||
|
|
||||||
res.json({ authUrl });
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Step 2: Handle Plex OAuth callback
|
// Step 1: Generate Plex PIN and return auth URL
|
||||||
router.post('/plex/callback', asyncHandler(async (req, res) => {
|
router.get(
|
||||||
const { code } = req.body;
|
"/plex/url",
|
||||||
|
asyncHandler(async (_req, res) => {
|
||||||
if (!code) {
|
if (!PLEX_CLIENT_ID) {
|
||||||
return res.status(400).json({ error: 'Authorization code required' });
|
return res.status(500).json({ error: "Plex not configured" });
|
||||||
}
|
}
|
||||||
|
|
||||||
// Exchange code for Plex token
|
|
||||||
const tokenResponse = await axios.post(
|
|
||||||
'https://plex.tv/api/v2/oauth/token',
|
|
||||||
{
|
|
||||||
code,
|
|
||||||
client_id: PLEX_CLIENT_ID,
|
|
||||||
client_secret: PLEX_CLIENT_SECRET,
|
|
||||||
grant_type: 'authorization_code'
|
|
||||||
},
|
|
||||||
{
|
|
||||||
headers: {
|
|
||||||
'Accept': 'application/json',
|
|
||||||
'X-Plex-Client-Identifier': PLEX_CLIENT_ID
|
|
||||||
}
|
|
||||||
}
|
|
||||||
);
|
|
||||||
|
|
||||||
const plexToken = tokenResponse.data.access_token;
|
|
||||||
|
|
||||||
// Get user info from Plex
|
|
||||||
const userResponse = await axios.get('https://plex.tv/api/v2/user', {
|
|
||||||
headers: {
|
|
||||||
'X-Plex-Token': plexToken,
|
|
||||||
'X-Plex-Client-Identifier': PLEX_CLIENT_ID,
|
|
||||||
'Accept': 'application/json'
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
const plexUser = userResponse.data;
|
|
||||||
|
|
||||||
// Check if user exists, create if not
|
|
||||||
let user = await prisma.user.findUnique({
|
|
||||||
where: { plexId: plexUser.id }
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!user) {
|
|
||||||
user = await prisma.user.create({
|
|
||||||
data: {
|
|
||||||
plexId: plexUser.id,
|
|
||||||
plexUsername: plexUser.username || plexUser.email,
|
|
||||||
email: plexUser.email,
|
|
||||||
// Check if user is Plex admin (implement your logic)
|
|
||||||
isAdmin: false
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} else {
|
|
||||||
// Update user info
|
|
||||||
user = await prisma.user.update({
|
|
||||||
where: { id: user.id },
|
|
||||||
data: {
|
|
||||||
plexUsername: plexUser.username || plexUser.email,
|
|
||||||
email: plexUser.email
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create session
|
|
||||||
const session = await prisma.session.create({
|
|
||||||
data: {
|
|
||||||
userId: user.id,
|
|
||||||
token: jwt.sign({ userId: user.id }, JWT_SECRET, { expiresIn: '7d' }),
|
|
||||||
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000)
|
|
||||||
}
|
|
||||||
});
|
|
||||||
|
|
||||||
// Generate JWT
|
|
||||||
const token = jwt.sign(
|
|
||||||
{
|
|
||||||
userId: user.id,
|
|
||||||
plexId: user.plexId,
|
|
||||||
isAdmin: user.isAdmin
|
|
||||||
},
|
|
||||||
JWT_SECRET,
|
|
||||||
{ expiresIn: '7d' }
|
|
||||||
);
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
token,
|
|
||||||
sessionToken: session.token,
|
|
||||||
user: {
|
|
||||||
id: user.id,
|
|
||||||
plexId: user.plexId,
|
|
||||||
plexUsername: user.plexUsername,
|
|
||||||
email: user.email,
|
|
||||||
isAdmin: user.isAdmin,
|
|
||||||
walletAddress: user.walletAddress,
|
|
||||||
totalEarned: user.totalEarned,
|
|
||||||
totalSpent: user.totalSpent
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Verify token
|
const pinResponse = await axios.post(
|
||||||
router.get('/verify', asyncHandler(async (req, res) => {
|
"https://plex.tv/api/v2/pins?strong=true",
|
||||||
const authHeader = req.headers.authorization;
|
null,
|
||||||
|
{
|
||||||
if (!authHeader?.startsWith('Bearer ')) {
|
headers: {
|
||||||
return res.status(401).json({ error: 'No token provided' });
|
Accept: "application/json",
|
||||||
}
|
"X-Plex-Client-Identifier": PLEX_CLIENT_ID,
|
||||||
|
"X-Plex-Product": "CoopCoins",
|
||||||
const token = authHeader.substring(7);
|
"X-Plex-Version": "1.0.0",
|
||||||
|
"X-Plex-Device": "Web Browser",
|
||||||
try {
|
"X-Plex-Platform": "Web",
|
||||||
const decoded = jwt.verify(token, JWT_SECRET) as any;
|
},
|
||||||
|
},
|
||||||
const user = await prisma.user.findUnique({
|
);
|
||||||
where: { id: decoded.userId }
|
|
||||||
});
|
|
||||||
|
|
||||||
if (!user || !user.isActive) {
|
|
||||||
return res.status(401).json({ error: 'User not found or inactive' });
|
|
||||||
}
|
|
||||||
|
|
||||||
res.json({
|
|
||||||
user: {
|
|
||||||
id: user.id,
|
|
||||||
plexId: user.plexId,
|
|
||||||
plexUsername: user.plexUsername,
|
|
||||||
email: user.email,
|
|
||||||
isAdmin: user.isAdmin,
|
|
||||||
walletAddress: user.walletAddress,
|
|
||||||
totalEarned: user.totalEarned,
|
|
||||||
totalSpent: user.totalSpent
|
|
||||||
}
|
|
||||||
});
|
|
||||||
} catch (error) {
|
|
||||||
res.status(401).json({ error: 'Invalid token' });
|
|
||||||
}
|
|
||||||
}));
|
|
||||||
|
|
||||||
// Logout
|
const pin = pinResponse.data;
|
||||||
router.post('/logout', asyncHandler(async (req, res) => {
|
const authUrl = `https://app.plex.tv/auth#?clientID=${encodeURIComponent(PLEX_CLIENT_ID)}&code=${pin.code}&forwardUrl=${encodeURIComponent(PLEX_REDIRECT_URI)}`;
|
||||||
const authHeader = req.headers.authorization;
|
|
||||||
|
res.json({ authUrl, pinId: pin.id });
|
||||||
if (authHeader?.startsWith('Bearer ')) {
|
}),
|
||||||
const token = authHeader.substring(7);
|
);
|
||||||
|
|
||||||
try {
|
// Step 2: Exchange PIN for Plex token and create user session
|
||||||
const decoded = jwt.verify(token, JWT_SECRET) as any;
|
router.post(
|
||||||
|
"/plex/callback",
|
||||||
await prisma.session.deleteMany({
|
asyncHandler(async (req, res) => {
|
||||||
where: { userId: decoded.userId }
|
const { pinId } = req.body;
|
||||||
});
|
|
||||||
} catch {
|
if (!pinId) {
|
||||||
// Invalid token, ignore
|
return res.status(400).json({ error: "PIN ID required" });
|
||||||
}
|
}
|
||||||
}
|
|
||||||
|
// Check PIN status to get auth token
|
||||||
res.json({ message: 'Logged out successfully' });
|
const pinResponse = await axios.get(
|
||||||
}));
|
`https://plex.tv/api/v2/pins/${pinId}`,
|
||||||
|
{
|
||||||
|
headers: {
|
||||||
|
Accept: "application/json",
|
||||||
|
"X-Plex-Client-Identifier": PLEX_CLIENT_ID,
|
||||||
|
},
|
||||||
|
},
|
||||||
|
);
|
||||||
|
|
||||||
|
const pin = pinResponse.data;
|
||||||
|
|
||||||
|
if (!pin.authToken) {
|
||||||
|
return res.status(400).json({ error: "Authentication not completed" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const plexToken = pin.authToken;
|
||||||
|
|
||||||
|
// Get user info from Plex
|
||||||
|
const userResponse = await axios.get("https://plex.tv/api/v2/user", {
|
||||||
|
headers: {
|
||||||
|
"X-Plex-Token": plexToken,
|
||||||
|
"X-Plex-Client-Identifier": PLEX_CLIENT_ID,
|
||||||
|
Accept: "application/json",
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
const plexUser = userResponse.data;
|
||||||
|
|
||||||
|
// Find or create user
|
||||||
|
let user = await prisma.user.findUnique({
|
||||||
|
where: { plexId: plexUser.id },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user) {
|
||||||
|
user = await prisma.user.create({
|
||||||
|
data: {
|
||||||
|
plexId: plexUser.id,
|
||||||
|
plexUsername: plexUser.username || plexUser.email,
|
||||||
|
email: plexUser.email,
|
||||||
|
isAdmin: false,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} else {
|
||||||
|
user = await prisma.user.update({
|
||||||
|
where: { id: user.id },
|
||||||
|
data: {
|
||||||
|
plexUsername: plexUser.username || plexUser.email,
|
||||||
|
email: plexUser.email,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// Create session
|
||||||
|
const session = await prisma.session.create({
|
||||||
|
data: {
|
||||||
|
userId: user.id,
|
||||||
|
token: jwt.sign({ userId: user.id }, JWT_SECRET, { expiresIn: "7d" }),
|
||||||
|
expiresAt: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000),
|
||||||
|
},
|
||||||
|
});
|
||||||
|
|
||||||
|
// Generate JWT
|
||||||
|
const token = jwt.sign(
|
||||||
|
{
|
||||||
|
userId: user.id,
|
||||||
|
plexId: user.plexId,
|
||||||
|
isAdmin: user.isAdmin,
|
||||||
|
},
|
||||||
|
JWT_SECRET,
|
||||||
|
{ expiresIn: "7d" },
|
||||||
|
);
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
token,
|
||||||
|
sessionToken: session.token,
|
||||||
|
user: {
|
||||||
|
id: user.id,
|
||||||
|
plexId: user.plexId,
|
||||||
|
plexUsername: user.plexUsername,
|
||||||
|
email: user.email,
|
||||||
|
isAdmin: user.isAdmin,
|
||||||
|
walletAddress: user.walletAddress,
|
||||||
|
totalEarned: user.totalEarned,
|
||||||
|
totalSpent: user.totalSpent,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
router.get(
|
||||||
|
"/verify",
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const authHeader = req.headers.authorization;
|
||||||
|
|
||||||
|
if (!authHeader?.startsWith("Bearer ")) {
|
||||||
|
return res.status(401).json({ error: "No token provided" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const token = authHeader.substring(7);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const decoded = jwt.verify(token, JWT_SECRET) as any;
|
||||||
|
|
||||||
|
const user = await prisma.user.findUnique({
|
||||||
|
where: { id: decoded.userId },
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!user || !user.isActive) {
|
||||||
|
return res.status(401).json({ error: "User not found or inactive" });
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({
|
||||||
|
user: {
|
||||||
|
id: user.id,
|
||||||
|
plexId: user.plexId,
|
||||||
|
plexUsername: user.plexUsername,
|
||||||
|
email: user.email,
|
||||||
|
isAdmin: user.isAdmin,
|
||||||
|
walletAddress: user.walletAddress,
|
||||||
|
totalEarned: user.totalEarned,
|
||||||
|
totalSpent: user.totalSpent,
|
||||||
|
},
|
||||||
|
});
|
||||||
|
} catch (error) {
|
||||||
|
res.status(401).json({ error: "Invalid token" });
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
|
router.post(
|
||||||
|
"/logout",
|
||||||
|
asyncHandler(async (req, res) => {
|
||||||
|
const authHeader = req.headers.authorization;
|
||||||
|
|
||||||
|
if (authHeader?.startsWith("Bearer ")) {
|
||||||
|
const token = authHeader.substring(7);
|
||||||
|
|
||||||
|
try {
|
||||||
|
const decoded = jwt.verify(token, JWT_SECRET) as any;
|
||||||
|
|
||||||
|
await prisma.session.deleteMany({
|
||||||
|
where: { userId: decoded.userId },
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
// Ignore invalid tokens on logout
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
res.json({ message: "Logged out successfully" });
|
||||||
|
}),
|
||||||
|
);
|
||||||
|
|
||||||
export { router as authRouter };
|
export { router as authRouter };
|
||||||
|
|||||||
@@ -1,55 +1,56 @@
|
|||||||
'use client';
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from "react";
|
||||||
import { useRouter, useSearchParams } from 'next/navigation';
|
import { useRouter, useSearchParams } from "next/navigation";
|
||||||
import { authApi } from '@/lib/api';
|
import { authApi } from "@/lib/api";
|
||||||
import { useStore } from '@/lib/store';
|
import { useStore } from "@/lib/store";
|
||||||
import { Loader2 } from 'lucide-react';
|
import { Loader2 } from "lucide-react";
|
||||||
import { toast } from 'sonner';
|
import { toast } from "sonner";
|
||||||
|
|
||||||
export default function AuthCallbackPage() {
|
export default function AuthCallbackPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const searchParams = useSearchParams();
|
const searchParams = useSearchParams();
|
||||||
const { setUser, setToken } = useStore();
|
const { setUser, setToken } = useStore();
|
||||||
const [status, setStatus] = useState('Completing sign in...');
|
const [status, setStatus] = useState("Completing sign in...");
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
const code = searchParams.get('code');
|
const pinId = sessionStorage.getItem("plexPinId");
|
||||||
|
|
||||||
if (!code) {
|
|
||||||
toast.error('Invalid authentication response');
|
|
||||||
router.push('/login');
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
|
|
||||||
const handleCallback = async () => {
|
if (!pinId) {
|
||||||
try {
|
toast.error("Invalid authentication response");
|
||||||
const response = await authApi.plexCallback(code);
|
router.push("/login");
|
||||||
const { user, token } = response.data;
|
return;
|
||||||
|
}
|
||||||
localStorage.setItem('token', token);
|
|
||||||
setUser(user);
|
|
||||||
setToken(token);
|
|
||||||
|
|
||||||
toast.success(`Welcome, ${user.plexUsername}!`);
|
|
||||||
router.push('/dashboard');
|
|
||||||
} catch (error) {
|
|
||||||
setStatus('Authentication failed');
|
|
||||||
toast.error('Authentication failed');
|
|
||||||
console.error(error);
|
|
||||||
setTimeout(() => router.push('/login'), 2000);
|
|
||||||
}
|
|
||||||
};
|
|
||||||
|
|
||||||
handleCallback();
|
const handleCallback = async () => {
|
||||||
}, [searchParams, router, setUser, setToken]);
|
try {
|
||||||
|
const response = await authApi.plexCallback(pinId);
|
||||||
|
const { user, token } = response.data;
|
||||||
|
|
||||||
return (
|
sessionStorage.removeItem("plexPinId");
|
||||||
<div className="min-h-screen flex items-center justify-center bg-slate-950 p-4">
|
localStorage.setItem("token", token);
|
||||||
<div className="text-center">
|
setUser(user);
|
||||||
<Loader2 className="mx-auto h-12 w-12 animate-spin text-primary mb-4" />
|
setToken(token);
|
||||||
<p className="text-lg text-foreground">{status}</p>
|
|
||||||
</div>
|
toast.success(`Welcome, ${user.plexUsername}!`);
|
||||||
</div>
|
router.push("/dashboard");
|
||||||
);
|
} catch (error) {
|
||||||
|
setStatus("Authentication failed");
|
||||||
|
toast.error("Authentication failed");
|
||||||
|
console.error(error);
|
||||||
|
setTimeout(() => router.push("/login"), 2000);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
handleCallback();
|
||||||
|
}, [searchParams, router, setUser, setToken]);
|
||||||
|
|
||||||
|
return (
|
||||||
|
<div className="min-h-screen flex items-center justify-center bg-slate-950 p-4">
|
||||||
|
<div className="text-center">
|
||||||
|
<Loader2 className="mx-auto h-12 w-12 animate-spin text-primary mb-4" />
|
||||||
|
<p className="text-lg text-foreground">{status}</p>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -1,93 +1,100 @@
|
|||||||
'use client';
|
"use client";
|
||||||
|
|
||||||
import { useEffect, useState } from 'react';
|
import { useEffect, useState } from "react";
|
||||||
import { useRouter } from 'next/navigation';
|
import { useRouter } from "next/navigation";
|
||||||
import { authApi } from '@/lib/api';
|
import { authApi } from "@/lib/api";
|
||||||
import { useStore } from '@/lib/store';
|
import { useStore } from "@/lib/store";
|
||||||
import { Button } from '@/components/ui/button';
|
import { Button } from "@/components/ui/button";
|
||||||
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
|
import {
|
||||||
import { Loader2, Tv } from 'lucide-react';
|
Card,
|
||||||
import { toast } from 'sonner';
|
CardContent,
|
||||||
|
CardDescription,
|
||||||
|
CardHeader,
|
||||||
|
CardTitle,
|
||||||
|
} from "@/components/ui/card";
|
||||||
|
import { Loader2, Tv } from "lucide-react";
|
||||||
|
import { toast } from "sonner";
|
||||||
|
|
||||||
export default function LoginPage() {
|
export default function LoginPage() {
|
||||||
const router = useRouter();
|
const router = useRouter();
|
||||||
const { isAuthenticated } = useStore();
|
const { isAuthenticated } = useStore();
|
||||||
const [isLoading, setIsLoading] = useState(false);
|
const [isLoading, setIsLoading] = useState(false);
|
||||||
const [isMounted, setIsMounted] = useState(false);
|
const [isMounted, setIsMounted] = useState(false);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
setIsMounted(true);
|
setIsMounted(true);
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
if (isAuthenticated) {
|
if (isAuthenticated) {
|
||||||
router.push('/dashboard');
|
router.push("/dashboard");
|
||||||
}
|
}
|
||||||
}, [isAuthenticated, router]);
|
}, [isAuthenticated, router]);
|
||||||
|
|
||||||
const handlePlexLogin = async () => {
|
const handlePlexLogin = async () => {
|
||||||
setIsLoading(true);
|
setIsLoading(true);
|
||||||
try {
|
try {
|
||||||
const response = await authApi.getPlexUrl();
|
const response = await authApi.getPlexUrl();
|
||||||
window.location.href = response.data.authUrl;
|
sessionStorage.setItem("plexPinId", response.data.pinId);
|
||||||
} catch (error) {
|
window.location.href = response.data.authUrl;
|
||||||
toast.error('Failed to initiate Plex login');
|
} catch (error) {
|
||||||
console.error(error);
|
toast.error("Failed to initiate Plex login");
|
||||||
setIsLoading(false);
|
console.error(error);
|
||||||
}
|
setIsLoading(false);
|
||||||
};
|
}
|
||||||
|
};
|
||||||
|
|
||||||
if (!isMounted) {
|
if (!isMounted) {
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex items-center justify-center bg-slate-950 p-4">
|
<div className="min-h-screen flex items-center justify-center bg-slate-950 p-4">
|
||||||
<Card className="w-full max-w-md">
|
<Card className="w-full max-w-md">
|
||||||
<CardHeader className="text-center">
|
<CardHeader className="text-center">
|
||||||
<div className="mx-auto w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mb-4">
|
<div className="mx-auto w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mb-4">
|
||||||
<Tv className="w-8 h-8 text-primary" />
|
<Tv className="w-8 h-8 text-primary" />
|
||||||
</div>
|
</div>
|
||||||
<CardTitle className="text-2xl">CoopCoins</CardTitle>
|
<CardTitle className="text-2xl">CoopCoins</CardTitle>
|
||||||
<CardDescription>Loading...</CardDescription>
|
<CardDescription>Loading...</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<div className="min-h-screen flex items-center justify-center bg-slate-950 p-4">
|
<div className="min-h-screen flex items-center justify-center bg-slate-950 p-4">
|
||||||
<Card className="w-full max-w-md">
|
<Card className="w-full max-w-md">
|
||||||
<CardHeader className="text-center">
|
<CardHeader className="text-center">
|
||||||
<div className="mx-auto w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mb-4">
|
<div className="mx-auto w-16 h-16 bg-primary/10 rounded-full flex items-center justify-center mb-4">
|
||||||
<Tv className="w-8 h-8 text-primary" />
|
<Tv className="w-8 h-8 text-primary" />
|
||||||
</div>
|
</div>
|
||||||
<CardTitle className="text-2xl">CoopCoins</CardTitle>
|
<CardTitle className="text-2xl">CoopCoins</CardTitle>
|
||||||
<CardDescription>
|
<CardDescription>
|
||||||
Earn CoopCoins ($COOP) for watching content on Plex
|
Earn CoopCoins ($COOP) for watching content on Plex
|
||||||
</CardDescription>
|
</CardDescription>
|
||||||
</CardHeader>
|
</CardHeader>
|
||||||
<CardContent>
|
<CardContent>
|
||||||
<Button
|
<Button
|
||||||
onClick={handlePlexLogin}
|
onClick={handlePlexLogin}
|
||||||
disabled={isLoading}
|
disabled={isLoading}
|
||||||
className="w-full h-12 text-lg"
|
className="w-full h-12 text-lg"
|
||||||
>
|
>
|
||||||
{isLoading ? (
|
{isLoading ? (
|
||||||
<>
|
<>
|
||||||
<Loader2 className="mr-2 h-5 w-5 animate-spin" />
|
<Loader2 className="mr-2 h-5 w-5 animate-spin" />
|
||||||
Connecting...
|
Connecting...
|
||||||
</>
|
</>
|
||||||
) : (
|
) : (
|
||||||
<>
|
<>
|
||||||
<Tv className="mr-2 h-5 w-5" />
|
<Tv className="mr-2 h-5 w-5" />
|
||||||
Sign in with Plex
|
Sign in with Plex
|
||||||
</>
|
</>
|
||||||
)}
|
)}
|
||||||
</Button>
|
</Button>
|
||||||
<p className="mt-4 text-center text-sm text-muted-foreground">
|
<p className="mt-4 text-center text-sm text-muted-foreground">
|
||||||
Sign in with your Plex account to start earning rewards
|
Sign in with your Plex account to start earning rewards
|
||||||
</p>
|
</p>
|
||||||
</CardContent>
|
</CardContent>
|
||||||
</Card>
|
</Card>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
|
|||||||
+75
-60
@@ -1,100 +1,115 @@
|
|||||||
import axios from 'axios';
|
import axios from "axios";
|
||||||
|
|
||||||
const API_URL = process.env.NEXT_PUBLIC_API_URL || (typeof window !== 'undefined' ? `${window.location.origin}/api` : 'http://localhost:3001/api');
|
const API_URL =
|
||||||
|
process.env.NEXT_PUBLIC_API_URL ||
|
||||||
|
(typeof window !== "undefined"
|
||||||
|
? `${window.location.origin}/api`
|
||||||
|
: "http://localhost:3001/api");
|
||||||
|
|
||||||
export const api = axios.create({
|
export const api = axios.create({
|
||||||
baseURL: `${API_URL}/api`,
|
baseURL: `${API_URL}/api`,
|
||||||
headers: {
|
headers: {
|
||||||
'Content-Type': 'application/json',
|
"Content-Type": "application/json",
|
||||||
},
|
},
|
||||||
});
|
});
|
||||||
|
|
||||||
// Add auth token to requests
|
// Add auth token to requests
|
||||||
api.interceptors.request.use((config) => {
|
api.interceptors.request.use((config) => {
|
||||||
const token = localStorage.getItem('token');
|
const token = localStorage.getItem("token");
|
||||||
if (token) {
|
if (token) {
|
||||||
config.headers.Authorization = `Bearer ${token}`;
|
config.headers.Authorization = `Bearer ${token}`;
|
||||||
}
|
}
|
||||||
return config;
|
return config;
|
||||||
});
|
});
|
||||||
|
|
||||||
// Handle token expiration
|
// Handle token expiration
|
||||||
api.interceptors.response.use(
|
api.interceptors.response.use(
|
||||||
(response) => response,
|
(response) => response,
|
||||||
(error) => {
|
(error) => {
|
||||||
if (error.response?.status === 401) {
|
if (error.response?.status === 401) {
|
||||||
localStorage.removeItem('token');
|
localStorage.removeItem("token");
|
||||||
localStorage.removeItem('user');
|
localStorage.removeItem("user");
|
||||||
window.location.href = '/login';
|
window.location.href = "/login";
|
||||||
}
|
}
|
||||||
return Promise.reject(error);
|
return Promise.reject(error);
|
||||||
}
|
},
|
||||||
);
|
);
|
||||||
|
|
||||||
// Auth API
|
// Auth API
|
||||||
export const authApi = {
|
export const authApi = {
|
||||||
getPlexUrl: () => api.get('/auth/plex/url'),
|
getPlexUrl: () => api.get("/auth/plex/url"),
|
||||||
plexCallback: (code: string) => api.post('/auth/plex/callback', { code }),
|
plexCallback: (pinId: string) => api.post("/auth/plex/callback", { pinId }),
|
||||||
verify: () => api.get('/auth/verify'),
|
verify: () => api.get("/auth/verify"),
|
||||||
logout: () => api.post('/auth/logout'),
|
logout: () => api.post("/auth/logout"),
|
||||||
};
|
};
|
||||||
|
|
||||||
// User API
|
// User API
|
||||||
export const userApi = {
|
export const userApi = {
|
||||||
getMe: () => api.get('/users/me'),
|
getMe: () => api.get("/users/me"),
|
||||||
updateMe: (data: { email?: string }) => api.put('/users/me', data),
|
updateMe: (data: { email?: string }) => api.put("/users/me", data),
|
||||||
getWatchHistory: (page = 1, limit = 20) =>
|
getWatchHistory: (page = 1, limit = 20) =>
|
||||||
api.get(`/users/me/watch-history?page=${page}&limit=${limit}`),
|
api.get(`/users/me/watch-history?page=${page}&limit=${limit}`),
|
||||||
getRequests: (page = 1, limit = 20, status?: string) =>
|
getRequests: (page = 1, limit = 20, status?: string) =>
|
||||||
api.get(`/users/me/requests?page=${page}&limit=${limit}${status ? `&status=${status}` : ''}`),
|
api.get(
|
||||||
getLeaderboard: () => api.get('/users/leaderboard'),
|
`/users/me/requests?page=${page}&limit=${limit}${status ? `&status=${status}` : ""}`,
|
||||||
|
),
|
||||||
|
getLeaderboard: () => api.get("/users/leaderboard"),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Wallet API
|
// Wallet API
|
||||||
export const walletApi = {
|
export const walletApi = {
|
||||||
getWallet: () => api.get('/wallet'),
|
getWallet: () => api.get("/wallet"),
|
||||||
createWallet: () => api.post('/wallet/create'),
|
createWallet: () => api.post("/wallet/create"),
|
||||||
connectWallet: (address: string) => api.post('/wallet/connect', { address }),
|
connectWallet: (address: string) => api.post("/wallet/connect", { address }),
|
||||||
backupWallet: () => api.post('/wallet/backup'),
|
backupWallet: () => api.post("/wallet/backup"),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Transactions API
|
// Transactions API
|
||||||
export const transactionApi = {
|
export const transactionApi = {
|
||||||
getTransactions: (page = 1, limit = 20, type?: string) =>
|
getTransactions: (page = 1, limit = 20, type?: string) =>
|
||||||
api.get(`/transactions?page=${page}&limit=${limit}${type ? `&type=${type}` : ''}`),
|
api.get(
|
||||||
getStats: () => api.get('/transactions/stats'),
|
`/transactions?page=${page}&limit=${limit}${type ? `&type=${type}` : ""}`,
|
||||||
getRecentActivity: () => api.get('/transactions/recent'),
|
),
|
||||||
|
getStats: () => api.get("/transactions/stats"),
|
||||||
|
getRecentActivity: () => api.get("/transactions/recent"),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Admin API
|
// Admin API
|
||||||
export const adminApi = {
|
export const adminApi = {
|
||||||
getSettings: () => api.get('/admin/settings'),
|
getSettings: () => api.get("/admin/settings"),
|
||||||
updateSettings: (data: any) => api.put('/admin/settings', data),
|
updateSettings: (data: any) => api.put("/admin/settings", data),
|
||||||
pause: () => api.post('/admin/pause'),
|
pause: () => api.post("/admin/pause"),
|
||||||
resume: () => api.post('/admin/resume'),
|
resume: () => api.post("/admin/resume"),
|
||||||
getUsers: (page = 1, limit = 50, search?: string) =>
|
getUsers: (page = 1, limit = 50, search?: string) =>
|
||||||
api.get(`/admin/users?page=${page}&limit=${limit}${search ? `&search=${search}` : ''}`),
|
api.get(
|
||||||
updateUser: (id: string, data: any) => api.put(`/admin/users/${id}`, data),
|
`/admin/users?page=${page}&limit=${limit}${search ? `&search=${search}` : ""}`,
|
||||||
grantBonus: (userId: string, amount: number, reason?: string) =>
|
),
|
||||||
api.post(`/admin/users/${userId}/bonus`, { amount, reason }),
|
updateUser: (id: string, data: any) => api.put(`/admin/users/${id}`, data),
|
||||||
getAnalytics: () => api.get('/admin/analytics'),
|
grantBonus: (userId: string, amount: number, reason?: string) =>
|
||||||
getAllTransactions: (page = 1, limit = 50) =>
|
api.post(`/admin/users/${userId}/bonus`, { amount, reason }),
|
||||||
api.get(`/transactions/admin/all?page=${page}&limit=${limit}`),
|
getAnalytics: () => api.get("/admin/analytics"),
|
||||||
getSystemStats: () => api.get('/transactions/admin/stats'),
|
getAllTransactions: (page = 1, limit = 50) =>
|
||||||
|
api.get(`/transactions/admin/all?page=${page}&limit=${limit}`),
|
||||||
|
getSystemStats: () => api.get("/transactions/admin/stats"),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Overseer API
|
// Overseer API
|
||||||
export const overseerApi = {
|
export const overseerApi = {
|
||||||
getCosts: () => api.get('/overseer/costs'),
|
getCosts: () => api.get("/overseer/costs"),
|
||||||
getBalance: () => api.get('/overseer/balance'),
|
getBalance: () => api.get("/overseer/balance"),
|
||||||
search: (query: string) => api.get(`/overseer/search?query=${encodeURIComponent(query)}`),
|
search: (query: string) =>
|
||||||
request: (data: { mediaType: string; mediaId: number; title: string; seasons?: number[] }) =>
|
api.get(`/overseer/search?query=${encodeURIComponent(query)}`),
|
||||||
api.post('/overseer/request', data),
|
request: (data: {
|
||||||
|
mediaType: string;
|
||||||
|
mediaId: number;
|
||||||
|
title: string;
|
||||||
|
seasons?: number[];
|
||||||
|
}) => api.post("/overseer/request", data),
|
||||||
};
|
};
|
||||||
|
|
||||||
// Tautulli API
|
// Tautulli API
|
||||||
export const tautulliApi = {
|
export const tautulliApi = {
|
||||||
getStatus: () => api.get('/tautulli/status'),
|
getStatus: () => api.get("/tautulli/status"),
|
||||||
getStats: () => api.get('/tautulli/stats'),
|
getStats: () => api.get("/tautulli/stats"),
|
||||||
getWebhookConfig: () => api.get('/tautulli/webhook-config'),
|
getWebhookConfig: () => api.get("/tautulli/webhook-config"),
|
||||||
};
|
};
|
||||||
|
|||||||
Reference in New Issue
Block a user