| 1 | 'use server';
|
|---|
| 2 |
|
|---|
| 3 | import { auth } from '@/auth';
|
|---|
| 4 | import { redirect } from 'next/navigation';
|
|---|
| 5 | import postgres from 'postgres';
|
|---|
| 6 | import bcrypt from 'bcrypt';
|
|---|
| 7 |
|
|---|
| 8 | const sql = postgres(process.env.POSTGRES_URL!, { ssl: 'require' });
|
|---|
| 9 |
|
|---|
| 10 | export async function updateProfile(formData: FormData) {
|
|---|
| 11 | const session = await auth();
|
|---|
| 12 |
|
|---|
| 13 | const userId = Number(session?.user?.id);
|
|---|
| 14 | if (!Number.isInteger(userId)) {
|
|---|
| 15 | throw new Error('Invalid user ID in session');
|
|---|
| 16 | }
|
|---|
| 17 |
|
|---|
| 18 | if (!session?.user?.id) redirect('/login');
|
|---|
| 19 |
|
|---|
| 20 | const name = formData.get('name') as string;
|
|---|
| 21 | const email = formData.get('email') as string;
|
|---|
| 22 |
|
|---|
| 23 | await sql`
|
|---|
| 24 | UPDATE "user"
|
|---|
| 25 | SET user_name = ${name},
|
|---|
| 26 | email = ${email}
|
|---|
| 27 | WHERE user_id = ${userId}
|
|---|
| 28 | `;
|
|---|
| 29 |
|
|---|
| 30 | redirect('/profile');
|
|---|
| 31 | }
|
|---|
| 32 |
|
|---|
| 33 | export async function updatePassword(formData: FormData) {
|
|---|
| 34 | const session = await auth();
|
|---|
| 35 |
|
|---|
| 36 | const userId = Number(session?.user?.id);
|
|---|
| 37 | if (!Number.isInteger(userId)) {
|
|---|
| 38 | throw new Error('Invalid user ID in session');
|
|---|
| 39 | }
|
|---|
| 40 |
|
|---|
| 41 | if (!session?.user?.id) redirect('/login');
|
|---|
| 42 |
|
|---|
| 43 | const currentPassword = formData.get('currentPassword') as string;
|
|---|
| 44 | const newPassword = formData.get('newPassword') as string;
|
|---|
| 45 |
|
|---|
| 46 | const users = await sql`
|
|---|
| 47 | SELECT password
|
|---|
| 48 | FROM "user"
|
|---|
| 49 | WHERE user_id = ${userId}
|
|---|
| 50 | `;
|
|---|
| 51 |
|
|---|
| 52 | const user = users[0];
|
|---|
| 53 | if (!user) redirect('/login');
|
|---|
| 54 |
|
|---|
| 55 | const match = await bcrypt.compare(currentPassword, user.password);
|
|---|
| 56 | if (!match) {
|
|---|
| 57 | throw new Error('Current password is incorrect');
|
|---|
| 58 | }
|
|---|
| 59 |
|
|---|
| 60 | const hashed = await bcrypt.hash(newPassword, 10);
|
|---|
| 61 |
|
|---|
| 62 | await sql`
|
|---|
| 63 | UPDATE "user"
|
|---|
| 64 | SET password = ${hashed}
|
|---|
| 65 | WHERE user_id = ${userId}
|
|---|
| 66 | `;
|
|---|
| 67 |
|
|---|
| 68 | redirect('/profile');
|
|---|
| 69 | }
|
|---|