user.db.ts 1.78 KB
Newer Older
Yoon, Daeki's avatar
Yoon, Daeki committed
1
import bcrypt from "bcryptjs";
2
import { IUser, Role, User } from "../models";
3
4

export const createUser = async (user: IUser) => {
Yoon, Daeki's avatar
Yoon, Daeki committed
5
6
  // 비밀번호 암호화
  const hash = await bcrypt.hash(user.password, 10);
7
8
9
10
11
12
13
14
15
16
17
  // 사용자 역할 추가: 기본값은 "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,
18
    avatar: user.avatar,
Jiwon Yoon's avatar
Jiwon Yoon committed
19
    socialType: user.socialType,
20
21
22
23
    isNew: true,
  });
  const retUser = await newUser.save();
  return retUser;
24
25
};

Yoon, Daeki's avatar
Yoon, Daeki committed
26
27
28
29
30
31
32
33
34
35
export const deleteUserById = async (userId: string) => {
  const deletedUser = await User.findByIdAndDelete(userId);
  return deletedUser;
};

export const findUserById = async (id: string) => {
  const user = await User.findById(id);
  return user;
};

36
37
38
39
40
41
42
43
44
45
46
47
48
49
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 getUsers = async () => {
50
51
52
53
  const users = await User.find({}).populate({
    path: "avatar",
    select: "_id name url",
  });
54
55
56
57
58
59
60
61
62
63
64
  return users;
};

export const isUser = async (email: string) => {
  const user = await User.findOne({ email });
  if (user) {
    return true;
  } else {
    return false;
  }
};
65
66
67
68
69
70
71
72
73

export const isValidUserId = async (userId: string) => {
  const user = await User.findById(userId);
  if (user) {
    return true;
  } else {
    return false;
  }
};
Jiwon Yoon's avatar
Jiwon Yoon committed
74
75
76
77
78

export const isSocialType = async (socialType: string, email: string) => {
  const user = await User.findOne({ email, socialType });
  return user;
};