// app/actions/auth.js 'use server' import { queryOne, run } from '../../lib/db'; import bcrypt from 'bcryptjs'; // Register a new user export async function registerUser(formData) { try { const username = formData.get('username'); const password = formData.get('password'); // Check if user already exists const existingUser = await queryOne( 'SELECT * FROM users WHERE username = ?', [username] ); if (existingUser) { return { success: false, error: 'Username already exists' }; } // Hash the password const hashedPassword = await bcrypt.hash(password, 10); // Insert the new user const result = await run( 'INSERT INTO users (username, password, role) VALUES (?, ?, ?)', [username, hashedPassword, 'user'] ); return { success: true, userId: result.lastID }; } catch (error) { console.error('Registration error:', error); return { success: false, error: 'Registration failed: ' + error.message }; } } // Login function (to be used with NextAuth) export async function validateCredentials(username, password) { try { const user = await queryOne( 'SELECT * FROM users WHERE username = ?', [username] ); if (!user) { return null; } // Using bcrypt.compare to properly compare hashed passwords const isValid = await bcrypt.compare(password, user.password); if (!isValid) { return null; } return { id: user.id, username: user.username, role: user.role, teamId: user.team_id }; } catch (error) { console.error('Login error:', error); return null; } } // Join a team export async function joinTeam(userId, teamCode) { try { // Find the team with the given code const team = await queryOne( 'SELECT * FROM teams WHERE code = ?', [teamCode] ); if (!team) { return { success: false, error: 'Invalid team code' }; } // Update the user's team_id await run( 'UPDATE users SET team_id = ? WHERE id = ?', [team.id, userId] ); return { success: true, teamId: team.id }; } catch (error) { console.error('Join team error:', error); return { success: false, error: 'Failed to join team: ' + error.message }; } } // Start/Stop Hunt Timer export async function startHuntTimer(active) { try { // Update the hunt status await run( 'UPDATE hunt_settings SET active = ?', [active ? 1 : 0] ); return { success: true }; } catch (error) { console.error('Hunt timer error:', error); return { success: false, error: 'Failed to update hunt timer: ' + error.message }; } } // Get Hunt Status export async function getHuntStatus() { try { const settings = await queryOne('SELECT active FROM hunt_settings LIMIT 1'); return { active: settings ? Boolean(settings.active) : false }; } catch (error) { console.error('Get hunt status error:', error); throw error; } }