source: app/(app)/profile/actions.ts@ 95953b2

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

refactor: reuse lib/db.ts's sql object across files

  • Instead of creating a new postgres.js object and storing it in the

sql file across all of the files, reuse the object created in the
lib/db.ts

  • Property mode set to 100644
File size: 2.4 KB
Line 
1'use server';
2
3import { auth } from '@/auth';
4import { redirect } from 'next/navigation';
5import { sql } from '@/app/lib/db';
6import bcrypt from 'bcrypt';
7
8type ActionResult = string | undefined; // string = error message, undefined = success
9
10export async function updateProfile(
11 _prevState: ActionResult,
12 formData: FormData
13): Promise<ActionResult> {
14 const session = await auth();
15 if (!session?.user?.id) {
16 redirect('/login');
17 }
18
19 const userId = Number(session.user.id);
20 if (!Number.isInteger(userId)) {
21 return 'Invalid session. Please log in again.';
22 }
23 const name = String(formData.get('name') ?? '').trim();
24 const email = String(formData.get('email') ?? '').trim().toLowerCase();
25
26 if (!name) {
27 return 'Name is required.';
28 }
29 if (!email || !email.includes('@')) {
30 return 'Please enter a valid email.';
31 }
32
33 // Email already exists check
34 const existing = await sql`
35 SELECT user_id FROM "user"
36 WHERE email = ${email} AND user_id != ${userId}
37 `;
38 if (existing.length > 0) {
39 return 'Email already exists.';
40 }
41
42 await sql`
43 UPDATE "user"
44 SET user_name = ${name},
45 email = ${email}
46 WHERE user_id = ${userId}
47 `;
48
49 redirect('/profile');
50}
51
52export async function updatePassword(
53 _prevState: ActionResult,
54 formData: FormData
55): Promise<ActionResult> {
56 const session = await auth();
57 if (!session?.user?.id) {
58 redirect('/login');
59 }
60
61 const userId = Number(session.user.id);
62 if (!Number.isInteger(userId)) {
63 return 'Invalid session. Please log in again.';
64 }
65 const currentPassword = String(formData.get('currentPassword') ?? '');
66 const newPassword = String(formData.get('newPassword') ?? '');
67
68 if (newPassword.length < 6) {
69 return 'New password must be at least 6 characters.';
70 }
71
72 const users = await sql`
73 SELECT password
74 FROM "user"
75 WHERE user_id = ${userId}
76 `;
77 const user = users[0];
78 if (!user) {
79 return 'User not found. Please log in again.';
80 }
81
82 const match = await bcrypt.compare(currentPassword, user.password);
83 if (!match) {
84 return 'Current password is incorrect.';
85 }
86
87 const hashed = await bcrypt.hash(newPassword, 10);
88
89 await sql`
90 UPDATE "user"
91 SET password = ${hashed}
92 WHERE user_id = ${userId}
93 `;
94
95 redirect('/profile');
96}
Note: See TracBrowser for help on using the repository browser.