Commit d8de2d3f authored by 이재연's avatar 이재연
Browse files

No commit message

No commit message
parent ccc8f484
import React from 'react'; import React from 'react';
import { Navbar, Nav } from 'react-bootstrap'; import { Navbar, Nav } from 'react-bootstrap';
import { handleLogout, isAuthenticated } from '../utils/auth'; import { handleLogout, isAuthenticated, isAuthenticatedAdmin } from '../utils/auth';
function MainNav() { function MainNav() {
const user = isAuthenticated() const user = isAuthenticated()
const admin = isAuthenticatedAdmin()
return ( return (
<Navbar sticky="top" style={{ background: "#CDC5C2" }}> <Navbar sticky="top" style={{ background: "#CDC5C2" }}>
...@@ -13,7 +14,7 @@ function MainNav() { ...@@ -13,7 +14,7 @@ function MainNav() {
{' '}KU# {' '}KU#
</Navbar.Brand> </Navbar.Brand>
<Nav> <Nav>
{user ? <> <Nav.Link className="text-light" onClick={() => handleLogout()}>Logout</Nav.Link> {user,admin ? <> <Nav.Link className="text-light" onClick={() => handleLogout()}>Logout</Nav.Link>
<Nav.Link className="text-light" href="/account"> Mypage </Nav.Link> <Nav.Link className="text-light" href="/account"> Mypage </Nav.Link>
</> </>
: ( : (
...@@ -25,9 +26,13 @@ function MainNav() { ...@@ -25,9 +26,13 @@ function MainNav() {
<Nav.Link href="/shoppingcart"> <Nav.Link href="/shoppingcart">
<img alt="카트" src="/icon/cart.svg" width="30" height="30" /> <img alt="카트" src="/icon/cart.svg" width="30" height="30" />
</Nav.Link> </Nav.Link>
<Nav.Link href="/admin"> {admin ? <Nav.Link href="/admin">
<img alt="관리자" src="/icon/option.svg" width="30" height="30" /> <img alt="관리자" src="/icon/option.svg" width="30" height="30" />
</Nav.Link> </Nav.Link> :(
<>
</>
)}
</Nav> </Nav>
</Navbar> </Navbar>
) )
......
...@@ -97,7 +97,7 @@ function Account() { ...@@ -97,7 +97,7 @@ function Account() {
<Col md={5} className="d-flex align-content-center justify-content-center"> <Col md={5} className="d-flex align-content-center justify-content-center">
<Button variant="outline-light" onClick={handleShow}> <Button variant="outline-light" onClick={handleShow}>
{account.avatarUrl ? ( {account.avatarUrl ? (
<Image src={account.avatarUrl && `/image/${account.avatarUrl}`} className="img-thumbnail" <Image src={account.avatarUrl && `/images/${account.avatarUrl}`} className="img-thumbnail"
roundedCircle style={{ objectFit: "cover", width: "10rem", height: "10rem" }} /> roundedCircle style={{ objectFit: "cover", width: "10rem", height: "10rem" }} />
) : ( ) : (
<Image src="/icon/person.svg" className="img-thumbnail" <Image src="/icon/person.svg" className="img-thumbnail"
......
...@@ -3,7 +3,7 @@ import { Link, Redirect } from 'react-router-dom'; ...@@ -3,7 +3,7 @@ import { Link, Redirect } from 'react-router-dom';
import { Form, Col, Container, Button, Row, Alert } from 'react-bootstrap'; import { Form, Col, Container, Button, Row, Alert } from 'react-bootstrap';
import axios from 'axios' import axios from 'axios'
import catchErrors from '../utils/catchErrors' import catchErrors from '../utils/catchErrors'
import { handleLogin } from '../utils/auth' import { handleLogin, handleLoginAdmin } from '../utils/auth'
const INIT_USER = { const INIT_USER = {
...@@ -11,16 +11,23 @@ const INIT_USER = { ...@@ -11,16 +11,23 @@ const INIT_USER = {
password: '' password: ''
} }
const INIT_ADMIN = {
id: '',
password: ''
}
function Login() { function Login() {
const [validated, setValidated] = useState(false); const [validated, setValidated] = useState(false);
const [user, setUser] = useState(INIT_USER) const [user, setUser] = useState(INIT_USER)
const [error, setError] = useState('') const [error, setError] = useState('')
const [success, setSuccess] = useState(false) const [success, setSuccess] = useState(false)
const [admin, setAdmin] = useState(INIT_ADMIN)
function handleChange(event) { function handleChange(event) {
const { name, value } = event.target const { name, value } = event.target
setUser({ ...user, [name]: value }) setUser({ ...user, [name]: value })
setAdmin({ ...admin, [name]: value })
} }
...@@ -34,9 +41,13 @@ function Login() { ...@@ -34,9 +41,13 @@ function Login() {
setValidated(true); setValidated(true);
try { try {
setError('') setError('')
const response=await axios.post('/api/auth/login', user) if (user) {
handleLogin(response.data) const response = await axios.post('/api/auth/login', user)
setSuccess(true) handleLogin(response.data)
setSuccess(true)
}else{
return false
}
} catch (error) { } catch (error) {
catchErrors(error, setError) catchErrors(error, setError)
} }
...@@ -44,7 +55,7 @@ function Login() { ...@@ -44,7 +55,7 @@ function Login() {
if (success) { if (success) {
alert('로그인 되었습니다.') alert('로그인 되었습니다.')
window.location.href='/' window.location.href = '/'
} }
......
...@@ -114,7 +114,7 @@ function Product({ match, location }) { ...@@ -114,7 +114,7 @@ function Product({ match, location }) {
</style> </style>
<Row className="justify-content-center mt-5 mx-0"> <Row className="justify-content-center mt-5 mx-0">
<Col sm={11} md={4}> <Col sm={11} md={4}>
<img src={product.main_img} style={{ objectFit: "contain", width: "100%" }} /> <img src={`/images/${product.main_img}`} style={{ objectFit: "contain", width: "100%" }} />
</Col> </Col>
<Col sm={11} md={4} className="align-middle mt-4"> <Col sm={11} md={4} className="align-middle mt-4">
<h3 className="mb-4">{product.name}</h3> <h3 className="mb-4">{product.name}</h3>
......
...@@ -12,13 +12,15 @@ function ProductsList({ match }) { ...@@ -12,13 +12,15 @@ function ProductsList({ match }) {
const [mainCategory, setMainCategory] = useState(match.params.main.toUpperCase()) const [mainCategory, setMainCategory] = useState(match.params.main.toUpperCase())
const [subcategory, setSubcategory] = useState([]) const [subcategory, setSubcategory] = useState([])
const [productlist, setProductlist] = useState([]) const [productlist, setProductlist] = useState([])
const [bestlist, setBestlist] = useState([])
const [newlist, setNewlist] = useState([])
const [sub, setSub] = useState([]) const [sub, setSub] = useState([])
const [error, setError] = useState('') const [error, setError] = useState('')
// const user=isAuthenticated() // const user=isAuthenticated()
useEffect(() => { useEffect(() => {
getSubsCategories() // getSubsCategories()
getProductlist() getProductlist()
}, [mainCategory]) }, [mainCategory])
...@@ -44,15 +46,15 @@ function ProductsList({ match }) { ...@@ -44,15 +46,15 @@ function ProductsList({ match }) {
// e.preventDefault() // e.preventDefault()
// } // }
async function getSubsCategories() { // async function getSubsCategories() {
try { // try {
const response = await axios.get(`/api/categories/sub/${mainCategory}`) // const response = await axios.get(`/api/categories/sub/${mainCategory}`)
console.log("sub", response.data) // console.log("sub", response.data)
setSubcategory(response.data) // setSubcategory(response.data)
} catch (error) { // } catch (error) {
catchError(error, setError) // catchError(error, setError)
} // }
} // }
async function getProductlist() { async function getProductlist() {
try { try {
...@@ -79,6 +81,7 @@ function ProductsList({ match }) { ...@@ -79,6 +81,7 @@ function ProductsList({ match }) {
} }
} }
return ( return (
<div> <div>
{console.log("main=",mainCategory)} {console.log("main=",mainCategory)}
...@@ -114,8 +117,8 @@ function ProductsList({ match }) { ...@@ -114,8 +117,8 @@ function ProductsList({ match }) {
<Dropdown> <Dropdown>
<Dropdown.Toggle className="mx-2">정렬</Dropdown.Toggle> <Dropdown.Toggle className="mx-2">정렬</Dropdown.Toggle>
<Dropdown.Menu> <Dropdown.Menu>
<Dropdown.Item>인기상품</Dropdown.Item> <Dropdown.Item >인기상품</Dropdown.Item>
<Dropdown.Item>신상품</Dropdown.Item> <Dropdown.Item >신상품</Dropdown.Item>
<Dropdown.Item>낮은가격</Dropdown.Item> <Dropdown.Item>낮은가격</Dropdown.Item>
<Dropdown.Item>높은가격</Dropdown.Item> <Dropdown.Item>높은가격</Dropdown.Item>
</Dropdown.Menu> </Dropdown.Menu>
......
import axios from "axios" import axios from "axios"
export function handleLogin({userId,role,name}){ export function handleLogin({userId,adminId,role,name}){
localStorage.setItem('id',userId) localStorage.setItem('id',userId)
localStorage.setItem('role',role) localStorage.setItem('role',role)
localStorage.setItem('name',name) localStorage.setItem('name',name)
localStorage.setItem('adminId',adminId)
} }
export async function handleLogout(){ export async function handleLogout(){
localStorage.removeItem('id') localStorage.removeItem('id')
localStorage.removeItem('role') localStorage.removeItem('role')
localStorage.removeItem('name') localStorage.removeItem('name')
await axios.get('/api/auth/logout') localStorage.removeItem('adminId')
localStorage.removeItem('adminrole')
localStorage.removeItem('adminname')
await axios.get('/api/auth/logout')
window.location.href = '/' window.location.href = '/'
} }
export function isAuthenticatedAdmin(){
const adminId= localStorage.getItem('adminId')
if(adminId){
return adminId
} else {
return false
}
}
export function isAuthenticated(){ export function isAuthenticated(){
const userId= localStorage.getItem('id') const userId= localStorage.getItem('id')
if(userId){ if(userId){
......
...@@ -5,15 +5,16 @@ import config from '../config.js' ...@@ -5,15 +5,16 @@ import config from '../config.js'
const login = async (req, res) => { const login = async (req, res) => {
const { id, password } = req.body const { id, password } = req.body
console.log(id, password)
console.log(req.body)
try { try {
const user = await User.findOne({ id }).select('password role name') const user = await User.findOne({role:"user",id:id}).select('password name')
console.log('u=', user) console.log('u=', user)
if (!user) { if (!user) {
return res.status(404).send(`${id}가 존재하지 않습니다.`) return res.status(404).send(`${user.id}가 존재하지 않습니다.`)
} }
const passwordMatch = await bcrypt.compare(password, user.password) const passwordMatch = await bcrypt.compare(password, user.password)
if (passwordMatch) { if (passwordMatch) {
const token = jwt.sign({ userId: user._id }, config.jwtSecret, { const token = jwt.sign({ userId: user._id }, config.jwtSecret, {
expiresIn: '3d' expiresIn: '3d'
...@@ -34,9 +35,47 @@ const login = async (req, res) => { ...@@ -34,9 +35,47 @@ const login = async (req, res) => {
} }
} }
const admin = (req, res) => {
try {
res.json(admin)
} catch (error) {
res.status(500).send('다시 시도하세요.')
}
}
const adminId = async (req, res, next, admin) => {
try {
const admin = await User.findOne({ role: "admin" }).select('id password role name')
console.log('a=',admin)
if (!admin) {
res.status(404).send(`${id}가 존재하지 않습니다.`)
}
const adminpasswordMatch = await bcrypt.compare(password, admin.password)
if (adminpasswordMatch) {
const token = jwt.sign({ adminId: admin.id }, config.jwtSecret, {
expiresIn: '3d'
})
res.cookie('token', token, {
maxAge: config.cookieMaxAge,
httpOnly: true,
secure: config.env === 'production'
})
res.json({ adminId: admin.id, role: admin.role, name: admin.name })
}else {
res.status(401).send('비밀번호가 일치하지 않습니다.')
}
req.admin = admin
next()
} catch (error) {
res.status(500).send('로그인 실패. 다시 시도하세요.')
}
}
const logout = (req, res) => { const logout = (req, res) => {
res.clearCookie('token') res.clearCookie('token')
res.send('로그아웃 되었습니다.') res.send('로그아웃 되었습니다.')
} }
export default { login, logout }
\ No newline at end of file export default { login, logout, admin, adminId }
\ No newline at end of file
...@@ -11,16 +11,15 @@ const getCategory = async (req, res) => { ...@@ -11,16 +11,15 @@ const getCategory = async (req, res) => {
} }
} }
const getSubCategory=(req,res)=>{ // const getSubCategory=(req,res)=>{
} // }
const getsubId=(req,res,next,sub)=>{ // const getsubId=(req,res,next,sub)=>{
const subcategory = await category.find({"Dress"}) // console.log('sub=',sub)
console.log('sub=',sub)
next() // next()
} // }
export default { getCategory , getsubId, getSubCategory} export default { getCategory }
\ No newline at end of file \ No newline at end of file
...@@ -6,10 +6,10 @@ const upload = multer({ dest: 'uploads/' }) ...@@ -6,10 +6,10 @@ const upload = multer({ dest: 'uploads/' })
const imageUpload = upload.fields([ const imageUpload = upload.fields([
{ name: 'main_image' }, { name: 'main_image' },
{ name: 'detail_image' } { name: 'detail_image' }
]) ])
const regist = async (req, res) => { const regist = async (req, res) => {
console.log("req.body=",req.body) console.log("req.body=", req.body)
try { try {
const { pro_name, price, stock, main_category, sub_category, description, colors, sizes } = req.body const { pro_name, price, stock, main_category, sub_category, description, colors, sizes } = req.body
const main_img = req.files['main_image'][0] const main_img = req.files['main_image'][0]
...@@ -33,15 +33,28 @@ const getToHome = async (res, req) => { ...@@ -33,15 +33,28 @@ const getToHome = async (res, req) => {
try { try {
const bestProduct = await Product.find({}).sort({ purchase: 1 }).limit(6) const bestProduct = await Product.find({}).sort({ purchase: 1 }).limit(6)
const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6) const newProduct = await Product.find({}).sort({ createdAt: -1 }).limit(6)
console.log("best=",bestProduct) console.log("best=", bestProduct)
console.log("new=",newProduct) console.log("new=", newProduct)
res.json(bestProduct, newProduct) res.json(bestProduct, newProduct)
} catch { } catch {
res.status(500).send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
} }
} }
const getlist=(req,res)=>{ const Sortlist = async (res, req) => {
try {
const newlist = await Product.find({}).sort({ createdAt: -1 })
const bestlist = await Product.find({}).sort({ purchase: 1 })
console.log('bestsort',bestlist)
console.log('newlist',newlist)
res.json(newlist, bestlist)
} catch {
res.status(500).send('상품을 불러오지 못했습니다.')
}
}
const getlist = (req, res) => {
try { try {
res.json(req.productslist) res.json(req.productslist)
} catch (error) { } catch (error) {
...@@ -52,7 +65,7 @@ const getlist=(req,res)=>{ ...@@ -52,7 +65,7 @@ const getlist=(req,res)=>{
const categoryId = async (req, res, next, category) => { const categoryId = async (req, res, next, category) => {
try { try {
const productslist = await Product.find({main_category: category}) const productslist = await Product.find({ main_category: category })
if (!productslist) { if (!productslist) {
res.status(404).send('상품을 찾을 수 없습니다.') res.status(404).send('상품을 찾을 수 없습니다.')
} }
...@@ -63,16 +76,16 @@ const categoryId = async (req, res, next, category) => { ...@@ -63,16 +76,16 @@ const categoryId = async (req, res, next, category) => {
} }
} }
const subgetlist=(req,res)=>{ const subgetlist = (req, res) => {
try{ try {
res.json(req.subproductslist) res.json(req.subproductslist)
}catch(error){ } catch (error) {
res.status(500).send('상품을 불러오지 못했습니다.') res.status(500).send('상품을 불러오지 못했습니다.')
} }
} }
const subcategoryId = async (req, res, next, subcategory) => { const subcategoryId = async (req, res, next, subcategory) => {
try { try {
const subproductslist = await Product.find({sub_category:subcategory}) const subproductslist = await Product.find({ sub_category: subcategory })
if (!subproductslist) { if (!subproductslist) {
res.status(404).send('상품을 찾을 수 없습니다.') res.status(404).send('상품을 찾을 수 없습니다.')
} }
...@@ -83,4 +96,4 @@ const subcategoryId = async (req, res, next, subcategory) => { ...@@ -83,4 +96,4 @@ const subcategoryId = async (req, res, next, subcategory) => {
} }
} }
export default { imageUpload, regist, categoryId, getlist, subcategoryId, subgetlist } export default { imageUpload, regist, categoryId, getlist, subcategoryId, subgetlist, getToHome , Sortlist}
...@@ -9,4 +9,9 @@ router.route('/login') ...@@ -9,4 +9,9 @@ router.route('/login')
router.route('/logout') router.route('/logout')
.get(authCtrl.logout) .get(authCtrl.logout)
router.route('/admin/:admin')
.post(authCtrl.admin)
router.param('admin',authCtrl.adminId)
export default router export default router
\ No newline at end of file
...@@ -6,9 +6,9 @@ const router = express.Router() ...@@ -6,9 +6,9 @@ const router = express.Router()
router.route('/main') router.route('/main')
.get(categoryCtrl.getCategory) .get(categoryCtrl.getCategory)
router.route('/sub/:sub') // router.route('/sub/:sub')
.get(categoryCtrl.getSubCategory) // .get(categoryCtrl.getSubCategory)
router.param('sub',categoryCtrl.getsubId) // router.param('sub',categoryCtrl.getsubId)
export default router export default router
\ No newline at end of file
...@@ -4,6 +4,9 @@ import productCtrl from '../controllers/product.controller.js'; ...@@ -4,6 +4,9 @@ import productCtrl from '../controllers/product.controller.js';
const router = express.Router() const router = express.Router()
router.route('/sort')
.get(productCtrl.Sortlist)
router.route('/regist') router.route('/regist')
.post(productCtrl.imageUpload, productCtrl.regist) .post(productCtrl.imageUpload, productCtrl.regist)
......
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