112 lines
2.8 KiB
TypeScript
112 lines
2.8 KiB
TypeScript
|
import db from '@/libs/db/prismaClient';
|
||
|
import { hashPassword, verifyPassword } from '@/libs/password';
|
||
|
import { isNil, omit } 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: hashPassword(password),
|
||
|
username,
|
||
|
},
|
||
|
});
|
||
|
return omit(user, ['password']);
|
||
|
};
|
||
|
|
||
|
export const ValidateUser = async (
|
||
|
credential: string,
|
||
|
password: string,
|
||
|
): Promise<
|
||
|
| { success: false; message: string; user: null }
|
||
|
| {
|
||
|
success: true;
|
||
|
message: string;
|
||
|
user: {
|
||
|
id: string;
|
||
|
email: string;
|
||
|
username: string;
|
||
|
role: 'ADMIN' | 'USER';
|
||
|
createdAt: Date;
|
||
|
updatedAt: Date;
|
||
|
};
|
||
|
}
|
||
|
> => {
|
||
|
const user = await db.user.findFirst({
|
||
|
where: {
|
||
|
OR: [{ email: credential }, { username: credential }],
|
||
|
},
|
||
|
select: {
|
||
|
id: true,
|
||
|
email: true,
|
||
|
username: true,
|
||
|
role: true,
|
||
|
password: true,
|
||
|
createdAt: true,
|
||
|
updatedAt: true,
|
||
|
},
|
||
|
});
|
||
|
if (isNil(user))
|
||
|
return {
|
||
|
success: false,
|
||
|
message: '用戶不存在',
|
||
|
user: null,
|
||
|
};
|
||
|
|
||
|
const ispasswordValid = verifyPassword(password, user.password);
|
||
|
if (!ispasswordValid)
|
||
|
return {
|
||
|
success: false,
|
||
|
message: '密碼錯誤',
|
||
|
user: null,
|
||
|
};
|
||
|
|
||
|
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;
|
||
|
};
|