Commit 894ded2b authored by Yoon, Daeki's avatar Yoon, Daeki 😅
Browse files

backend auth와 병합

parents 83daf4b0 417c92f8
...@@ -25,6 +25,15 @@ ...@@ -25,6 +25,15 @@
cd .. cd ..
``` ```
## DB 초기값 설정
앱에 필요한 기본 디비 테이블 및 초기값 생성
```bash
npx ts-node migrations\create.roles.ts
npx ts-node migrations\create.admin.ts
```
### 서버 실행 ### 서버 실행
1. 프론트엔드 서버 실행 1. 프론트엔드 서버 실행
......
import { connect } from "mongoose";
import { mongoUri } from "../src/config";
import { Role, User } from "../src/models";
import { userDb } from "../src/db";
const roles = [
["admin", 1],
["manager", 10],
["staff", 100],
["user", 1000],
["guest", 10000],
];
connect(mongoUri)
.then(async (mongoose) => {
const adminRole = await Role.findOne({ name: "admin" });
if (!adminRole) {
throw new Error("admin role이 없습니다. 먼저 role 테이블을 만드세요.");
}
await userDb.createUser({
email: "admin@example.com",
name: "admin",
role: adminRole?._id,
password: "asdfasdf",
});
console.log("admin 계정이 만들어졌습니다.");
await mongoose.disconnect();
})
.catch((error) => console.log("롤 초기 생성 에러", error));
import { connect } from "mongoose";
import { mongoUri } from "../src/config";
import { Role } from "../src/models";
const roles = [
["admin", 1],
["manager", 10],
["staff", 100],
["user", 1000],
["guest", 10000],
];
connect(mongoUri)
.then(async (mongoose) => {
const retRoles = roles.map(async ([name, priority]) => {
const result = await Role.create({ name, priority });
return result;
});
try {
await Promise.all(retRoles);
console.log("roles created successfully.");
} catch (error) {
console.log("error:", error);
} finally {
await mongoose.disconnect();
}
})
.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 { Files } from "formidable";
import { ObjectId } from "mongoose"; import { ObjectId } from "mongoose";
import { IUser, Post, User } from "../models"; import { IUser, Role, Post, 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 (
...@@ -31,6 +39,10 @@ export const findUserByPostId = async (postId: string) => { ...@@ -31,6 +39,10 @@ export const findUserByPostId = async (postId: string) => {
const post = await Post.findOne({ _id: postId }).populate("user"); const post = await Post.findOne({ _id: postId }).populate("user");
return post?.user; return post?.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({});
...@@ -46,9 +58,13 @@ export const isUser = async (email: string) => { ...@@ -46,9 +58,13 @@ 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;
} else {
return false;
}
}; };
export const postPicture = ( export const postPicture = (
......
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";
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 }, {
priority: { type: Number }, name: { type: String },
}); 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