source: app/(auth)/actions.ts@ f023e5d

nextjs
Last change on this file since f023e5d 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 { z } from 'zod';
4import { sql } from '@/app/lib/db';
5import { signIn } from '@/auth';
6import bcrypt from "bcryptjs";
7import { AuthError } from 'next-auth';
8
9export async function authenticate(
10 prevState: string | undefined,
11 formData: FormData,
12) {
13 try {
14 const redirectTo =
15 (formData.get('redirectTo') as string)?.startsWith('/')
16 ? (formData.get('redirectTo') as string)
17 : '/dashboard';
18
19 await signIn('credentials', {
20 ...Object.fromEntries(formData),
21 redirectTo,
22 });
23 } catch (error) {
24 if (error instanceof AuthError) {
25 switch (error.type) {
26 case 'CredentialsSignin':
27 return 'Invalid email or password.';
28 default:
29 return 'Something went wrong. Please try again.';
30 }
31 }
32 throw error;
33 }
34}
35
36export async function register(
37 prevState: string | undefined,
38 formData: FormData,
39) {
40 const schema = z.object({
41 user_name: z.string().min(1),
42 email: z.string().email(),
43 password: z.string().min(6),
44 redirectTo: z.string().optional(),
45 });
46
47 const parsed = schema.safeParse({
48 user_name: formData.get('user_name'),
49 email: formData.get('email'),
50 password: formData.get('password'),
51 redirectTo: formData.get('redirectTo'),
52 });
53
54 if (!parsed.success) {
55 return 'Invalid form data.';
56 }
57
58 const { user_name, email, password, redirectTo } = parsed.data;
59
60 // sanitize redirect
61 const safeRedirect =
62 redirectTo?.startsWith('/') ? redirectTo : '/dashboard';
63
64 const existing =
65 await sql`SELECT user_id FROM "user" WHERE email=${email}`;
66
67 if (existing.length > 0) {
68 return 'User already exists.';
69 }
70
71 const hashed = await bcrypt.hash(password, 10);
72
73 try {
74 await sql`
75 INSERT INTO "user" (user_name, email, password)
76 VALUES (${user_name}, ${email}, ${hashed})
77 `;
78 } catch {
79 return 'Failed to create user.';
80 }
81
82 try {
83 await signIn('credentials', {
84 email,
85 password,
86 redirectTo: safeRedirect,
87 });
88 } catch (error) {
89 if (error instanceof AuthError) {
90 return 'Account created, but auto-login failed. Please log in.';
91 }
92 throw error;
93 }
94}
Note: See TracBrowser for help on using the repository browser.