Guest User

Untitled

a guest
May 1st, 2025
19
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 5.55 KB | None | 0 0
  1. Component relevant part:
  2. 'use client';
  3.  
  4. import { useEffect, useState } from 'react';
  5. import { useSession } from 'next-auth/react';
  6. import Board from '../components/game/Board';
  7. import Chat from '../components/game/Chat';
  8. import Leaderboard from '../components/game/Leaderboard';
  9. import Minimap from '../components/game/Minimap';
  10. import GameLoader from '../components/game/GameLoader';
  11. import GameTips from '../components/game/GameTips';
  12. import CenterKingButton from '../components/game/CenterKingButton';
  13. import Link from 'next/link';
  14. import serviceInitializer from '../lib/services/ServiceInitializer';
  15. import GameSettings from '../components/game/GameSettings';
  16.  
  17. export default function GamePage() {
  18. const [isMobile, setIsMobile] = useState(false);
  19. const [socketParams, setSocketParams] = useState('');
  20. const [isLoading, setIsLoading] = useState(true);
  21. const [showTips, setShowTips] = useState(true);
  22. const [authError, setAuthError] = useState(null);
  23. const [isInitialized, setIsInitialized] = useState(false);
  24. const { data: session, status } = useSession();
  25.  
  26. useEffect(() => {
  27. console.log("component re-mounted", session, status)
  28. const setupConnection = async () => {
  29. if (status === 'loading') return; // Wait until auth state is determined
  30.  
  31. try {
  32. // Create parameters for the socket connection
  33. const params = new URLSearchParams();
  34.  
  35. if (status === 'authenticated' && session?.user) {
  36. // Fetch secure token from the API - this is now the PRIMARY method
  37. try {
  38. const response = await fetch('/api/game/token');
  39.  
  40. if (!response.ok) {
  41. throw new Error(`Failed to get game token: ${response.status}`);
  42. }
  43.  
  44. const data = await response.json();
  45.  
  46. if (!data.token) {
  47. throw new Error('No token returned from server');
  48. }
  49.  
  50. // Use the token as the main authentication method
  51. params.append('token', data.token);
  52.  
  53. // Add username as additional info (not for authentication)
  54. if (session.user.name) {
  55. params.append('username', session.user.name);
  56. }
  57.  
  58. console.log('Successfully obtained authentication token');
  59. } catch (error) {
  60. console.error('Error getting game auth token:', error);
  61. setAuthError('Failed to authenticate with game server. Please try again.');
  62. return;
  63. }
  64. } else {
  65. // For anonymous users, generate a guest ID
  66. const guestId = `guest_${Math.random().toString(36).substring(2, 9)}`;
  67. params.append('guestId', guestId);
  68. params.append('username', `Guest_${Math.random().toString(36).substring(2, 9)}`);
  69. }
  70.  
  71. setSocketParams(`?${params.toString()}`);
  72.  
  73. } catch (error) {
  74. console.error('Failed to set up authentication:', error);
  75. setAuthError('Failed to set up authentication. Please try again later.');
  76. }
  77. };
  78.  
  79. setupConnection();
  80. }, [session, status]);
  81.  
  82.  
  83. // app/api/auth/[...nextauth]/route.js
  84. import NextAuth from 'next-auth';
  85. import bcrypt from 'bcryptjs';
  86. import { connectToDatabase } from '@/app/lib/db/mongoose';
  87. import User from '@/app/lib/models/User';
  88. import CredentialsProvider from "next-auth/providers/credentials";
  89.  
  90. export const authOptions = {
  91. providers: [
  92. CredentialsProvider({
  93. name: 'Credentials',
  94. credentials: {
  95. login: { label: "Email or Username", type: "text" },
  96. password: { label: "Password", type: "password" }
  97. },
  98. async authorize(credentials) {
  99. try {
  100. await connectToDatabase();
  101.  
  102. // Check if login is email or username
  103. const isEmail = credentials.login.includes('@');
  104.  
  105. // Find user by email or username
  106. const user = await User.findOne(
  107. isEmail
  108. ? { email: credentials.login.toLowerCase() }
  109. : { username: credentials.login }
  110. ).select('+password');
  111.  
  112. if (!user) {
  113. throw new Error('Invalid credentials');
  114. }
  115.  
  116. // Check if password matches
  117. const isMatch = await bcrypt.compare(credentials.password, user.password);
  118.  
  119. if (!isMatch) {
  120. throw new Error('Invalid credentials');
  121. }
  122.  
  123. // Update last login time
  124. user.lastLogin = Date.now();
  125. await user.save();
  126.  
  127. return {
  128. id: user._id.toString(),
  129. name: user.username,
  130. email: user.email
  131. };
  132. } catch (error) {
  133. console.error('Auth error:', error);
  134. return null;
  135. }
  136. }
  137. })
  138. ],
  139. callbacks: {
  140. async jwt({ token, user }) {
  141. if (user) {
  142. token.id = user.id;
  143. token.username = user.username;
  144. token.role = user.role || 'user';
  145. }
  146. return token;
  147. },
  148. async session({ session, token }) {
  149. if (token) {
  150. session.user.id = token.id;
  151. session.user.username = token.username;
  152. session.user.role = token.role || 'user';
  153. }
  154. return session;
  155. }
  156. },
  157. pages: {
  158. signIn: '/auth/login',
  159. error: '/auth/login'
  160. },
  161. session: {
  162. strategy: 'jwt',
  163. maxAge: 30 * 24 * 60 * 60, // 30 days,
  164. updateAge: 24 * 60 * 60
  165. },
  166. secret: process.env.NEXTAUTH_SECRET
  167. };
  168.  
  169. const handler = NextAuth(authOptions);
  170.  
  171. export { handler as GET, handler as POST };
Advertisement
Add Comment
Please, Sign In to add comment