import bcrypt from "bcryptjs"; import { ObjectId } from "mongoose"; import { IUser, Role, Post, User, Avatar } from "../models"; import fs from "fs/promises"; export const createUser = async (user: IUser) => { // 비밀번호 암호화 const hash = await bcrypt.hash(user.password, 10); const newAvatar = await Avatar.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, avatar: newAvatar, }); 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("avatar"); 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?.avatar === undefined)) { if (originalfilename === null) { await Avatar.findByIdAndUpdate(profile.avatar._id, { nickname: nickname, }); } else if (nickname === "") { await Avatar.findByIdAndUpdate(profile.avatar._id, { originalfilename: originalfilename, newfilename: newfilename, picturepath: picturepath, }); } else { await Avatar.findByIdAndUpdate(profile.avatar._id, { originalfilename: originalfilename, newfilename: newfilename, picturepath: picturepath, nickname: nickname, }); } } }; export const deleteUser = async (userId: ObjectId) => { const user = await User.findById(userId); if (!(user?.avatar === undefined)) { const ref = await Avatar.findById(user.avatar._id); await fs.unlink("../travel/uploads/" + ref?.newfilename); await Avatar.deleteOne({ _id: user.avatar._id }); await User.deleteOne({ _id: userId }); } };