user.db.ts 4.67 KB
Newer Older
1
import bcrypt from "bcryptjs";
2
3
import { HydratedDocument, ObjectId } from "mongoose";
import { IUser, Role, Post, User, FileInfo, IRole, IFileInfo } from "../models";
Kim, MinGyu's avatar
Kim, MinGyu committed
4
import fs from "fs/promises";
5
import formidable from "formidable";
Yoon, Daeki's avatar
Yoon, Daeki committed
6
7

export const createUser = async (user: IUser) => {
8
9
  // 비밀번호 암호화
  const hash = await bcrypt.hash(user.password, 10);
Yoon, Daeki's avatar
Yoon, Daeki committed
10
  // const newFileInfo = await FileInfo.create({});
Yoon, Daeki's avatar
Yoon, Daeki committed
11
12
13
14
15
16
17
18
  // 사용자 역할 추가: 기본값은 "user"
  let userRole = null;
  if (user.role) {
    userRole = await Role.findById(user.role);
  } else {
    userRole = await Role.findOne({ name: "user" });
  }
  const newUser = new User({
Lee Soobeom's avatar
Lee Soobeom committed
19
    email: user.email,
20
    name: user.name,
Lee Soobeom's avatar
Lee Soobeom committed
21
    password: hash,
Yoon, Daeki's avatar
Yoon, Daeki committed
22
23
    role: userRole,
    isNew: true,
Yoon, Daeki's avatar
Yoon, Daeki committed
24
    // fileInfo: newFileInfo._id,
Lee Soobeom's avatar
Lee Soobeom committed
25
  });
Yoon, Daeki's avatar
Yoon, Daeki committed
26
27
  const retUser = await newUser.save();
  return retUser;
Yoon, Daeki's avatar
Yoon, Daeki committed
28
29
30
31
32
33
34
35
};

export const findUserByEmail = async (
  email: string,
  includePassword: boolean = false
) => {
  let user;
  if (includePassword) {
Yoon, Daeki's avatar
Yoon, Daeki committed
36
37
38
    user = await User.findOne({ email })
      .select("+password")
      .populate<{ role: IRole }>("role");
Yoon, Daeki's avatar
Yoon, Daeki committed
39
  } else {
Yoon, Daeki's avatar
Yoon, Daeki committed
40
    user = await User.findOne({ email }).populate<{ role: IRole }>("role");
Yoon, Daeki's avatar
Yoon, Daeki committed
41
42
43
44
  }
  return user;
};

Lee Soobeom's avatar
Lee Soobeom committed
45
46
47
48
export const findUserByPostId = async (postId: string) => {
  const post = await Post.findOne({ _id: postId }).populate("user");
  return post?.user;
};
Kim, MinGyu's avatar
Kim, MinGyu committed
49

Yoon, Daeki's avatar
Yoon, Daeki committed
50
export const getProfile = async (userId: string) => {
51
  const profile = await User.findById(userId).populate("avatar");
Yoon, Daeki's avatar
Yoon, Daeki committed
52
53
  return profile; //이름 수정
};
Lee Soobeom's avatar
Lee Soobeom committed
54

Yoon, Daeki's avatar
Yoon, Daeki committed
55
56
57
58
59
60
61
62
63
64
65
66
67
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;
  }
};
Kim, MinGyu's avatar
Kim, MinGyu committed
68

Yoon, Daeki's avatar
Yoon, Daeki committed
69
70
71
72
73
74
75
export const isValidUserId = async (userId: string) => {
  const user = await User.findById(userId);
  if (user) {
    return true;
  } else {
    return false;
  }
76
77
};

78
export const updateProfile = async (
79
  userId: ObjectId,
80
81
  name: string,
  avatar: formidable.File
82
) => {
83
84
85
86
87
88
89
90
91
92
93
94
95
96
  const user = await User.findById(userId).populate<{ avatar: IFileInfo }>(
    "avatar"
  );
  console.log("user in update profile", user, avatar);
  if (!user) {
    throw new Error("사용자가 존재하지 않습니다");
  }
  if (avatar) {
    if (!user.avatar) {
      // 사용자의 아바타가 존재하지 않으면 생성
      const file = await FileInfo.create({
        originalfilename: avatar.originalFilename,
        newfilename: avatar.newFilename,
        picturepath: avatar.filepath,
Kim, MinGyu's avatar
Kim, MinGyu committed
97
      });
98
      user.avatar = file;
Kim, MinGyu's avatar
Kim, MinGyu committed
99
    } else {
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
      // 아바타에 같은 원래파일이름이 존재하는지 확인
      // 같으면 파일 수정하지 않고 통과
      if (
        avatar.originalFilename &&
        user.avatar.originalfilename !== avatar.originalFilename
      ) {
        // 같지 않으면 기존의 파일을 디스크에서 삭제한 후
        try {
          await fs.unlink(user.avatar.picturepath);
        } catch (error) {
          console.log("error", error);
        }
        const userAvatar = user.avatar as HydratedDocument<IFileInfo>;
        // 기존 아바타 fileinfo의 파일이름과 경로 변경 설정
        userAvatar.originalfilename = avatar.originalFilename;
        userAvatar.newfilename = avatar.newFilename;
        userAvatar.picturepath = avatar.filepath;
        await userAvatar.save();
      }
Kim, MinGyu's avatar
Kim, MinGyu committed
119
    }
Kim, MinGyu's avatar
Kim, MinGyu committed
120
  }
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
  user.name = name;
  await user.save();
  console.log("user updated", user);
  return user;

  // if (!(profile?.avatar === undefined)) {
  //   if (originalfilename === null) {
  //     await FileInfo.findByIdAndUpdate(profile.avatar._id, {
  //       nickname: nickname,
  //     });
  //   } else if (nickname === "") {
  //     const ref = FileInfo.findById(profile.avatar._id);
  //     console.log(ref);

  //     await FileInfo.findByIdAndUpdate(profile.avatar._id, {
  //       originalfilename: originalfilename,
  //       newfilename: newfilename,
  //       picturepath: picturepath,
  //     });
  //   } else {
  //     const ref = await FileInfo.findByIdAndUpdate(profile.avatar._id, {
  //       originalfilename: originalfilename,
  //       newfilename: newfilename,
  //       picturepath: picturepath,
  //       nickname: nickname,
  //     });
  //   }
  // }
149
};
Kim, MinGyu's avatar
Kim, MinGyu committed
150

Kim, MinGyu's avatar
Kim, MinGyu committed
151
export const deleteUser = async (userId: string) => {
Kim, MinGyu's avatar
Kim, MinGyu committed
152
  const user = await User.findById(userId);
153
154
  if (!(user?.avatar === undefined)) {
    const ref = await FileInfo.findById(user.avatar._id);
Kim, MinGyu's avatar
Kim, MinGyu committed
155
156
157
    if (!(ref?.newfilename === undefined)) {
      await fs.unlink("../travel/uploads/" + ref?.newfilename);
    }
158
    await FileInfo.deleteOne({ _id: user.avatar._id });
Kim, MinGyu's avatar
Kim, MinGyu committed
159
160
    const finish = await User.deleteOne({ _id: userId });
    return finish;
Kim, MinGyu's avatar
Kim, MinGyu committed
161
162
  }
};