import db from '@/lib/db/client'; import { verifyPassword } from '@/lib/password'; import { isNil, omit, pick } from 'lodash'; import type { createUserType } from './type'; export const getUserByEmail = async (email: string) => { const user = await db.user.findFirst({ where: { email }, select: { id: true, email: true, username: true, password: true, }, }); if (isNil(user)) return null; return user; }; export const getUserById = async (id: string) => { const user = await db.user.findUnique({ where: { id } }); return user; }; export const getUserByusername = async (username: string) => { try { return await db.user.findFirst({ where: { username } }); } catch (error) { console.log(error); return null; } }; export const createUser = async (data: createUserType) => { const { username, email, password } = data; const user = await db.user.create({ data: { email, password, username, }, }); return pick(user, ['id', 'email', 'name']); }; export const ValidateUser = async (credential: string, password: string) => { const user = await db.user.findFirst({ where: { OR: [{ email: credential }, { username: credential }], }, select: { id: true, email: true, username: true, password: true, }, }); if (isNil(user)) return { success: false, message: '用戶不存在', user: null, }; const ispasswordValid = verifyPassword(password, user.password); if (!ispasswordValid) return { success: false, message: '密碼錯誤', user: omit(user, ['password']), }; return { success: true, message: '登入成功', user: omit(user, ['password']), }; }; export const uniqueEmailValidator = async (email: string) => { if (isNil(email)) return true; const user = await getUserByEmail(email); if (isNil(user)) return true; return false; }; export const uniqueUsernameValidator = async (username: string) => { if (isNil(username)) return true; const user = await getUserByusername(username); if (isNil(user)) return true; return false; };