source: app/(app)/profile/actions.ts@ f20977e

nextjs
Last change on this file since f20977e was f20977e, checked in by Vasilaki Tocili <vasilakigorgi@…>, 4 months ago

fix: changing user's name, email and password

  • The NextAuth was using UUID instead of my database Serial integer ID,

so I changed the auth and the definitions to use the Serial ID from the
database to perform correctly the chaning of user's name, email and password

  • Removed redundant unused code from auth.d.ts
  • Updated the actions.ts of profile to use the new stringified integer

ID from the database as a SQL query parameter and also added a early
throwing check for the user ID if it's number or not

  • Property mode set to 100644
File size: 1.7 KB
Line 
1'use server';
2
3import { auth } from '@/auth';
4import { redirect } from 'next/navigation';
5import postgres from 'postgres';
6import bcrypt from 'bcrypt';
7
8const sql = postgres(process.env.POSTGRES_URL!, { ssl: 'require' });
9
10export 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
33export 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}
Note: See TracBrowser for help on using the repository browser.