chatbot-template/app/login/actions.ts

72 lines
1.5 KiB
TypeScript
Raw Normal View History

2024-03-14 20:00:52 +03:00
'use server'
import { signIn } from '@/auth'
2024-03-19 04:37:30 +03:00
import { User } from '@/lib/types'
2024-03-14 20:00:52 +03:00
import { AuthError } from 'next-auth'
import { z } from 'zod'
2024-03-19 04:37:30 +03:00
import { kv } from '@vercel/kv'
import { ResultCode } from '@/lib/utils'
export async function getUser(email: string) {
const user = await kv.hgetall<User>(`user:${email}`)
return user
}
interface Result {
type: string
resultCode: ResultCode
}
2024-03-14 20:00:52 +03:00
export async function authenticate(
2024-03-19 04:37:30 +03:00
_prevState: Result | undefined,
2024-03-14 20:00:52 +03:00
formData: FormData
2024-03-19 04:37:30 +03:00
): Promise<Result | undefined> {
2024-03-14 20:00:52 +03:00
try {
const email = formData.get('email')
const password = formData.get('password')
const parsedCredentials = z
.object({
email: z.string().email(),
password: z.string().min(6)
})
.safeParse({
email,
password
})
if (parsedCredentials.success) {
await signIn('credentials', {
email,
password,
2024-03-19 04:37:30 +03:00
redirect: false
2024-03-14 20:00:52 +03:00
})
2024-03-19 04:37:30 +03:00
return {
type: 'success',
resultCode: ResultCode.UserLoggedIn
}
2024-03-14 20:00:52 +03:00
} else {
2024-03-19 04:37:30 +03:00
return {
type: 'error',
resultCode: ResultCode.InvalidCredentials
}
2024-03-14 20:00:52 +03:00
}
} catch (error) {
if (error instanceof AuthError) {
switch (error.type) {
case 'CredentialsSignin':
2024-03-19 04:37:30 +03:00
return {
type: 'error',
resultCode: ResultCode.InvalidCredentials
}
2024-03-14 20:00:52 +03:00
default:
return {
type: 'error',
2024-03-19 04:37:30 +03:00
resultCode: ResultCode.UnknownError
2024-03-14 20:00:52 +03:00
}
}
}
}
}