Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Component relevant part:
- 'use client';
- import { useEffect, useState } from 'react';
- import { useSession } from 'next-auth/react';
- import Board from '../components/game/Board';
- import Chat from '../components/game/Chat';
- import Leaderboard from '../components/game/Leaderboard';
- import Minimap from '../components/game/Minimap';
- import GameLoader from '../components/game/GameLoader';
- import GameTips from '../components/game/GameTips';
- import CenterKingButton from '../components/game/CenterKingButton';
- import Link from 'next/link';
- import serviceInitializer from '../lib/services/ServiceInitializer';
- import GameSettings from '../components/game/GameSettings';
- export default function GamePage() {
- const [isMobile, setIsMobile] = useState(false);
- const [socketParams, setSocketParams] = useState('');
- const [isLoading, setIsLoading] = useState(true);
- const [showTips, setShowTips] = useState(true);
- const [authError, setAuthError] = useState(null);
- const [isInitialized, setIsInitialized] = useState(false);
- const { data: session, status } = useSession();
- useEffect(() => {
- console.log("component re-mounted", session, status)
- const setupConnection = async () => {
- if (status === 'loading') return; // Wait until auth state is determined
- try {
- // Create parameters for the socket connection
- const params = new URLSearchParams();
- if (status === 'authenticated' && session?.user) {
- // Fetch secure token from the API - this is now the PRIMARY method
- try {
- const response = await fetch('/api/game/token');
- if (!response.ok) {
- throw new Error(`Failed to get game token: ${response.status}`);
- }
- const data = await response.json();
- if (!data.token) {
- throw new Error('No token returned from server');
- }
- // Use the token as the main authentication method
- params.append('token', data.token);
- // Add username as additional info (not for authentication)
- if (session.user.name) {
- params.append('username', session.user.name);
- }
- console.log('Successfully obtained authentication token');
- } catch (error) {
- console.error('Error getting game auth token:', error);
- setAuthError('Failed to authenticate with game server. Please try again.');
- return;
- }
- } else {
- // For anonymous users, generate a guest ID
- const guestId = `guest_${Math.random().toString(36).substring(2, 9)}`;
- params.append('guestId', guestId);
- params.append('username', `Guest_${Math.random().toString(36).substring(2, 9)}`);
- }
- setSocketParams(`?${params.toString()}`);
- } catch (error) {
- console.error('Failed to set up authentication:', error);
- setAuthError('Failed to set up authentication. Please try again later.');
- }
- };
- setupConnection();
- }, [session, status]);
- // app/api/auth/[...nextauth]/route.js
- import NextAuth from 'next-auth';
- import bcrypt from 'bcryptjs';
- import { connectToDatabase } from '@/app/lib/db/mongoose';
- import User from '@/app/lib/models/User';
- import CredentialsProvider from "next-auth/providers/credentials";
- export const authOptions = {
- providers: [
- CredentialsProvider({
- name: 'Credentials',
- credentials: {
- login: { label: "Email or Username", type: "text" },
- password: { label: "Password", type: "password" }
- },
- async authorize(credentials) {
- try {
- await connectToDatabase();
- // Check if login is email or username
- const isEmail = credentials.login.includes('@');
- // Find user by email or username
- const user = await User.findOne(
- isEmail
- ? { email: credentials.login.toLowerCase() }
- : { username: credentials.login }
- ).select('+password');
- if (!user) {
- throw new Error('Invalid credentials');
- }
- // Check if password matches
- const isMatch = await bcrypt.compare(credentials.password, user.password);
- if (!isMatch) {
- throw new Error('Invalid credentials');
- }
- // Update last login time
- user.lastLogin = Date.now();
- await user.save();
- return {
- id: user._id.toString(),
- name: user.username,
- email: user.email
- };
- } catch (error) {
- console.error('Auth error:', error);
- return null;
- }
- }
- })
- ],
- callbacks: {
- async jwt({ token, user }) {
- if (user) {
- token.id = user.id;
- token.username = user.username;
- token.role = user.role || 'user';
- }
- return token;
- },
- async session({ session, token }) {
- if (token) {
- session.user.id = token.id;
- session.user.username = token.username;
- session.user.role = token.role || 'user';
- }
- return session;
- }
- },
- pages: {
- signIn: '/auth/login',
- error: '/auth/login'
- },
- session: {
- strategy: 'jwt',
- maxAge: 30 * 24 * 60 * 60, // 30 days,
- updateAge: 24 * 60 * 60
- },
- secret: process.env.NEXTAUTH_SECRET
- };
- const handler = NextAuth(authOptions);
- export { handler as GET, handler as POST };
Advertisement
Add Comment
Please, Sign In to add comment