Commit 417c92f8 authored by Yoon, Daeki's avatar Yoon, Daeki 😅
Browse files

role 기능 추가

parent fd35bfb8
...@@ -14,12 +14,16 @@ const roles = [ ...@@ -14,12 +14,16 @@ const roles = [
connect(mongoUri) connect(mongoUri)
.then(async (mongoose) => { .then(async (mongoose) => {
const adminRole = await Role.findOne({ name: "admin" }); const adminRole = await Role.findOne({ name: "admin" });
if (!adminRole) {
throw new Error("admin role이 없습니다. 먼저 role 테이블을 만드세요.");
}
await userDb.createUser({ await userDb.createUser({
email: "admin@example.com", email: "admin@example.com",
name: "admin", name: "admin",
role: adminRole?._id, role: adminRole?._id,
password: "asdfasdf", password: "asdfasdf",
}); });
console.log("admin 계정이 만들어졌습니다.");
await mongoose.disconnect(); await mongoose.disconnect();
}) })
.catch((error) => console.log("롤 초기 생성 에러", error)); .catch((error) => console.log("롤 초기 생성 에러", error));
...@@ -4,12 +4,41 @@ import jwt, { JwtPayload } from "jsonwebtoken"; ...@@ -4,12 +4,41 @@ import jwt, { JwtPayload } from "jsonwebtoken";
import isLength from "validator/lib/isLength"; import isLength from "validator/lib/isLength";
import isEmail from "validator/lib/isEmail"; import isEmail from "validator/lib/isEmail";
import { asyncWrap } from "../helpers"; import { asyncWrap } from "../helpers";
import { userDb } from "../db"; import { roleDb, userDb } from "../db";
import { jwtCofig, envConfig, cookieConfig } from "../config"; import { jwtCofig, envConfig, cookieConfig } from "../config";
export interface TypedRequestAuth<T> extends Request { export interface TypedRequestAuth<T> extends Request {
auth: T; auth: T;
} }
/**
* 지정된 역할 이상으로 권한이 있는지를 판단하는 미들웨어를 반환합니다.
* @param roleName 역할 문자열
* @returns 미들웨어
*/
export const hasRole = (roleName: string) => {
// roleName 이상으로 허락하는 것
return async (reqExp: Request, res: Response, next: NextFunction) => {
const req = reqExp as TypedRequestAuth<{ userId: string }>;
if (!req.auth) {
return res.status(401).send("로그인이 필요합니다");
}
const { userId } = req.auth;
if (!(await userDb.isValidUserId(userId))) {
return res.status(401).send("유효한 사용자가 아닙니다");
}
const userRole = await roleDb.findRoleByUserId(userId);
const maxRole = await roleDb.findRoleByName(roleName);
if (maxRole && Number(maxRole.priority) >= Number(userRole.priority)) {
return next();
} else {
return res.status(401).send("이용 권한이 없습니다");
}
};
};
export const login = asyncWrap(async (req, res) => { export const login = asyncWrap(async (req, res) => {
const { email, password } = req.body; const { email, password } = req.body;
console.log(`email: ${email}, password: ${password}`); console.log(`email: ${email}, password: ${password}`);
......
export * as userCtrl from "./user.controller";
export * as authCtrl from "./auth.controller"; export * as authCtrl from "./auth.controller";
export * as postCtrl from "./post.controller"; export * as postCtrl from "./post.controller";
export * as roleCtrl from "./role.controller";
export * as userCtrl from "./user.controller";
import { roleDb } from "../db";
import { asyncWrap } from "../helpers";
export const getRoles = asyncWrap(async (req, res, next) => {
const roles = await roleDb.getAllRoles();
return res.json(roles);
});
export * as userDb from "./user.db"; export * as roleDb from "./role.db";
export * as postDb from "./post.db"; export * as postDb from "./post.db";
export * as userDb from "./user.db";
import { Role, User } from "../models";
export const findRoleById = async (roleId: string) => {
const role = await Role.findById(roleId);
return role;
};
export const findRoleByName = async (roleName: string) => {
const role = await Role.findOne({ name: roleName });
return role;
};
export const findRoleByUserId = async (userId: string) => {
const user = await User.findById(userId).populate("role");
const role = user?.get("role");
return role;
};
export const getAllRoles = async () => {
const roles = await Role.find({});
return roles;
};
import bcrypt from "bcryptjs"; import bcrypt from "bcryptjs";
import { IUser, User } from "../models"; import { IUser, Role, User } from "../models";
export const createUser = async (user: IUser) => { export const createUser = async (user: IUser) => {
// 비밀번호 암호화 // 비밀번호 암호화
const hash = await bcrypt.hash(user.password, 10); const hash = await bcrypt.hash(user.password, 10);
const newUser = await User.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, email: user.email,
password: hash, password: hash,
name: user.name, role: userRole,
isNew: true,
}); });
return newUser; const retUser = await newUser.save();
return retUser;
}; };
export const findUserByEmail = async ( export const findUserByEmail = async (
...@@ -25,6 +34,11 @@ export const findUserByEmail = async ( ...@@ -25,6 +34,11 @@ export const findUserByEmail = async (
return user; return user;
}; };
export const getProfile = async (userId: string) => {
const profile = await User.findById(userId);
return profile; //이름 수정
};
export const getUsers = async () => { export const getUsers = async () => {
const users = await User.find({}); const users = await User.find({});
return users; return users;
...@@ -39,7 +53,11 @@ export const isUser = async (email: string) => { ...@@ -39,7 +53,11 @@ export const isUser = async (email: string) => {
} }
}; };
export const getProfile = async (userId : string) => { export const isValidUserId = async (userId: string) => {
const profile = await User.findById(userId) const user = await User.findById(userId);
return profile //이름 수정 if (user) {
} return true;
\ No newline at end of file } else {
return false;
}
};
export { default as User, IUser } from "./user.model"; export { default as User, IUser } from "./user.model";
export { default as Post, PostType } from "./post.model"; export { default as Post, PostType } from "./post.model";
export { default as Role } from "./role.model";
import { Document, model, Schema, Types } from "mongoose"; import { model, Schema, Types } from "mongoose";
import { Posting } from ".";
export interface PostType { export interface PostType {
title: string; title: string;
......
...@@ -5,9 +5,12 @@ interface IRole { ...@@ -5,9 +5,12 @@ interface IRole {
priority: number; priority: number;
} }
const schema = new Schema<IRole>({ const schema = new Schema<IRole>(
{
name: { type: String }, name: { type: String },
priority: { type: Number }, priority: { type: Number },
}); },
{ toJSON: { versionKey: false } }
);
export default model<IRole>("Role", schema); export default model<IRole>("Role", schema);
import express from "express";
import { authCtrl, roleCtrl } from "../controllers";
const router = express.Router();
router.all("/", authCtrl.requireLogin);
router.route("/").get(authCtrl.hasRole("admin"), roleCtrl.getRoles);
export default router;
...@@ -6,6 +6,6 @@ const router = express.Router(); ...@@ -6,6 +6,6 @@ const router = express.Router();
router router
.route("/") .route("/")
.get(authCtrl.requireLogin, userCtrl.getUsers) .get(authCtrl.requireLogin, userCtrl.getUsers)
.post(authCtrl.requireLogin, userCtrl.createUser); .post(authCtrl.requireLogin, authCtrl.hasRole("admin"), userCtrl.createUser);
export default router; export default router;
Markdown is supported
0% or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment