import bcrypt from "bcryptjs"; import { ObjectId } from "mongoose"; import { IUser, Role, Post, User, FileInfo } from "../models"; import fs from "fs/promises"; export const createUser = async (user: IUser) => { // 비밀번호 암호화 const hash = await bcrypt.hash(user.password, 10); const newFileInfo = await FileInfo.create({}); // 사용자 역할 추가: 기본값은 "user" let userRole = null; if (user.role) { userRole = await Role.findById(user.role); } else { userRole = await Role.findOne({ name: "user" }); } const newUser = new User({ email: user.email, password: hash, role: userRole, isNew: true, fileInfo: newFileInfo._id, }); const retUser = await newUser.save(); return retUser; }; export const findUserByEmail = async ( email: string, includePassword: boolean = false ) => { let user; if (includePassword) { user = await User.findOne({ email }).select("+password"); } else { user = await User.findOne({ email }); } return user; }; export const findUserByPostId = async (postId: string) => { const post = await Post.findOne({ _id: postId }).populate("user"); return post?.user; }; export const getProfile = async (userId: string) => { const profile = await User.findById(userId).populate("fileInfo"); return profile; //이름 수정 }; export const getUsers = async () => { const users = await User.find({}); return users; }; export const isUser = async (email: string) => { const user = await User.findOne({ email }); if (user) { return true; } else { return false; } }; export const isValidUserId = async (userId: string) => { const user = await User.findById(userId); if (user) { return true; } else { return false; } }; export const postPicture = async ( userId: ObjectId, nickname: string, originalfilename?: string | null, newfilename?: string, picturepath?: string ) => { const profile = await User.findById(userId); if (!(profile?.fileInfo === undefined)) { if (originalfilename === null) { await FileInfo.findByIdAndUpdate(profile.fileInfo._id, { nickname: nickname, }); } else if (nickname === "") { const ref = FileInfo.findById(profile.fileInfo._id); console.log(ref); await FileInfo.findByIdAndUpdate(profile.fileInfo._id, { originalfilename: originalfilename, newfilename: newfilename, picturepath: picturepath, }); } else { const ref = await FileInfo.findByIdAndUpdate(profile.fileInfo._id, { originalfilename: originalfilename, newfilename: newfilename, picturepath: picturepath, nickname: nickname, }); } } }; export const deleteUser = async (userId: string) => { const user = await User.findById(userId); if (!(user?.fileInfo === undefined)) { const ref = await FileInfo.findById(user.fileInfo._id); if (!(ref?.newfilename === undefined)) { await fs.unlink("../travel/uploads/" + ref?.newfilename); } await FileInfo.deleteOne({ _id: user.fileInfo._id }); const finish = await User.deleteOne({ _id: userId }); return finish; } };