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:
2026-04-21 09:27:00 -04:00
parent 7e68f57d69
commit 5751e08eb1
5 changed files with 515 additions and 460 deletions
+48 -47
View File
@@ -1,55 +1,56 @@
'use client';
"use client";
import { useEffect, useState } from 'react';
import { useRouter, useSearchParams } from 'next/navigation';
import { authApi } from '@/lib/api';
import { useStore } from '@/lib/store';
import { Loader2 } from 'lucide-react';
import { toast } from 'sonner';
import { useEffect, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { authApi } from "@/lib/api";
import { useStore } from "@/lib/store";
import { Loader2 } from "lucide-react";
import { toast } from "sonner";
export default function AuthCallbackPage() {
const router = useRouter();
const searchParams = useSearchParams();
const { setUser, setToken } = useStore();
const [status, setStatus] = useState('Completing sign in...');
const router = useRouter();
const searchParams = useSearchParams();
const { setUser, setToken } = useStore();
const [status, setStatus] = useState("Completing sign in...");
useEffect(() => {
const code = searchParams.get('code');
if (!code) {
toast.error('Invalid authentication response');
router.push('/login');
return;
}
useEffect(() => {
const pinId = sessionStorage.getItem("plexPinId");
const handleCallback = async () => {
try {
const response = await authApi.plexCallback(code);
const { user, token } = response.data;
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);
}
};
if (!pinId) {
toast.error("Invalid authentication response");
router.push("/login");
return;
}
handleCallback();
}, [searchParams, router, setUser, setToken]);
const handleCallback = async () => {
try {
const response = await authApi.plexCallback(pinId);
const { user, token } = response.data;
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>
);
sessionStorage.removeItem("plexPinId");
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();
}, [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>
);
}
+91 -84
View File
@@ -1,93 +1,100 @@
'use client';
"use client";
import { useEffect, useState } from 'react';
import { useRouter } from 'next/navigation';
import { authApi } from '@/lib/api';
import { useStore } from '@/lib/store';
import { Button } from '@/components/ui/button';
import { Card, CardContent, CardDescription, CardHeader, CardTitle } from '@/components/ui/card';
import { Loader2, Tv } from 'lucide-react';
import { toast } from 'sonner';
import { useEffect, useState } from "react";
import { useRouter } from "next/navigation";
import { authApi } from "@/lib/api";
import { useStore } from "@/lib/store";
import { Button } from "@/components/ui/button";
import {
Card,
CardContent,
CardDescription,
CardHeader,
CardTitle,
} from "@/components/ui/card";
import { Loader2, Tv } from "lucide-react";
import { toast } from "sonner";
export default function LoginPage() {
const router = useRouter();
const { isAuthenticated } = useStore();
const [isLoading, setIsLoading] = useState(false);
const [isMounted, setIsMounted] = useState(false);
const router = useRouter();
const { isAuthenticated } = useStore();
const [isLoading, setIsLoading] = useState(false);
const [isMounted, setIsMounted] = useState(false);
useEffect(() => {
setIsMounted(true);
}, []);
useEffect(() => {
setIsMounted(true);
}, []);
useEffect(() => {
if (isAuthenticated) {
router.push('/dashboard');
}
}, [isAuthenticated, router]);
useEffect(() => {
if (isAuthenticated) {
router.push("/dashboard");
}
}, [isAuthenticated, router]);
const handlePlexLogin = async () => {
setIsLoading(true);
try {
const response = await authApi.getPlexUrl();
window.location.href = response.data.authUrl;
} catch (error) {
toast.error('Failed to initiate Plex login');
console.error(error);
setIsLoading(false);
}
};
const handlePlexLogin = async () => {
setIsLoading(true);
try {
const response = await authApi.getPlexUrl();
sessionStorage.setItem("plexPinId", response.data.pinId);
window.location.href = response.data.authUrl;
} catch (error) {
toast.error("Failed to initiate Plex login");
console.error(error);
setIsLoading(false);
}
};
if (!isMounted) {
return (
<div className="min-h-screen flex items-center justify-center bg-slate-950 p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<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" />
</div>
<CardTitle className="text-2xl">CoopCoins</CardTitle>
<CardDescription>Loading...</CardDescription>
</CardHeader>
</Card>
</div>
);
}
if (!isMounted) {
return (
<div className="min-h-screen flex items-center justify-center bg-slate-950 p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<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" />
</div>
<CardTitle className="text-2xl">CoopCoins</CardTitle>
<CardDescription>Loading...</CardDescription>
</CardHeader>
</Card>
</div>
);
}
return (
<div className="min-h-screen flex items-center justify-center bg-slate-950 p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<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" />
</div>
<CardTitle className="text-2xl">CoopCoins</CardTitle>
<CardDescription>
Earn CoopCoins ($COOP) for watching content on Plex
</CardDescription>
</CardHeader>
<CardContent>
<Button
onClick={handlePlexLogin}
disabled={isLoading}
className="w-full h-12 text-lg"
>
{isLoading ? (
<>
<Loader2 className="mr-2 h-5 w-5 animate-spin" />
Connecting...
</>
) : (
<>
<Tv className="mr-2 h-5 w-5" />
Sign in with Plex
</>
)}
</Button>
<p className="mt-4 text-center text-sm text-muted-foreground">
Sign in with your Plex account to start earning rewards
</p>
</CardContent>
</Card>
</div>
);
return (
<div className="min-h-screen flex items-center justify-center bg-slate-950 p-4">
<Card className="w-full max-w-md">
<CardHeader className="text-center">
<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" />
</div>
<CardTitle className="text-2xl">CoopCoins</CardTitle>
<CardDescription>
Earn CoopCoins ($COOP) for watching content on Plex
</CardDescription>
</CardHeader>
<CardContent>
<Button
onClick={handlePlexLogin}
disabled={isLoading}
className="w-full h-12 text-lg"
>
{isLoading ? (
<>
<Loader2 className="mr-2 h-5 w-5 animate-spin" />
Connecting...
</>
) : (
<>
<Tv className="mr-2 h-5 w-5" />
Sign in with Plex
</>
)}
</Button>
<p className="mt-4 text-center text-sm text-muted-foreground">
Sign in with your Plex account to start earning rewards
</p>
</CardContent>
</Card>
</div>
);
}
+75 -60
View File
@@ -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({
baseURL: `${API_URL}/api`,
headers: {
'Content-Type': 'application/json',
},
baseURL: `${API_URL}/api`,
headers: {
"Content-Type": "application/json",
},
});
// Add auth token to requests
api.interceptors.request.use((config) => {
const token = localStorage.getItem('token');
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
const token = localStorage.getItem("token");
if (token) {
config.headers.Authorization = `Bearer ${token}`;
}
return config;
});
// Handle token expiration
api.interceptors.response.use(
(response) => response,
(error) => {
if (error.response?.status === 401) {
localStorage.removeItem('token');
localStorage.removeItem('user');
window.location.href = '/login';
}
return Promise.reject(error);
}
(response) => response,
(error) => {
if (error.response?.status === 401) {
localStorage.removeItem("token");
localStorage.removeItem("user");
window.location.href = "/login";
}
return Promise.reject(error);
},
);
// Auth API
export const authApi = {
getPlexUrl: () => api.get('/auth/plex/url'),
plexCallback: (code: string) => api.post('/auth/plex/callback', { code }),
verify: () => api.get('/auth/verify'),
logout: () => api.post('/auth/logout'),
getPlexUrl: () => api.get("/auth/plex/url"),
plexCallback: (pinId: string) => api.post("/auth/plex/callback", { pinId }),
verify: () => api.get("/auth/verify"),
logout: () => api.post("/auth/logout"),
};
// User API
export const userApi = {
getMe: () => api.get('/users/me'),
updateMe: (data: { email?: string }) => api.put('/users/me', data),
getWatchHistory: (page = 1, limit = 20) =>
api.get(`/users/me/watch-history?page=${page}&limit=${limit}`),
getRequests: (page = 1, limit = 20, status?: string) =>
api.get(`/users/me/requests?page=${page}&limit=${limit}${status ? `&status=${status}` : ''}`),
getLeaderboard: () => api.get('/users/leaderboard'),
getMe: () => api.get("/users/me"),
updateMe: (data: { email?: string }) => api.put("/users/me", data),
getWatchHistory: (page = 1, limit = 20) =>
api.get(`/users/me/watch-history?page=${page}&limit=${limit}`),
getRequests: (page = 1, limit = 20, status?: string) =>
api.get(
`/users/me/requests?page=${page}&limit=${limit}${status ? `&status=${status}` : ""}`,
),
getLeaderboard: () => api.get("/users/leaderboard"),
};
// Wallet API
export const walletApi = {
getWallet: () => api.get('/wallet'),
createWallet: () => api.post('/wallet/create'),
connectWallet: (address: string) => api.post('/wallet/connect', { address }),
backupWallet: () => api.post('/wallet/backup'),
getWallet: () => api.get("/wallet"),
createWallet: () => api.post("/wallet/create"),
connectWallet: (address: string) => api.post("/wallet/connect", { address }),
backupWallet: () => api.post("/wallet/backup"),
};
// Transactions API
export const transactionApi = {
getTransactions: (page = 1, limit = 20, type?: string) =>
api.get(`/transactions?page=${page}&limit=${limit}${type ? `&type=${type}` : ''}`),
getStats: () => api.get('/transactions/stats'),
getRecentActivity: () => api.get('/transactions/recent'),
getTransactions: (page = 1, limit = 20, type?: string) =>
api.get(
`/transactions?page=${page}&limit=${limit}${type ? `&type=${type}` : ""}`,
),
getStats: () => api.get("/transactions/stats"),
getRecentActivity: () => api.get("/transactions/recent"),
};
// Admin API
export const adminApi = {
getSettings: () => api.get('/admin/settings'),
updateSettings: (data: any) => api.put('/admin/settings', data),
pause: () => api.post('/admin/pause'),
resume: () => api.post('/admin/resume'),
getUsers: (page = 1, limit = 50, search?: string) =>
api.get(`/admin/users?page=${page}&limit=${limit}${search ? `&search=${search}` : ''}`),
updateUser: (id: string, data: any) => api.put(`/admin/users/${id}`, data),
grantBonus: (userId: string, amount: number, reason?: string) =>
api.post(`/admin/users/${userId}/bonus`, { amount, reason }),
getAnalytics: () => api.get('/admin/analytics'),
getAllTransactions: (page = 1, limit = 50) =>
api.get(`/transactions/admin/all?page=${page}&limit=${limit}`),
getSystemStats: () => api.get('/transactions/admin/stats'),
getSettings: () => api.get("/admin/settings"),
updateSettings: (data: any) => api.put("/admin/settings", data),
pause: () => api.post("/admin/pause"),
resume: () => api.post("/admin/resume"),
getUsers: (page = 1, limit = 50, search?: string) =>
api.get(
`/admin/users?page=${page}&limit=${limit}${search ? `&search=${search}` : ""}`,
),
updateUser: (id: string, data: any) => api.put(`/admin/users/${id}`, data),
grantBonus: (userId: string, amount: number, reason?: string) =>
api.post(`/admin/users/${userId}/bonus`, { amount, reason }),
getAnalytics: () => api.get("/admin/analytics"),
getAllTransactions: (page = 1, limit = 50) =>
api.get(`/transactions/admin/all?page=${page}&limit=${limit}`),
getSystemStats: () => api.get("/transactions/admin/stats"),
};
// Overseer API
export const overseerApi = {
getCosts: () => api.get('/overseer/costs'),
getBalance: () => api.get('/overseer/balance'),
search: (query: string) => api.get(`/overseer/search?query=${encodeURIComponent(query)}`),
request: (data: { mediaType: string; mediaId: number; title: string; seasons?: number[] }) =>
api.post('/overseer/request', data),
getCosts: () => api.get("/overseer/costs"),
getBalance: () => api.get("/overseer/balance"),
search: (query: string) =>
api.get(`/overseer/search?query=${encodeURIComponent(query)}`),
request: (data: {
mediaType: string;
mediaId: number;
title: string;
seasons?: number[];
}) => api.post("/overseer/request", data),
};
// Tautulli API
export const tautulliApi = {
getStatus: () => api.get('/tautulli/status'),
getStats: () => api.get('/tautulli/stats'),
getWebhookConfig: () => api.get('/tautulli/webhook-config'),
getStatus: () => api.get("/tautulli/status"),
getStats: () => api.get("/tautulli/stats"),
getWebhookConfig: () => api.get("/tautulli/webhook-config"),
};