ok, implement sqlite

This commit is contained in:
Leon Serfaty G
2025-07-17 11:12:35 +00:00
parent 09e59d46bd
commit 5f38178a60
8 changed files with 391 additions and 45 deletions
+36 -24
View File
@@ -1,39 +1,51 @@
'use server';
import { redirect } from 'next/navigation';
import { cookies } from 'next/headers';
import db from './db';
import type { User } from './types';
const FAKE_USER = {
email: 'admin@example.com',
password: 'password',
name: 'Admin User',
};
export async function signIn(formData: FormData) {
const email = formData.get('email');
const password = formData.get('password');
if (email === FAKE_USER.email && password === FAKE_USER.password) {
const sessionData = {
isLoggedIn: true,
email: FAKE_USER.email,
name: FAKE_USER.name,
};
cookies().set('session', JSON.stringify(sessionData), {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 24 * 7, // One week
path: '/',
});
redirect('/admin');
if (typeof email !== 'string' || typeof password !== 'string') {
// Handle case where form data is missing or not strings
redirect('/login?error=Invalid%20input');
return;
}
// In a real app, you'd handle the error case, e.g., redirect to login with an error message.
// For simplicity, we'll just redirect back.
redirect('/login');
try {
const stmt = db.prepare('SELECT * FROM users WHERE email = ?');
const user = stmt.get(email) as User | undefined;
// In a real app, you would use a secure password hashing library like bcrypt
// For this example, we'll compare plain text passwords.
if (user && user.password === password) {
const sessionData = {
isLoggedIn: true,
userId: user.id,
email: user.email,
name: user.name,
};
cookies().set('session', JSON.stringify(sessionData), {
httpOnly: true,
secure: process.env.NODE_ENV === 'production',
maxAge: 60 * 60 * 24 * 7, // One week
path: '/',
});
redirect('/admin');
} else {
// Failed login
redirect('/login?error=Invalid%20credentials');
}
} catch (error) {
console.error('Failed to sign in:', error);
redirect('/login?error=Database%20error');
}
}
export async function signOut() {
+16
View File
@@ -0,0 +1,16 @@
import Database from 'better-sqlite3';
// Use a file-based database in development
const db = new Database('local.db');
// Create the users table if it doesn't exist
db.exec(`
CREATE TABLE IF NOT EXISTS users (
id INTEGER PRIMARY KEY AUTOINCREMENT,
email TEXT UNIQUE NOT NULL,
password TEXT NOT NULL,
name TEXT NOT NULL
)
`);
export default db;
+7
View File
@@ -0,0 +1,7 @@
export interface User {
id: number;
email: string;
password?: string; // Should be handled securely, not sent to client
name: string;
}