source: app/(auth)/actions.ts@ 23a1424

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

refactor: move auth actions to correct place

  • Move /lib/actions.ts to /(auth)/actions.ts since all of the content

of actions.ts was for authenticating, and since I have actions colocated
with the stuff they are affecting it was only right to make this move

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