feat: add review writing page and integrate Steam account linking

- Implemented WriteReviewPage for users to submit reviews with ratings and playtime.
- Created global CSS styles for consistent theming across the application.
- Established RootLayout for metadata and global styles.
- Developed LoginPage for user authentication with email/password and Steam login options.
- Built Home page to display game search results and recent reviews.
- Added LinkSteamPage for linking Steam accounts to user profiles.
- Created ProfilePage to manage user information and display their reviews.
- Developed GameCard and ReviewCard components for displaying games and reviews.
- Implemented Header component for navigation and user session management.
- Added Providers component to wrap the application with session context.
- Integrated NextAuth for user authentication with Steam and credentials.
- Set up Prisma client for database interactions.
- Created Steam API utility functions for fetching game and user data.
- Configured TypeScript settings for the project.
This commit is contained in:
2026-02-22 02:53:23 +05:00
parent ce018da271
commit 1a6e754e4b
41 changed files with 2093 additions and 2 deletions

View File

@@ -0,0 +1,3 @@
import { handlers } from '@/lib/auth'
export const { GET, POST } = handlers

View File

@@ -0,0 +1,51 @@
import { NextRequest, NextResponse } from 'next/server'
import { hash } from 'bcryptjs'
import { prisma } from '@/lib/db'
export async function POST(request: NextRequest) {
try {
const { email, username, password } = await request.json()
if (!email || !username || !password) {
return NextResponse.json(
{ error: 'All fields are required' },
{ status: 400 }
)
}
const existingUser = await prisma.user.findFirst({
where: {
OR: [{ email }, { username }]
}
})
if (existingUser) {
return NextResponse.json(
{ error: 'Email or username already exists' },
{ status: 400 }
)
}
const passwordHash = await hash(password, 12)
const user = await prisma.user.create({
data: {
email,
username,
passwordHash
}
})
return NextResponse.json({
id: user.id,
email: user.email,
username: user.username
})
} catch (error) {
console.error('Registration error:', error)
return NextResponse.json(
{ error: 'Something went wrong' },
{ status: 500 }
)
}
}

View File

@@ -0,0 +1,54 @@
import { NextRequest, NextResponse } from 'next/server'
import { getGameDetails } from '@/lib/steam'
import { prisma } from '@/lib/db'
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ appId: string }> }
) {
const resolvedParams = await params
const appId = parseInt(resolvedParams.appId)
if (isNaN(appId)) {
return NextResponse.json({ error: 'Invalid app ID' }, { status: 400 })
}
let game = await prisma.game.findUnique({
where: { app_id: appId }
})
if (!game) {
const steamData = await getGameDetails(appId)
if (!steamData) {
return NextResponse.json({ error: 'Game not found' }, { status: 404 })
}
game = await prisma.game.create({
data: {
app_id: appId,
name: steamData.name,
description: steamData.short_description,
header_image: steamData.header_image,
capsule_image: steamData.capsule_image,
background_image: steamData.background,
release_date: steamData.release_date?.date,
developers: steamData.developers || [],
publishers: steamData.publishers || [],
genres: steamData.genres?.map(g => g.description) || []
}
})
}
return NextResponse.json({
app_id: game.app_id,
name: game.name,
description: game.description,
header_image: game.header_image,
background_image: game.background_image,
release_date: game.release_date,
developers: game.developers,
publishers: game.publishers,
genres: game.genres
})
}

View File

@@ -0,0 +1,34 @@
import { NextRequest, NextResponse } from 'next/server'
import { searchSteamGames, getGameDetails } from '@/lib/steam'
import { prisma } from '@/lib/db'
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url)
const query = searchParams.get('q')
if (!query) {
return NextResponse.json([])
}
const cachedGames = await prisma.game.findMany({
where: {
name: {
contains: query,
mode: 'insensitive'
}
},
select: {
app_id: true,
name: true,
header_image: true
},
take: 10
})
if (cachedGames.length > 0) {
return NextResponse.json(cachedGames)
}
const steamGames = await searchSteamGames(query)
return NextResponse.json(steamGames)
}

View File

@@ -0,0 +1,61 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/db'
export async function POST(
request: NextRequest,
{ params }: { params: Promise<{ id: string }> }
) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const resolvedParams = await params
const { voteType } = await request.json()
if (voteType !== 1 && voteType !== -1) {
return NextResponse.json({ error: 'Invalid vote type' }, { status: 400 })
}
const review = await prisma.review.findUnique({
where: { id: resolvedParams.id }
})
if (!review) {
return NextResponse.json({ error: 'Review not found' }, { status: 404 })
}
const existingVote = await prisma.vote.findUnique({
where: {
user_review_unique: {
user_id: session.user.id,
review_id: resolvedParams.id
}
}
})
if (existingVote) {
if (existingVote.vote_type === voteType) {
await prisma.vote.delete({
where: { id: existingVote.id }
})
} else {
await prisma.vote.update({
where: { id: existingVote.id },
data: { vote_type: voteType }
})
}
} else {
await prisma.vote.create({
data: {
user_id: session.user.id,
review_id: resolvedParams.id,
vote_type: voteType
}
})
}
return NextResponse.json({ success: true })
}

View File

@@ -0,0 +1,119 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/db'
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url)
const appId = searchParams.get('appId')
const userOnly = searchParams.get('userOnly') === 'true'
const limit = parseInt(searchParams.get('limit') || '20')
const session = await auth()
const userId = session?.user?.id
const where: Record<string, unknown> = {}
if (appId) {
where.app_id = parseInt(appId)
}
const reviews = await prisma.review.findMany({
where,
include: {
user: {
select: {
username: true,
steamAvatar: true
}
},
votes: true,
game: {
select: {
name: true
}
}
},
orderBy: {
created_at: 'desc'
},
take: limit
})
const formattedReviews = reviews.map(review => {
const upvotes = review.votes.filter(v => v.vote_type === 1).length
const downvotes = review.votes.filter(v => v.vote_type === -1).length
const userVote = userId
? review.votes.find(v => v.user_id === userId)?.vote_type || null
: null
return {
id: review.id,
username: review.user.username,
avatar_url: review.user.steamAvatar,
content: review.content,
rating: review.rating,
playtime_hours: review.playtime_hours,
upvotes,
downvotes,
user_vote: userVote,
created_at: review.created_at.toISOString(),
game_name: review.game?.name
}
})
return NextResponse.json(formattedReviews)
}
export async function POST(request: NextRequest) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
if (!session.user.steamId) {
return NextResponse.json(
{ error: 'Steam account required to post reviews' },
{ status: 403 }
)
}
const { appId, content, rating, playtimeHours } = await request.json()
if (!appId || !content || !rating) {
return NextResponse.json(
{ error: 'Missing required fields' },
{ status: 400 }
)
}
const existingReview = await prisma.review.findFirst({
where: {
user_id: session.user.id,
app_id: appId
}
})
if (existingReview) {
return NextResponse.json(
{ error: 'You have already reviewed this game' },
{ status: 400 }
)
}
const game = await prisma.game.findUnique({
where: { app_id: appId }
})
const review = await prisma.review.create({
data: {
user_id: session.user.id,
app_id: appId,
content,
rating,
playtime_hours: playtimeHours || null
}
})
return NextResponse.json(review)
}

View File

@@ -0,0 +1,25 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { getPlayerPlaytime, getPlayerAchievements } from '@/lib/steam'
export async function GET(
request: NextRequest,
{ params }: { params: Promise<{ appId: string }> }
) {
const session = await auth()
if (!session?.user?.steamId) {
return NextResponse.json({ error: 'Steam not linked' }, { status: 401 })
}
const resolvedParams = await params
const appId = parseInt(resolvedParams.appId)
const playtime = await getPlayerPlaytime(session.user.steamId, appId)
const achievements = await getPlayerAchievements(session.user.steamId, appId)
return NextResponse.json({
playtime,
achievements: achievements?.achievements || []
})
}

View File

@@ -0,0 +1,33 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { extractSteamIdFromIdentity, getPlayerProfile } from '@/lib/steam'
import { prisma } from '@/lib/db'
export async function GET(request: NextRequest) {
const { searchParams } = new URL(request.url)
const identity = searchParams.get('openid.identity')
const claimedId = searchParams.get('openid.claimed_id')
const steamId = extractSteamIdFromIdentity(identity || claimedId || '')
if (!steamId) {
return NextResponse.redirect(new URL('/profile?error=steam_link_failed', request.url))
}
const profile = await getPlayerProfile(steamId)
const session = await auth()
if (session?.user?.id) {
await prisma.user.update({
where: { id: session.user.id },
data: {
steamId: steamId,
steamPersonaname: profile?.personaname || null,
steamAvatar: profile?.avatarfull || null
}
})
}
return NextResponse.redirect(new URL('/profile?steam_linked=true', request.url))
}

View File

@@ -0,0 +1,18 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { getSteamOpenIDUrl } from '@/lib/steam'
export async function POST(request: NextRequest) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
const baseUrl = process.env.NEXTAUTH_URL || 'http://localhost:3000'
const returnTo = `${baseUrl}/api/steam/callback`
const openIdUrl = getSteamOpenIDUrl(returnTo)
return NextResponse.json({ url: openIdUrl })
}

View File

@@ -0,0 +1,22 @@
import { NextRequest, NextResponse } from 'next/server'
import { auth } from '@/lib/auth'
import { prisma } from '@/lib/db'
export async function POST(request: NextRequest) {
const session = await auth()
if (!session?.user?.id) {
return NextResponse.json({ error: 'Unauthorized' }, { status: 401 })
}
await prisma.user.update({
where: { id: session.user.id },
data: {
steamId: null,
steamPersonaname: null,
steamAvatar: null
}
})
return NextResponse.json({ success: true })
}

BIN
src/app/favicon.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 25 KiB

View File

@@ -0,0 +1,218 @@
'use client'
import { useState, useEffect } from 'react'
import { useSession } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import { ReviewCard } from '@/components/ReviewCard'
import Link from 'next/link'
interface GameDetails {
app_id: number
name: string
description: string | null
header_image: string | null
background_image: string | null
release_date: string | null
developers: string[]
publishers: string[]
genres: string[]
}
interface Review {
id: string
username: string
avatar_url: string | null
content: string
rating: number
playtime_hours: number | null
upvotes: number
downvotes: number
user_vote: number | null
created_at: string
}
export default function GamePage({ params }: { params: Promise<{ appId: string }> }) {
const { data: session } = useSession()
const router = useRouter()
const [game, setGame] = useState<GameDetails | null>(null)
const [reviews, setReviews] = useState<Review[]>([])
const [loading, setLoading] = useState(true)
const [resolvedParams, setResolvedParams] = useState<{ appId: string } | null>(null)
useEffect(() => {
params.then(setResolvedParams)
}, [params])
useEffect(() => {
if (!resolvedParams) return
const fetchData = async () => {
setLoading(true)
try {
const [gameRes, reviewsRes] = await Promise.all([
fetch(`/api/games/${resolvedParams.appId}`),
fetch(`/api/reviews?appId=${resolvedParams.appId}`)
])
const gameData = await gameRes.json()
const reviewsData = await reviewsRes.json()
setGame(gameData)
setReviews(reviewsData)
} catch (error) {
console.error('Failed to fetch data:', error)
} finally {
setLoading(false)
}
}
fetchData()
}, [resolvedParams])
const handleVote = async (reviewId: string, voteType: 1 | -1) => {
await fetch(`/api/reviews/${reviewId}/vote`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ voteType })
})
const res = await fetch(`/api/reviews?appId=${resolvedParams?.appId}`)
const data = await res.json()
setReviews(data)
}
const canReview = session?.user?.steamId
if (loading) {
return (
<div className="flex items-center justify-center min-h-[50vh]">
<div className="text-white">Loading...</div>
</div>
)
}
if (!game) {
return (
<div className="flex items-center justify-center min-h-[50vh]">
<div className="text-white">Game not found</div>
</div>
)
}
return (
<div>
<div
className="relative h-64 md:h-96 bg-cover bg-center"
style={{ backgroundImage: game.background_image ? `url(${game.background_image})` : undefined }}
>
<div className="absolute inset-0 bg-gradient-to-t from-[#1a1a2e] to-transparent" />
</div>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 -mt-32 relative z-10">
<div className="flex flex-col md:flex-row gap-8">
<div className="w-full md:w-1/3">
<img
src={game.header_image || '/placeholder.png'}
alt={game.name}
className="w-full rounded-xl shadow-2xl"
/>
</div>
<div className="w-full md:w-2/3">
<h1 className="text-4xl font-bold text-white mb-4">{game.name}</h1>
<div className="flex flex-wrap gap-2 mb-4">
{game.genres.map((genre) => (
<span
key={genre}
className="px-3 py-1 bg-[#16213e] text-gray-300 rounded-full text-sm"
>
{genre}
</span>
))}
</div>
{game.developers.length > 0 && (
<p className="text-gray-400 mb-2">
<span className="text-white">Developer:</span> {game.developers.join(', ')}
</p>
)}
{game.publishers.length > 0 && (
<p className="text-gray-400 mb-2">
<span className="text-white">Publisher:</span> {game.publishers.join(', ')}
</p>
)}
{game.release_date && (
<p className="text-gray-400 mb-4">
<span className="text-white">Release Date:</span> {game.release_date}
</p>
)}
{canReview ? (
<Link
href={`/game/${game.app_id}/write`}
className="inline-block px-6 py-3 bg-[#00d4ff] hover:bg-[#00b8e6] text-[#1a1a2e] font-medium rounded-lg transition-colors"
>
Write a Review
</Link>
) : session ? (
<Link
href="/profile/link-steam"
className="inline-block px-6 py-3 bg-[#7c3aed] hover:bg-[#6d28d9] text-white font-medium rounded-lg transition-colors"
>
Link Steam to Write Review
</Link>
) : (
<Link
href="/login"
className="inline-block px-6 py-3 bg-[#00d4ff] hover:bg-[#00b8e6] text-[#1a1a2e] font-medium rounded-lg transition-colors"
>
Sign In to Write Review
</Link>
)}
</div>
</div>
{game.description && (
<div className="mt-8 bg-[#16213e] rounded-xl p-6">
<h2 className="text-2xl font-bold text-white mb-4">About</h2>
<p className="text-gray-300 whitespace-pre-line">{game.description}</p>
</div>
)}
<div className="mt-8 mb-12">
<h2 className="text-2xl font-bold text-white mb-6">
Reviews ({reviews.length})
</h2>
{reviews.length === 0 ? (
<div className="text-center py-12 bg-[#16213e] rounded-xl">
<p className="text-gray-400">No reviews yet. Be the first to write one!</p>
</div>
) : (
<div className="space-y-4">
{reviews.map((review) => (
<ReviewCard
key={review.id}
id={review.id}
username={review.username}
avatarUrl={review.avatar_url}
content={review.content}
rating={review.rating}
playtimeHours={review.playtime_hours}
upvotes={review.upvotes}
downvotes={review.downvotes}
userVote={review.user_vote}
createdAt={review.created_at}
onVote={handleVote}
/>
))}
</div>
)}
</div>
</div>
</div>
)
}

View File

@@ -0,0 +1,159 @@
'use client'
import { useState, useEffect } from 'react'
import { useSession } from 'next-auth/react'
import { useRouter } from 'next/navigation'
export default function WriteReviewPage({ params }: { params: Promise<{ appId: string }> }) {
const { data: session, update } = useSession()
const router = useRouter()
const [content, setContent] = useState('')
const [rating, setRating] = useState(5)
const [loading, setLoading] = useState(true)
const [submitting, setSubmitting] = useState(false)
const [game, setGame] = useState<{ name: string; header_image: string | null } | null>(null)
const [playtime, setPlaytime] = useState<number>(0)
const [resolvedParams, setResolvedParams] = useState<{ appId: string } | null>(null)
useEffect(() => {
params.then(setResolvedParams)
}, [params])
useEffect(() => {
if (!resolvedParams) return
const fetchData = async () => {
try {
const [gameRes, statsRes] = await Promise.all([
fetch(`/api/games/${resolvedParams.appId}`),
session?.user?.steamId
? fetch(`/api/steam/${resolvedParams.appId}/stats`).then(r => r.json()).catch(() => null)
: Promise.resolve(null)
])
const gameData = await gameRes.json()
setGame(gameData)
if (statsRes) {
setPlaytime(statsRes.playtime || 0)
}
} catch (error) {
console.error('Failed to fetch data:', error)
} finally {
setLoading(false)
}
}
fetchData()
}, [resolvedParams, session])
useEffect(() => {
if (session && !session.user.steamId) {
router.push('/profile/link-steam')
}
}, [session, router])
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
if (!session?.user?.steamId || !resolvedParams) return
setSubmitting(true)
try {
const res = await fetch('/api/reviews', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({
appId: parseInt(resolvedParams.appId),
content,
rating,
playtimeHours: playtime
})
})
if (res.ok) {
router.push(`/game/${resolvedParams.appId}`)
} else {
const data = await res.json()
alert(data.error || 'Failed to submit review')
}
} catch (error) {
console.error('Failed to submit review:', error)
} finally {
setSubmitting(false)
}
}
if (loading) {
return (
<div className="flex items-center justify-center min-h-[50vh]">
<div className="text-white">Loading...</div>
</div>
)
}
if (!session?.user?.steamId) {
return null
}
return (
<div className="max-w-3xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<h1 className="text-3xl font-bold text-white mb-8">Write a Review</h1>
{game && (
<div className="flex items-center gap-4 mb-8 bg-[#16213e] rounded-xl p-4">
<img
src={game.header_image || '/placeholder.png'}
alt={game.name}
className="w-24 h-16 object-cover rounded"
/>
<div>
<h2 className="text-xl font-bold text-white">{game.name}</h2>
<p className="text-gray-400">Your playtime: {playtime} hours</p>
</div>
</div>
)}
<form onSubmit={handleSubmit} className="space-y-6">
<div>
<label className="block text-white mb-2">Rating</label>
<div className="flex items-center gap-2">
{[1, 2, 3, 4, 5, 6, 7, 8, 9, 10].map((r) => (
<button
key={r}
type="button"
onClick={() => setRating(r)}
className={`w-10 h-10 rounded-lg font-bold transition-colors ${
rating === r
? 'bg-[#00d4ff] text-[#1a1a2e]'
: 'bg-[#16213e] text-gray-400 hover:bg-[#1a1a2e]'
}`}
>
{r}
</button>
))}
</div>
</div>
<div>
<label className="block text-white mb-2">Your Review</label>
<textarea
value={content}
onChange={(e) => setContent(e.target.value)}
rows={8}
className="w-full px-4 py-3 rounded-lg bg-[#16213e] border border-[#0f3460] text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#00d4ff]"
placeholder="Share your thoughts about this game..."
required
/>
</div>
<button
type="submit"
disabled={submitting}
className="w-full py-3 bg-[#00d4ff] hover:bg-[#00b8e6] text-[#1a1a2e] font-medium rounded-lg transition-colors disabled:opacity-50"
>
{submitting ? 'Submitting...' : 'Submit Review'}
</button>
</form>
</div>
)
}

21
src/app/globals.css Normal file
View File

@@ -0,0 +1,21 @@
@import "tailwindcss";
:root {
--background: #1a1a2e;
--foreground: #ffffff;
}
@theme inline {
--color-background: var(--background);
--color-foreground: var(--foreground);
}
body {
background: var(--background);
color: var(--foreground);
font-family: 'Inter', system-ui, -apple-system, sans-serif;
}
* {
box-sizing: border-box;
}

22
src/app/layout.tsx Normal file
View File

@@ -0,0 +1,22 @@
import type { Metadata } from "next"
import "./globals.css"
import { Providers } from "@/components/Providers"
export const metadata: Metadata = {
title: "FairReview - Steam Game Reviews",
description: "Honest game reviews from real players with Steam integration",
}
export default function RootLayout({
children,
}: Readonly<{
children: React.ReactNode
}>) {
return (
<html lang="en">
<body className="antialiased">
<Providers>{children}</Providers>
</body>
</html>
)
}

164
src/app/login/page.tsx Normal file
View File

@@ -0,0 +1,164 @@
'use client'
import { useState } from 'react'
import { signIn } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import Link from 'next/link'
export default function LoginPage() {
const router = useRouter()
const [isLogin, setIsLogin] = useState(true)
const [email, setEmail] = useState('')
const [password, setPassword] = useState('')
const [username, setUsername] = useState('')
const [error, setError] = useState('')
const [loading, setLoading] = useState(false)
const handleSubmit = async (e: React.FormEvent) => {
e.preventDefault()
setError('')
setLoading(true)
try {
if (isLogin) {
const result = await signIn('credentials', {
email,
password,
redirect: false
})
if (result?.error) {
setError('Invalid email or password')
} else {
router.push('/')
router.refresh()
}
} else {
const res = await fetch('/api/auth/register', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ email, username, password })
})
const data = await res.json()
if (!res.ok) {
setError(data.error || 'Registration failed')
} else {
const result = await signIn('credentials', {
email,
password,
redirect: false
})
if (result?.error) {
setError('Registration succeeded but login failed')
} else {
router.push('/')
router.refresh()
}
}
}
} catch (err) {
setError('Something went wrong')
} finally {
setLoading(false)
}
}
const handleSteamLogin = () => {
signIn('steam', { callbackUrl: '/' })
}
return (
<div className="min-h-[calc(100vh-4rem)] flex items-center justify-center px-4">
<div className="w-full max-w-md">
<div className="bg-[#16213e] rounded-2xl p-8">
<h1 className="text-3xl font-bold text-white text-center mb-8">
{isLogin ? 'Welcome Back' : 'Create Account'}
</h1>
<form onSubmit={handleSubmit} className="space-y-4">
{!isLogin && (
<div>
<label className="block text-gray-400 mb-2">Username</label>
<input
type="text"
value={username}
onChange={(e) => setUsername(e.target.value)}
className="w-full px-4 py-3 rounded-lg bg-[#1a1a2e] border border-[#0f3460] text-white focus:outline-none focus:ring-2 focus:ring-[#00d4ff]"
required
/>
</div>
)}
<div>
<label className="block text-gray-400 mb-2">Email</label>
<input
type="email"
value={email}
onChange={(e) => setEmail(e.target.value)}
className="w-full px-4 py-3 rounded-lg bg-[#1a1a2e] border border-[#0f3460] text-white focus:outline-none focus:ring-2 focus:ring-[#00d4ff]"
required
/>
</div>
<div>
<label className="block text-gray-400 mb-2">Password</label>
<input
type="password"
value={password}
onChange={(e) => setPassword(e.target.value)}
className="w-full px-4 py-3 rounded-lg bg-[#1a1a2e] border border-[#0f3460] text-white focus:outline-none focus:ring-2 focus:ring-[#00d4ff]"
required
/>
</div>
{error && (
<p className="text-red-400 text-sm">{error}</p>
)}
<button
type="submit"
disabled={loading}
className="w-full py-3 bg-[#00d4ff] hover:bg-[#00b8e6] text-[#1a1a2e] font-medium rounded-lg transition-colors disabled:opacity-50"
>
{loading ? 'Please wait...' : isLogin ? 'Sign In' : 'Create Account'}
</button>
</form>
<div className="mt-6">
<div className="relative">
<div className="absolute inset-0 flex items-center">
<div className="w-full border-t border-[#0f3460]"></div>
</div>
<div className="relative flex justify-center text-sm">
<span className="px-4 bg-[#16213e] text-gray-400">Or continue with</span>
</div>
</div>
<button
onClick={handleSteamLogin}
className="mt-4 w-full py-3 bg-[#1b2838] hover:bg-[#2a475e] text-white font-medium rounded-lg transition-colors flex items-center justify-center gap-2"
>
<svg viewBox="0 0 24 24" className="w-6 h-6" fill="currentColor">
<path d="M11.979 0C5.678 0 .527 4.92.044 11.15l3.632 5.336c.456-.274.99-.42 1.548-.42 1.706 0 3.088 1.382 3.088 3.088 0 1.706-1.382 3.088-3.088 3.088-1.274 0-2.397-.77-2.92-1.888L.582 22.78C2.542 20.296 5.458 18.75 8.71 18.75c5.302 0 9.584-4.282 9.584-9.584C18.294 4.282 13.574 0 11.979 0zm-2.42 5.16c-1.382 0-2.5 1.118-2.5 2.5 0 1.382 1.118 2.5 2.5 2.5 1.382 0 2.5-1.118 2.5-2.5 0-1.382-1.118-2.5-2.5-2.5z"/>
</svg>
Sign in with Steam
</button>
</div>
<p className="mt-8 text-center text-gray-400">
{isLogin ? "Don't have an account? " : 'Already have an account? '}
<button
onClick={() => setIsLogin(!isLogin)}
className="text-[#00d4ff] hover:underline"
>
{isLogin ? 'Sign Up' : 'Sign In'}
</button>
</p>
</div>
</div>
</div>
)
}

151
src/app/page.tsx Normal file
View File

@@ -0,0 +1,151 @@
'use client'
import { useState, useEffect } from 'react'
import { GameCard } from '@/components/GameCard'
import { ReviewCard } from '@/components/ReviewCard'
interface Game {
app_id: number
name: string
header_image: string | null
}
interface Review {
id: string
username: string
avatar_url: string | null
content: string
rating: number
playtime_hours: number | null
upvotes: number
downvotes: number
user_vote: number | null
created_at: string
}
export default function Home() {
const [searchQuery, setSearchQuery] = useState('')
const [games, setGames] = useState<Game[]>([])
const [recentReviews, setRecentReviews] = useState<Review[]>([])
const [loading, setLoading] = useState(false)
const searchGames = async () => {
if (!searchQuery.trim()) return
setLoading(true)
try {
const res = await fetch(`/api/games/search?q=${encodeURIComponent(searchQuery)}`)
const data = await res.json()
setGames(data)
} catch (error) {
console.error('Search failed:', error)
} finally {
setLoading(false)
}
}
const fetchRecentReviews = async () => {
try {
const res = await fetch('/api/reviews?limit=5')
const data = await res.json()
setRecentReviews(data)
} catch (error) {
console.error('Failed to fetch reviews:', error)
}
}
useEffect(() => {
fetchRecentReviews()
}, [])
const handleVote = async (reviewId: string, voteType: 1 | -1) => {
await fetch(`/api/reviews/${reviewId}/vote`, {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify({ voteType })
})
fetchRecentReviews()
}
const handleKeyDown = (e: React.KeyboardEvent) => {
if (e.key === 'Enter') {
searchGames()
}
}
return (
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div className="text-center mb-12">
<h1 className="text-4xl font-bold text-white mb-4">
Discover & Review Steam Games
</h1>
<p className="text-gray-400 mb-8">
Real reviews from real players with Steam integration
</p>
<div className="max-w-xl mx-auto">
<div className="flex gap-2">
<input
type="text"
value={searchQuery}
onChange={(e) => setSearchQuery(e.target.value)}
onKeyDown={handleKeyDown}
placeholder="Search for Steam games..."
className="flex-1 px-4 py-3 rounded-lg bg-[#16213e] border border-[#0f3460] text-white placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-[#00d4ff]"
/>
<button
onClick={searchGames}
disabled={loading}
className="px-6 py-3 bg-[#00d4ff] hover:bg-[#00b8e6] text-[#1a1a2e] font-medium rounded-lg transition-colors disabled:opacity-50"
>
{loading ? 'Searching...' : 'Search'}
</button>
</div>
</div>
</div>
{games.length > 0 && (
<div className="mb-12">
<h2 className="text-2xl font-bold text-white mb-6">Search Results</h2>
<div className="grid grid-cols-2 md:grid-cols-3 lg:grid-cols-4 gap-6">
{games.map((game) => (
<GameCard
key={game.app_id}
appId={game.app_id}
name={game.name}
headerImage={game.header_image}
/>
))}
</div>
</div>
)}
<div>
<h2 className="text-2xl font-bold text-white mb-6">Recent Reviews</h2>
{recentReviews.length === 0 ? (
<div className="text-center py-12 bg-[#16213e] rounded-xl">
<p className="text-gray-400">No reviews yet. Be the first to write one!</p>
</div>
) : (
<div className="space-y-4">
{recentReviews.map((review) => (
<ReviewCard
key={review.id}
id={review.id}
username={review.username}
avatarUrl={review.avatar_url}
content={review.content}
rating={review.rating}
playtimeHours={review.playtime_hours}
upvotes={review.upvotes}
downvotes={review.downvotes}
userVote={review.user_vote}
createdAt={review.created_at}
onVote={handleVote}
/>
))}
</div>
)}
</div>
</div>
)
}

View File

@@ -0,0 +1,45 @@
'use client'
import { useSession } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import { useEffect } from 'react'
export default function LinkSteamPage() {
const { data: session, update } = useSession()
const router = useRouter()
useEffect(() => {
if (!session) {
router.push('/login')
return
}
const linkSteam = async () => {
try {
const res = await fetch('/api/steam/link', { method: 'POST' })
const data = await res.json()
if (data.url) {
window.location.href = data.url
} else if (data.error) {
alert(data.error)
router.push('/profile')
}
} catch (error) {
console.error('Failed to link Steam:', error)
router.push('/profile')
}
}
linkSteam()
}, [session, router])
return (
<div className="flex items-center justify-center min-h-[50vh]">
<div className="text-center">
<div className="text-4xl mb-4">🔄</div>
<p className="text-white text-xl">Connecting to Steam...</p>
</div>
</div>
)
}

147
src/app/profile/page.tsx Normal file
View File

@@ -0,0 +1,147 @@
'use client'
import { useSession } from 'next-auth/react'
import { useRouter } from 'next/navigation'
import { useEffect, useState } from 'react'
import Link from 'next/link'
interface UserReview {
id: string
app_id: number
game_name: string
content: string
rating: number
created_at: string
}
export default function ProfilePage() {
const { data: session, update } = useSession()
const router = useRouter()
const [reviews, setReviews] = useState<UserReview[]>([])
const [loading, setLoading] = useState(true)
useEffect(() => {
if (!session) {
router.push('/login')
return
}
const fetchReviews = async () => {
try {
const res = await fetch('/api/reviews?userOnly=true')
const data = await res.json()
setReviews(data)
} catch (error) {
console.error('Failed to fetch reviews:', error)
} finally {
setLoading(false)
}
}
fetchReviews()
}, [session, router])
const handleUnlinkSteam = async () => {
if (!confirm('Are you sure you want to unlink your Steam account?')) return
try {
const res = await fetch('/api/steam/unlink', { method: 'POST' })
if (res.ok) {
await update()
window.location.reload()
}
} catch (error) {
console.error('Failed to unlink Steam:', error)
}
}
if (!session) {
return null
}
return (
<div className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
<div className="bg-[#16213e] rounded-xl p-6 mb-8">
<div className="flex items-center gap-6">
<div className="w-20 h-20 rounded-full bg-[#1a1a2e] flex items-center justify-center overflow-hidden">
{session.user.steamAvatar ? (
<img
src={session.user.steamAvatar}
alt="Steam Avatar"
className="w-full h-full object-cover"
/>
) : (
<span className="text-4xl">👤</span>
)}
</div>
<div>
<h1 className="text-2xl font-bold text-white">{session.user.name}</h1>
<p className="text-gray-400">{session.user.email}</p>
<div className="mt-2">
{session.user.steamId ? (
<div className="flex items-center gap-3">
<span className="px-3 py-1 bg-green-600 text-white text-sm rounded-full">
Steam Linked
</span>
<button
onClick={handleUnlinkSteam}
className="text-red-400 hover:text-red-300 text-sm"
>
Unlink
</button>
</div>
) : (
<Link
href="/profile/link-steam"
className="inline-block px-4 py-2 bg-[#00d4ff] hover:bg-[#00b8e6] text-[#1a1a2e] text-sm font-medium rounded-lg transition-colors"
>
Link Steam Account
</Link>
)}
</div>
</div>
</div>
</div>
<div>
<h2 className="text-2xl font-bold text-white mb-6">Your Reviews</h2>
{loading ? (
<div className="text-center py-8 text-gray-400">Loading...</div>
) : reviews.length === 0 ? (
<div className="text-center py-12 bg-[#16213e] rounded-xl">
<p className="text-gray-400 mb-4">You haven't written any reviews yet.</p>
<Link
href="/"
className="text-[#00d4ff] hover:underline"
>
Browse games to write your first review
</Link>
</div>
) : (
<div className="space-y-4">
{reviews.map((review) => (
<div key={review.id} className="bg-[#16213e] rounded-xl p-6">
<div className="flex items-center justify-between mb-2">
<Link
href={`/game/${review.app_id}`}
className="text-xl font-bold text-white hover:text-[#00d4ff]"
>
{review.game_name}
</Link>
<span className="text-[#00d4ff] font-bold">{review.rating}/10</span>
</div>
<p className="text-gray-300 mb-2">{review.content}</p>
<p className="text-gray-500 text-sm">
{new Date(review.created_at).toLocaleDateString()}
</p>
</div>
))}
</div>
)}
</div>
</div>
)
}

View File

@@ -0,0 +1,32 @@
import Link from 'next/link'
interface GameCardProps {
appId: number
name: string
headerImage?: string | null
}
export function GameCard({ appId, name, headerImage }: GameCardProps) {
return (
<Link href={`/game/${appId}`}>
<div className="bg-[#16213e] rounded-xl overflow-hidden hover:ring-2 hover:ring-[#00d4ff] transition-all group">
<div className="aspect-video relative overflow-hidden">
{headerImage ? (
<img
src={headerImage}
alt={name}
className="w-full h-full object-cover group-hover:scale-105 transition-transform duration-300"
/>
) : (
<div className="w-full h-full bg-[#1a1a2e] flex items-center justify-center">
<span className="text-4xl">🎮</span>
</div>
)}
</div>
<div className="p-4">
<h3 className="text-white font-medium truncate">{name}</h3>
</div>
</div>
</Link>
)
}

56
src/components/Header.tsx Normal file
View File

@@ -0,0 +1,56 @@
'use client'
import Link from 'next/link'
import { useSession, signOut } from 'next-auth/react'
export function Header() {
const { data: session } = useSession()
return (
<header className="bg-[#1a1a2e] border-b border-[#16213e]">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="flex items-center justify-between h-16">
<Link href="/" className="flex items-center space-x-2">
<div className="w-8 h-8 bg-gradient-to-br from-[#00d4ff] to-[#7c3aed] rounded-lg flex items-center justify-center">
<span className="text-white font-bold text-sm">FR</span>
</div>
<span className="text-white font-bold text-xl">FairReview</span>
</Link>
<nav className="flex items-center space-x-4">
<Link
href="/"
className="text-gray-300 hover:text-white transition-colors"
>
Home
</Link>
{session ? (
<>
<Link
href="/profile"
className="text-gray-300 hover:text-white transition-colors"
>
Profile
</Link>
<button
onClick={() => signOut()}
className="text-gray-300 hover:text-white transition-colors"
>
Sign Out
</button>
</>
) : (
<Link
href="/login"
className="bg-[#00d4ff] hover:bg-[#00b8e6] text-[#1a1a2e] px-4 py-2 rounded-lg font-medium transition-colors"
>
Sign In
</Link>
)}
</nav>
</div>
</div>
</header>
)
}

View File

@@ -0,0 +1,15 @@
'use client'
import { SessionProvider } from 'next-auth/react'
import { Header } from '@/components/Header'
export function Providers({ children }: { children: React.ReactNode }) {
return (
<SessionProvider>
<div className="min-h-screen bg-[#1a1a2e]">
<Header />
<main>{children}</main>
</div>
</SessionProvider>
)
}

View File

@@ -0,0 +1,119 @@
'use client'
import { useState } from 'react'
import { useSession } from 'next-auth/react'
interface ReviewCardProps {
id: string
username: string
avatarUrl?: string | null
content: string
rating: number
playtimeHours?: number | null
upvotes: number
downvotes: number
userVote?: number | null
createdAt: string
onVote: (reviewId: string, voteType: 1 | -1) => Promise<void>
}
export function ReviewCard({
id,
username,
avatarUrl,
content,
rating,
playtimeHours,
upvotes,
downvotes,
userVote,
createdAt,
onVote
}: ReviewCardProps) {
const { data: session } = useSession()
const [voting, setVoting] = useState(false)
const handleVote = async (voteType: 1 | -1) => {
if (!session) return
setVoting(true)
try {
await onVote(id, voteType)
} finally {
setVoting(false)
}
}
const formatDate = (dateString: string) => {
return new Date(dateString).toLocaleDateString('en-US', {
year: 'numeric',
month: 'short',
day: 'numeric'
})
}
return (
<div className="bg-[#16213e] rounded-xl p-6">
<div className="flex items-start gap-4">
<div className="w-12 h-12 rounded-full bg-[#1a1a2e] flex items-center justify-center overflow-hidden">
{avatarUrl ? (
<img src={avatarUrl} alt={username} className="w-full h-full object-cover" />
) : (
<span className="text-2xl">👤</span>
)}
</div>
<div className="flex-1">
<div className="flex items-center gap-3 mb-2">
<span className="text-white font-medium">{username}</span>
<span className="text-[#00d4ff] font-bold">{rating}/10</span>
{playtimeHours !== null && playtimeHours !== undefined && (
<span className="text-gray-400 text-sm">{playtimeHours}h played</span>
)}
</div>
<p className="text-gray-300 mb-4">{content}</p>
<div className="flex items-center justify-between">
<span className="text-gray-500 text-sm">{formatDate(createdAt)}</span>
{session && (
<div className="flex items-center gap-2">
<button
onClick={() => handleVote(1)}
disabled={voting}
className={`flex items-center gap-1 px-3 py-1 rounded-lg transition-colors ${
userVote === 1
? 'bg-green-600 text-white'
: 'bg-[#1a1a2e] text-gray-400 hover:text-green-400'
}`}
>
<span></span>
<span>{upvotes}</span>
</button>
<button
onClick={() => handleVote(-1)}
disabled={voting}
className={`flex items-center gap-1 px-3 py-1 rounded-lg transition-colors ${
userVote === -1
? 'bg-red-600 text-white'
: 'bg-[#1a1a2e] text-gray-400 hover:text-red-400'
}`}
>
<span></span>
<span>{downvotes}</span>
</button>
</div>
)}
{!session && (
<span className="text-gray-500 text-sm">
Sign in to vote
</span>
)}
</div>
</div>
</div>
</div>
)
}

98
src/lib/auth.ts Normal file
View File

@@ -0,0 +1,98 @@
import NextAuth from 'next-auth'
import Credentials from 'next-auth/providers/credentials'
import Steam from 'next-auth/providers/steam'
import { compare } from 'bcryptjs'
import { prisma } from './db'
export const { handlers, signIn, signOut, auth } = NextAuth({
providers: [
Steam({
clientId: process.env.STEAM_CLIENT_ID,
clientSecret: process.env.STEAM_CLIENT_SECRET,
allowDangerousEmailAccountLinking: true
}),
Credentials({
name: 'credentials',
credentials: {
email: { label: 'Email', type: 'email' },
password: { label: 'Password', type: 'password' }
},
async authorize(credentials) {
if (!credentials?.email || !credentials?.password) {
return null
}
const user = await prisma.user.findUnique({
where: { email: credentials.email as string }
})
if (!user) {
return null
}
const isValid = await compare(
credentials.password as string,
user.passwordHash
)
if (!isValid) {
return null
}
return {
id: user.id,
email: user.email,
name: user.username,
steamId: user.steamId,
steamPersonaname: user.steamPersonaname,
steamAvatar: user.steamAvatar
}
}
})
],
callbacks: {
async jwt({ token, user }) {
if (user) {
token.id = user.id
token.steamId = user.steamId
token.steamPersonaname = user.steamPersonaname
token.steamAvatar = user.steamAvatar
}
return token
},
async session({ session, token }) {
if (token) {
session.user.id = token.id as string
session.user.steamId = token.steamId as string | null
session.user.steamPersonaname = token.steamPersonaname as string | null
session.user.steamAvatar = token.steamAvatar as string | null
}
return session
}
},
pages: {
signIn: '/login'
},
session: {
strategy: 'jwt'
}
})
declare module 'next-auth' {
interface User {
steamId?: string | null
steamPersonaname?: string | null
steamAvatar?: string | null
}
interface Session {
user: {
id: string
email: string
name: string
steamId?: string | null
steamPersonaname?: string | null
steamAvatar?: string | null
}
}
}

9
src/lib/db.ts Normal file
View File

@@ -0,0 +1,9 @@
import { PrismaClient } from '@prisma/client'
const globalForPrisma = globalThis as unknown as {
prisma: PrismaClient | undefined
}
export const prisma = globalForPrisma.prisma ?? new PrismaClient()
if (process.env.NODE_ENV !== 'production') globalForPrisma.prisma = prisma

171
src/lib/steam.ts Normal file
View File

@@ -0,0 +1,171 @@
const STEAM_API_KEY = process.env.STEAM_API_KEY
const STEAM_API_BASE = 'https://api.steampowered.com'
export interface SteamGame {
app_id: number
name: string
playtime_forever?: number
}
export interface SteamGameDetails {
[appId: string]: {
data: {
name: string
short_description: string
header_image: string
capsule_image: string
background: string
release_date: { date: string }
developers: string[]
publishers: string[]
genres: { description: string }[]
}
}
}
export interface SteamPlayerAchievements {
steamID: string
gameName: string
achievements: {
apiname: string
achieved: number
name: string
}[]
}
export interface SteamPlayerStats {
steamID: string
gameName: string
achievements: { name: string; achieved: number }[]
percentComplete: number
}
export async function searchSteamGames(query: string): Promise<SteamGame[]> {
try {
const response = await fetch(
`${STEAM_API_BASE}/ISteamGames/GetAppList/v0002/?format=json`
)
const data = await response.json()
const apps = data.applist?.apps?.app || []
const filtered = apps
.filter((app: { appid: number; name: string }) =>
app.name.toLowerCase().includes(query.toLowerCase())
)
.slice(0, 20)
return filtered.map((app: { appid: number; name: string }) => ({
app_id: app.appid,
name: app.name
}))
} catch (error) {
console.error('Error searching Steam games:', error)
return []
}
}
export async function getGameDetails(appId: number): Promise<SteamGameDetails[string]['data'] | null> {
try {
const response = await fetch(
`https://store.steampowered.com/api/appdetails?appids=${appId}`
)
const data: SteamGameDetails = await response.json()
if (data[appId]?.success && data[appId]?.data) {
return data[appId].data
}
return null
} catch (error) {
console.error('Error fetching game details:', error)
return null
}
}
export async function getOwnedGames(steamId: string): Promise<SteamGame[]> {
try {
const response = await fetch(
`${STEAM_API_BASE}/IPlayerService/GetOwnedGames/v0001/?key=${STEAM_API_KEY}&steamid=${steamId}&include_appinfo=1&format=json`
)
const data = await response.json()
return data.response?.games || []
} catch (error) {
console.error('Error fetching owned games:', error)
return []
}
}
export async function getPlayerAchievements(
steamId: string,
appId: number
): Promise<SteamPlayerAchievements | null> {
try {
const response = await fetch(
`${STEAM_API_BASE}/ISteamUserStats/GetPlayerAchievements/v0001/?appid=${appId}&key=${STEAM_API_KEY}&steamid=${steamId}`
)
if (!response.ok) return null
const data = await response.json()
if (data.playerstats?.success) {
return data.playerstats
}
return null
} catch (error) {
console.error('Error fetching achievements:', error)
return null
}
}
export async function getPlayerPlaytime(steamId: string, appId: number): Promise<number> {
try {
const ownedGames = await getOwnedGames(steamId)
const game = ownedGames.find((g: SteamGame) => g.app_id === appId)
return game?.playtime_forever ? Math.round(game.playtime_forever / 60) : 0
} catch (error) {
console.error('Error fetching playtime:', error)
return 0
}
}
export async function getPlayerProfile(steamId: string): Promise<{
personaname: string
avatarfull: string
} | null> {
try {
const response = await fetch(
`${STEAM_API_BASE}/ISteamUser/GetPlayerSummaries/v0002/?key=${STEAM_API_KEY}&steamids=${steamId}`
)
const data = await response.json()
const player = data.response?.players?.[0]
if (player) {
return {
personaname: player.personaname,
avatarfull: player.avatarfull
}
}
return null
} catch (error) {
console.error('Error fetching player profile:', error)
return null
}
}
export function getSteamOpenIDUrl(returnTo: string): string {
const params = new URLSearchParams({
'openid.ns': 'http://specs.openid.net/auth/2.0',
'openid.identity': 'http://specs.openid.net/auth/2.0/combine',
'openid.claimed_id': 'http://specs.openid.net/auth/2.0/combine',
'openid.return_to': returnTo,
'openid.realm': returnTo
})
return `https://steamcommunity.com/openid/login?${params.toString()}`
}
export function extractSteamIdFromIdentity(identity: string): string | null {
const match = identity.match(/^https?:\/\/steamcommunity\.com\/openid\/id\/(\d+)$/)
return match ? match[1] : null
}