source: app/(auth)/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
RevLine 
[e1175d1]1'use server'
2
3import { z } from 'zod';
[69d38f6]4import { sql } from '@/app/lib/db';
[25b259a]5import { signIn } from '@/auth';
[bd7f7a7]6import bcrypt from "bcryptjs";
[25b259a]7import { AuthError } from 'next-auth';
[e1175d1]8
[25b259a]9export async function authenticate(
10 prevState: string | undefined,
11 formData: FormData,
12) {
13 try {
[2e0a138]14 const redirectTo =
[f9fef87]15 (formData.get('redirectTo') as string)?.startsWith('/')
16 ? (formData.get('redirectTo') as string)
[794232d]17 : '/dashboard';
[2e0a138]18
19 await signIn('credentials', {
20 ...Object.fromEntries(formData),
21 redirectTo,
22 });
[25b259a]23 } catch (error) {
24 if (error instanceof AuthError) {
25 switch (error.type) {
26 case 'CredentialsSignin':
[2e0a138]27 return 'Invalid email or password.';
[25b259a]28 default:
[2e0a138]29 return 'Something went wrong. Please try again.';
[25b259a]30 }
31 }
32 throw error;
33 }
34}
35
[bd7f7a7]36export async function register(
37 prevState: string | undefined,
38 formData: FormData,
39) {
40 const schema = z.object({
[2253a52]41 user_name: z.string().min(1),
[bd7f7a7]42 email: z.string().email(),
43 password: z.string().min(6),
44 redirectTo: z.string().optional(),
45 });
46
47 const parsed = schema.safeParse({
[2253a52]48 user_name: formData.get('user_name'),
[bd7f7a7]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
[2253a52]58 const { user_name, email, password, redirectTo } = parsed.data;
[bd7f7a7]59
[9cae1de]60 // sanitize redirect
61 const safeRedirect =
[794232d]62 redirectTo?.startsWith('/') ? redirectTo : '/dashboard';
[9cae1de]63
[bd7f7a7]64 const existing =
[2d3c02f]65 await sql`SELECT user_id FROM "user" WHERE email=${email}`;
[bd7f7a7]66
67 if (existing.length > 0) {
68 return 'User already exists.';
69 }
70
71 const hashed = await bcrypt.hash(password, 10);
72
[9cae1de]73 try {
74 await sql`
[2d3c02f]75 INSERT INTO "user" (user_name, email, password)
[2253a52]76 VALUES (${user_name}, ${email}, ${hashed})
[9cae1de]77 `;
78 } catch {
79 return 'Failed to create user.';
80 }
[bd7f7a7]81
[9cae1de]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 }
[f3de0a3]94}
Note: See TracBrowser for help on using the repository browser.