캠프그라운드 스키마에 'author' 프로퍼티 추가
데이터베이스에 저장시 author 항목 추가
새로운 캠핑장 생성시 추가한 유저의 이름 뜨게 만들기.
show.ejs에 유저네임 작성
다른 사용자가 생성한 캠핑장을 업데이트 하기 위해 Postman이나 Ajax로 요청을 보낼 수 있는 put,delete 라우트 사용 못하게 하기.
해당 유저를 찾고 (find) , 업데이트 가능한 자격인지 확인하고 (update) 즉 2단계에 걸쳐 진행.
DELETE,EDIT의 행위를 취하려는 유저의 id가 캠핑장을 애초에 추가한 유저의 아이디와 동일한지 확인. (equals)
미들웨어 파일에 정리하기
<middleware.js>
const { campgroundSchema, reviewSchema } = require('./schemas.js')
const ExpressError = require('./utils/ExpressError')
const Campground = require('./models/campground')
module.exports.validateCampground = (req, res, next) => {
const { error } = campgroundSchema.validate(req.body);
if (error) {
const msg = error.details.map(el => el.message).join(',')
throw new ExpressError(msg, 400)
} else {
next();
}
module.exports.isAuthor = async(req,res,next) => {
const { id } = req.params;
const campground = await Campground.findById(id)
if(!campground.author.equals(req.user._id)) {
req.flash('error', 'You dont have have permission to do that !')
return res.redirect(`/campgrounds/${id}`)
} next();
}
}
module.exports.isLoggedIn = (req, res, next) => {
if (!req.isAuthenticated()) {
req.session.returnTo = req.originalUrl
req.flash('error', 'You must be signed in first!');
return res.redirect('/login');
}
next();
}
module.exports.validateReview = (req, res, next) => {
const { error } = reviewSchema.validate(req.body);
if (error) {
const msg = error.details.map(el => el.message).join(',')
throw new ExpressError(msg, 400)
} else {
next();
}
}
<campgrounds.js>
const { isLoggedIn, isAuthor,validateCampground } = require('../middleware');
리뷰스키마에 author 프로퍼티 추가.
매 새로운 리뷰를 제각기 다른 유저가 작성시 리뷰를 작성한 유저 네임 출력하기.
delete 라우터에 미들웨어 추가하기
참고로 밑에처럼 미들웨어 코드 생성시 해당 모델을 먼저 소환해주고 코드를 짜야 한다.