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:
+202
-183
@@ -1,192 +1,211 @@
|
||||
import { Router } from 'express';
|
||||
import axios from 'axios';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { prisma } from '../utils/prisma';
|
||||
import { asyncHandler } from '../middleware/errorHandler';
|
||||
import { Router } from "express";
|
||||
import axios from "axios";
|
||||
import jwt from "jsonwebtoken";
|
||||
import { prisma } from "../utils/prisma";
|
||||
import { asyncHandler } from "../middleware/errorHandler";
|
||||
|
||||
const router = Router();
|
||||
|
||||
// Plex OAuth configuration
|
||||
const PLEX_CLIENT_ID = process.env.PLEX_CLIENT_ID || '';
|
||||
const PLEX_CLIENT_SECRET = process.env.PLEX_CLIENT_SECRET || '';
|
||||
const PLEX_REDIRECT_URI = process.env.PLEX_REDIRECT_URI || '';
|
||||
const JWT_SECRET = process.env.JWT_SECRET || 'secret';
|
||||
const PLEX_CLIENT_ID = process.env.PLEX_CLIENT_ID || "";
|
||||
const PLEX_REDIRECT_URI = process.env.PLEX_REDIRECT_URI || "";
|
||||
const JWT_SECRET = process.env.JWT_SECRET || "secret";
|
||||
|
||||
// Step 1: Get Plex OAuth URL
|
||||
router.get('/plex/url', asyncHandler(async (_req, res) => {
|
||||
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 });
|
||||
}));
|
||||
if (!PLEX_CLIENT_ID) {
|
||||
console.error("ERROR: PLEX_CLIENT_ID not set");
|
||||
}
|
||||
|
||||
// Step 2: Handle Plex OAuth callback
|
||||
router.post('/plex/callback', asyncHandler(async (req, res) => {
|
||||
const { code } = req.body;
|
||||
|
||||
if (!code) {
|
||||
return res.status(400).json({ error: 'Authorization code required' });
|
||||
}
|
||||
|
||||
// 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
|
||||
}
|
||||
});
|
||||
}));
|
||||
// Step 1: Generate Plex PIN and return auth URL
|
||||
router.get(
|
||||
"/plex/url",
|
||||
asyncHandler(async (_req, res) => {
|
||||
if (!PLEX_CLIENT_ID) {
|
||||
return res.status(500).json({ error: "Plex not configured" });
|
||||
}
|
||||
|
||||
// Verify token
|
||||
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' });
|
||||
}
|
||||
}));
|
||||
const pinResponse = await axios.post(
|
||||
"https://plex.tv/api/v2/pins?strong=true",
|
||||
null,
|
||||
{
|
||||
headers: {
|
||||
Accept: "application/json",
|
||||
"X-Plex-Client-Identifier": PLEX_CLIENT_ID,
|
||||
"X-Plex-Product": "CoopCoins",
|
||||
"X-Plex-Version": "1.0.0",
|
||||
"X-Plex-Device": "Web Browser",
|
||||
"X-Plex-Platform": "Web",
|
||||
},
|
||||
},
|
||||
);
|
||||
|
||||
// Logout
|
||||
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 {
|
||||
// Invalid token, ignore
|
||||
}
|
||||
}
|
||||
|
||||
res.json({ message: 'Logged out successfully' });
|
||||
}));
|
||||
const pin = pinResponse.data;
|
||||
const authUrl = `https://app.plex.tv/auth#?clientID=${encodeURIComponent(PLEX_CLIENT_ID)}&code=${pin.code}&forwardUrl=${encodeURIComponent(PLEX_REDIRECT_URI)}`;
|
||||
|
||||
res.json({ authUrl, pinId: pin.id });
|
||||
}),
|
||||
);
|
||||
|
||||
// Step 2: Exchange PIN for Plex token and create user session
|
||||
router.post(
|
||||
"/plex/callback",
|
||||
asyncHandler(async (req, res) => {
|
||||
const { pinId } = req.body;
|
||||
|
||||
if (!pinId) {
|
||||
return res.status(400).json({ error: "PIN ID required" });
|
||||
}
|
||||
|
||||
// Check PIN status to get auth token
|
||||
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 };
|
||||
|
||||
Reference in New Issue
Block a user