환경변수.
git에 업로드 되면 안되는 state를
dotenv를 통해서 관리한다.
npm i dotenv
COOKIE_SECRET=sadfaw2432rf3r3fw4f5t34fwe23we
DB_URL=mongodb://127.0.0.1:27017/jmtube
GH_CLIENT=92bcfd75e0bd155308f8qwdfwe****
GH_SECRET=a4509e19b8c831238e4bf88e18d6195*&***
루트에 .env를 만들어서 주요한 환경변수들을 담아놓음.
그리고 gitignore에 .env를 포함시켜 준다.
git에 upload되면 않되기 때문에
import 'dotenv/config'
///npm i dotenv한 것을 위와 같은 형태로 불러준다.
import './db'
import Video from './models/Video'
import User from './models/User'
import express from 'express'
import session from 'express-session'
import MongoStore from 'connect-mongo'
import morgan from 'morgan'
import rootRouter from './routes/rootRouter'
import userRouter from './routes/userRouter'
import videoRouter from './routes/videoRouter'
import { localsMiddleware } from './middlewares'
const PORT = 4000
const app = express()
const logger = morgan('dev')
///GET, POST, status등의 상태를 보여주는 middleware
app.set('view engine', 'pug')
app.set('views', process.cwd() + '/src/views')
app.use(logger)
app.use(express.urlencoded({ extended: true }))
app.use(
session({
secret: process.env.COOKIE_SECRET,
///.env파일에 있는 COOKIE_SECRET 값을 이용함.
resave: false, //true하면 req요청때마다, cookie만듬, false는 login떄만 만듬
saveUninitialized: false,
///resave, saveUninitialized는 false로 해야
///로그인이 persist된다.
cookie: {
maxAge: 200000000000,
},
///cookie값이 지속되는 시간(대충 저정도면 1년지속됨.)
///web에서 F12 application으로 가면 session만료날짜 나옴.
store: MongoStore.create({ mongoUrl: process.env.DB_URL }),
///session을 save하는 장소, process.env.DB_URL을 이용함.
})
)
// app.use((req, res, next) => {
// res.locals.sexy = 'you' //pug파일에서 sexy로 접근가능
// res.locals.siteName = 'jmTube' //pug파일에서 siteName으로 접근가능
// console.log(res)
// res.sessionStore.all((error, sessions) => {
// console.log(sessions)
// next()
// })
// })
app.use(localsMiddleware)
app.use('/uploads', express.static('uploads'))
app.use('/', rootRouter)
app.use('/videos', videoRouter)
app.use('/users', userRouter)
app.listen(PORT, () => console.log('Server start in 4000'))
export const logout = (req, res) => {
req.session.destroy()
return res.redirect('/')
}
///session이 destroy되고, home path로 이동됨.
import express from 'express'
import {
finishGithubLogin,
getChangePassword,
getUserEdit,
logout,
postChangePassword,
postUserEdit,
seeUser,
startGithubLogin,
} from '../controllers/userController'
import {
avatarUpload,
protectorMiddleware,
publicOnlyMiddleware,
} from '../middlewares'
const userRouter = express.Router()
userRouter.get('/:id([0-9a-f]{24})', seeUser)
userRouter
.route('/edit')
.get(getUserEdit)
.all(protectorMiddleware)
.post(avatarUpload.single('avatar'), postUserEdit)
userRouter.get('/logout', logout)
///logout path로 req오면 userController의 logout 실행됨.
userRouter.get('/github/start', publicOnlyMiddleware, startGithubLogin)
userRouter.get('/github/finish', publicOnlyMiddleware, finishGithubLogin)
userRouter
.route('/change-password')
.all(protectorMiddleware)
.get(getChangePassword)
.post(postChangePassword)
export default userRouter
doctype html
html(lang="ko")
head
//block head
title #{pageTitle} | JmTube
link(rel="stylesheet" href="https://unpkg.com/mvp.css@1.12/mvp.css")
body
header
h1=pageTitle
nav
ul
li
a(href='/') Home
li
a(href='/search') Search
if loggedIn
li
a(href='/users/edit') Edit Profile
li
a(href='/users/logout') Logout
///Logout을 클릭하면,
///userController의 logout 함수가 작동되게 함.
li
a(href=`/users/${loggedInUser._id}`) #{loggedInUser.email}의 Profile
li
a(href='/videos/upload') Upload Video
else
li
a(href='/join') Join
li
a(href='/login') Login
main
block content
include partials/footer.pug