on admin dashboard header create a user icon where i can manage admin us
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
|
||||
'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' };
|
||||
}
|
||||
|
||||
const validated = UserUpdateSchema.safeParse(data);
|
||||
if (!validated.success) {
|
||||
return { success: false, error: 'Invalid data' };
|
||||
}
|
||||
|
||||
const { name, email, password } = validated.data;
|
||||
|
||||
try {
|
||||
if (password) {
|
||||
// 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.' };
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user