mirror of
https://github.com/mudabbir-ahmad/peworkshop.git
synced 2026-10-08 03:50:21 +00:00
76 lines
1.9 KiB
JavaScript
76 lines
1.9 KiB
JavaScript
// 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;
|
|
}
|
|
}
|
|
|
|
// Other functions remain the same...
|