Files
estimation-flow/src/lib/actions/user.ts
T

67 lines
2.0 KiB
TypeScript
Raw Normal View History

'use server';
import db from '@/lib/db';
import { User } from '@/lib/types';
import { z } from 'zod';
import { getSession } from '../auth';
const UserUpdateSchema = z.object({
name: z.string().min(1, 'Name is required'),
email: z.string().email('Invalid email address'),
password: z.string().optional(),
});
export async function getUser(): Promise<User | null> {
const session = await getSession();
if (!session?.userId) {
return null;
}
try {
const stmt = db.prepare('SELECT id, name, email FROM users WHERE id = ?');
const user = stmt.get(session.userId) as User | undefined;
return user ?? null;
} catch (error) {
console.error('Failed to get user:', error);
return null;
}
}
export async function updateUser(
data: z.infer<typeof UserUpdateSchema>
): Promise<{ success: boolean; error?: string }> {
const session = await getSession();
if (!session?.userId) {
return { success: false, error: 'Not authenticated. Please log in again.' };
}
const validated = UserUpdateSchema.safeParse(data);
if (!validated.success) {
const errors = validated.error.flatten().fieldErrors;
const firstError = Object.values(errors)[0]?.[0] ?? 'Invalid data provided.';
return { success: false, error: firstError };
}
const { name, email, password } = validated.data;
try {
if (password && password.trim().length > 0) {
// In a real application, hash the password
const stmt = db.prepare(
'UPDATE users SET name = ?, email = ?, password = ? WHERE id = ?'
);
stmt.run(name, email, password, session.userId);
} else {
const stmt = db.prepare('UPDATE users SET name = ?, email = ? WHERE id = ?');
stmt.run(name, email, session.userId);
}
return { success: true };
} catch (error: any) {
console.error('Failed to update user:', error);
if (error.code === 'SQLITE_CONSTRAINT_UNIQUE') {
return { success: false, error: 'Email already in use.' };
}
return { success: false, error: 'Failed to update user profile due to a server error.' };
}
}